Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(web): clarify App modes and scope workflow editor resources (#44171)
yyh8aa1fe96abc2
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 5617d5905b2..ab179df165e 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -2487,11 +2487,6 @@"count": 1}},- "web/app/components/workflow/hooks/use-inspect-vars-crud-common.ts": {- "typescript/no-explicit-any": {- "count": 1- }- },"web/app/components/workflow/hooks/use-serial-async-callback.ts": {"typescript/no-explicit-any": {"count": 1@@ -2787,7 +2782,7 @@"count": 1},"typescript/no-explicit-any": {- "count": 21+ "count": 20}},"web/app/components/workflow/nodes/_base/hooks/use-output-var-list.ts": {@@ -4250,11 +4245,6 @@"count": 1}},- "web/service/use-flow.ts": {- "eslint-react/no-unnecessary-use-prefix": {- "count": 1- }- },"web/service/use-log.ts": {"@tanstack/query/prefer-query-options": {"count": 7@@ -4333,13 +4323,13 @@},"web/service/use-workflow.ts": {"@tanstack/query/prefer-query-options": {- "count": 9+ "count": 6},"no-restricted-imports": {"count": 1},"typescript/no-explicit-any": {- "count": 3+ "count": 1}},"web/service/use-workspace.ts": {@@ -4380,7 +4370,7 @@},"web/types/workflow.ts": {"typescript/no-explicit-any": {- "count": 17+ "count": 16}},"web/utils/completion-params.spec.ts": {@@ -4423,4 +4413,4 @@"count": 2}}-}+}\ No newline at end of filediff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsxindex 12f6dc08fa0..6f626b14ee8 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/__tests__/layout-main.spec.tsx@@ -9,7 +9,6 @@ import {seedAppDetail,} from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import AppDetailLayout from '../layout-main'@@ -63,7 +62,7 @@ const createAppDetail = (overrides: Partial<AppDetailWithSite> = {}) =>createAppDetailFixture({id: 'app-1',name: 'Demo App',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.ViewLayout, AppACLPermission.Monitor],...overrides,})@@ -148,15 +147,15 @@ describe('AppDetailLayout', () => {describe('Document title', () => {it.each([- ['/app/app-1/workflow', 'common.appMenus.promptEng', AppModeEnum.WORKFLOW],- ['/app/app-1/configuration', 'common.appMenus.promptEng', AppModeEnum.CHAT],- ['/app/app-1/access-point', 'common.appMenus.accessPoint', AppModeEnum.WORKFLOW],- ['/app/app-1/deploy', 'common.appMenus.deploy', AppModeEnum.WORKFLOW],- ['/app/app-1/logs', 'common.appMenus.logs', AppModeEnum.WORKFLOW],- ['/app/app-1/annotations', 'common.appMenus.annotations', AppModeEnum.CHAT],- ['/app/app-1/overview', 'common.appMenus.overview', AppModeEnum.WORKFLOW],- ['/app/app-1/access-config', 'navigation.settings.resourceAccess', AppModeEnum.WORKFLOW],- ])('identifies the current detail page for %s', async (pathname, pageTitle, mode) => {+ ['/app/app-1/workflow', 'common.appMenus.promptEng', 'workflow'],+ ['/app/app-1/configuration', 'common.appMenus.promptEng', 'chat'],+ ['/app/app-1/access-point', 'common.appMenus.accessPoint', 'workflow'],+ ['/app/app-1/deploy', 'common.appMenus.deploy', 'workflow'],+ ['/app/app-1/logs', 'common.appMenus.logs', 'workflow'],+ ['/app/app-1/annotations', 'common.appMenus.annotations', 'chat'],+ ['/app/app-1/overview', 'common.appMenus.overview', 'workflow'],+ ['/app/app-1/access-config', 'navigation.settings.resourceAccess', 'workflow'],+ ] as const)('identifies the current detail page for %s', async (pathname, pageTitle, mode) => {mockPathname = pathnamemockAppResponse.mockResolvedValue(createAppDetail({@@ -543,7 +542,7 @@ describe('AppDetailLayout', () => {mockPathname = '/app/app-1/access-config'mockAppResponse.mockResolvedValue(createAppDetail({- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,bound_agent_id: 'agent-1',permission_keys: [AppACLPermission.AccessConfig],}),@@ -570,7 +569,7 @@ describe('AppDetailLayout', () => {</AppDetailLayout>,{cachedAppDetail: createAppDetail({- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,bound_agent_id: 'agent-1',permission_keys: [AppACLPermission.AccessConfig],}),@@ -608,7 +607,7 @@ describe('AppDetailLayout', () => {mockPathname = '/app/app-1/annotations'mockAppResponse.mockResolvedValue(createAppDetail({- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.Monitor],}),)@@ -629,7 +628,7 @@ describe('AppDetailLayout', () => {mockPathname = '/app/app-1/annotations'mockAppResponse.mockResolvedValue(createAppDetail({- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.LogAndAnnotation],}),)diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsxindex f582fbe49fc..8a6121f65f1 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx@@ -20,7 +20,6 @@ import useDocumentTitle from '@/hooks/use-document-title'import { redirect, usePathname } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { isNotFoundError } from '@/service/http-error'-import { AppModeEnum } from '@/types/app'import { getRedirectionPath } from '@/utils/app-redirection'import { getAppACLCapabilities } from '@/utils/permission'@@ -51,8 +50,7 @@ const getAppDetailRedirectPath = (permissionOptions: ResourceMaintainerPermissionOptions,) => {const appACLCapabilities = getAppACLCapabilities(appDetail.permission_keys, permissionOptions)- const isWorkflowApp =- appDetail.mode === AppModeEnum.WORKFLOW || appDetail.mode === AppModeEnum.ADVANCED_CHAT+ const isWorkflowApp = appDetail.mode === 'workflow' || appDetail.mode === 'advanced-chat'const isLayoutPath = pathname.endsWith('configuration') || pathname.endsWith('workflow')const isLogsPath = pathname.endsWith('logs')const isAnnotationsPath = pathname.endsWith('annotations')@@ -65,8 +63,7 @@ const getAppDetailRedirectPath = ((isLogsPath && !appACLCapabilities.canAccessLogAndAnnotation) ||(isAnnotationsPath && !appACLCapabilities.canAccessLogAndAnnotation) ||(isOverviewPath && !appACLCapabilities.canMonitor) ||- (isAccessConfigPath &&- (appDetail.mode === AppModeEnum.AGENT || !appACLCapabilities.canAccessConfig)) ||+ (isAccessConfigPath && (appDetail.mode === 'agent' || !appACLCapabilities.canAccessConfig)) ||(isAccessPointPath && !appACLCapabilities.canViewAccessPoint) ||(isDeployPath && (!isWorkflowApp || !appACLCapabilities.canDeploy)))diff --git a/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsx b/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsxindex c2197c8c4d0..1e669cdaadb 100644--- a/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsx+++ b/web/app/components/app-sidebar/__tests__/app-detail-section.spec.tsx@@ -3,7 +3,6 @@ import { screen } from '@testing-library/react'import { consoleQuery } from '@/service/console'import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import AppDetailSection from '../app-detail-section'@@ -221,18 +220,18 @@ describe('AppDetailSection', () => {it.each([{label: 'the app is not a workflow app',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permissionKeys: [AppACLPermission.Deploy],},{label: 'app deploy ACL permission is missing',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permissionKeys: [AppACLPermission.Monitor],},- ])('should hide deploy navigation when $label', ({ mode, permissionKeys }) => {+ ] as const)('should hide deploy navigation when $label', ({ mode, permissionKeys }) => {// ArrangemockAppMode = mode- mockAppPermissionKeys = permissionKeys+ mockAppPermissionKeys = [...permissionKeys]// Actrender(<AppDetailSection />)@@ -241,7 +240,7 @@ describe('AppDetailSection', () => {expect(screen.queryByRole('link', { name: 'common.appMenus.deploy' })).not.toBeInTheDocument()})- it.each([AppModeEnum.CHAT, AppModeEnum.AGENT_CHAT])(+ it.each(['chat', 'agent-chat'] as const)('should render resource access navigation for %s apps when app access config permission is granted',(mode) => {// Arrange@@ -263,7 +262,7 @@ describe('AppDetailSection', () => {it('should hide resource access navigation for Agent apps', () => {// Arrange- mockAppMode = AppModeEnum.AGENT+ mockAppMode = 'agent'mockAppPermissionKeys = [AppACLPermission.AccessConfig]// Actdiff --git a/web/app/components/app-sidebar/app-detail-section.tsx b/web/app/components/app-sidebar/app-detail-section.tsxindex 5f0e5eab6d6..a4c1cfbf7df 100644--- a/web/app/components/app-sidebar/app-detail-section.tsx+++ b/web/app/components/app-sidebar/app-detail-section.tsx@@ -13,7 +13,6 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { usePathname } from '@/next/navigation'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { getAppACLCapabilities } from '@/utils/permission'import { AppInfoView } from './app-info'import AppInfoHeader from './app-info/app-info-header'@@ -71,11 +70,9 @@ function AppDetailContent({ appId, expand }: { appId: string; expand: boolean })if (!appDetail || !systemFeatures || !currentUserId) return []const appId = appDetail.id- const isWorkflowApp =- appDetail.mode === AppModeEnum.WORKFLOW || appDetail.mode === AppModeEnum.ADVANCED_CHAT- const supportsAnnotations =- appDetail.mode !== AppModeEnum.WORKFLOW && appDetail.mode !== AppModeEnum.COMPLETION- const supportsResourceAccess = appDetail.mode !== AppModeEnum.AGENT+ const isWorkflowApp = appDetail.mode === 'workflow' || appDetail.mode === 'advanced-chat'+ const supportsAnnotations = appDetail.mode !== 'workflow' && appDetail.mode !== 'completion'+ const supportsResourceAccess = appDetail.mode !== 'agent'const appACLCapabilities = getAppACLCapabilities(appDetail.permission_keys, {currentUserId,resourceMaintainer: appDetail.maintainer,diff --git a/web/app/components/app-sidebar/app-info/__tests__/app-info-modals.spec.tsx b/web/app/components/app-sidebar/app-info/__tests__/app-info-modals.spec.tsxindex 898248457f0..4b79b467b23 100644--- a/web/app/components/app-sidebar/app-info/__tests__/app-info-modals.spec.tsx+++ b/web/app/components/app-sidebar/app-info/__tests__/app-info-modals.spec.tsx@@ -3,7 +3,6 @@ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import AppInfoModals from '../app-info-modals'vi.mock('next/dynamic', () => ({@@ -112,7 +111,7 @@ const createAppDetail = (overrides: Partial<AppDetailWithSite> = {}) =>createAppDetailFixture({id: 'app-1',name: 'Test App',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,icon: '🤖',icon_type: 'emoji',icon_background: '#FFEAD5',diff --git a/web/app/components/app-sidebar/app-info/__tests__/app-info-trigger.spec.tsx b/web/app/components/app-sidebar/app-info/__tests__/app-info-trigger.spec.tsxindex ba63d3a1973..c60c4c63fc2 100644--- a/web/app/components/app-sidebar/app-info/__tests__/app-info-trigger.spec.tsx+++ b/web/app/components/app-sidebar/app-info/__tests__/app-info-trigger.spec.tsx@@ -5,7 +5,6 @@ import * as React from 'react'import { createAccountProfileQueryWrapper } from '@/test/console/account-profile'import { render as renderWithConsoleState } from '@/test/console/render'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import AppInfoTrigger from '../app-info-trigger'@@ -41,7 +40,7 @@ const createAppDetail = (overrides: Partial<AppDetailWithSite> = {}) =>createAppDetailFixture({id: 'app-1',name: 'Test App',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,icon: '🤖',icon_type: 'emoji',icon_background: '#FFEAD5',@@ -74,7 +73,7 @@ describe('AppInfoTrigger', () => {it('renders expanded app metadata without making the app info clickable', async () => {const user = userEvent.setup()const props = createProps({- appDetail: createAppDetail({ name: 'My Chatbot', mode: AppModeEnum.ADVANCED_CHAT }),+ appDetail: createAppDetail({ name: 'My Chatbot', mode: 'advanced-chat' as const }),})render(<AppInfoTrigger {...props} />)@@ -119,7 +118,7 @@ describe('AppInfoTrigger', () => {it('shows import DSL for workflow apps without a workflow conversion operation', async () => {const user = userEvent.setup()const props = createProps({- appDetail: createAppDetail({ mode: AppModeEnum.WORKFLOW }),+ appDetail: createAppDetail({ mode: 'workflow' as const }),})render(<AppInfoTrigger {...props} />)diff --git a/web/app/components/app-sidebar/app-info/__tests__/app-mode-labels.spec.ts b/web/app/components/app-sidebar/app-info/__tests__/app-mode-labels.spec.tsindex e954621d001..a31b6fa7d03 100644--- a/web/app/components/app-sidebar/app-info/__tests__/app-mode-labels.spec.ts+++ b/web/app/components/app-sidebar/app-info/__tests__/app-mode-labels.spec.ts@@ -1,6 +1,5 @@import type { TFunction } from 'i18next'import { withSelectorKey } from '@/test/i18n-mock'-import { AppModeEnum } from '@/types/app'import { getAppModeLabel } from '../app-mode-labels'describe('getAppModeLabel', () => {@@ -10,19 +9,19 @@ describe('getAppModeLabel', () => {}, 'app') as unknown as TFunction<['app']>it('should return advanced chat label', () => {- expect(getAppModeLabel(AppModeEnum.ADVANCED_CHAT, t)).toBe('app.types.advanced')+ expect(getAppModeLabel('advanced-chat', t)).toBe('app.types.advanced')})it('should return agent chat label', () => {- expect(getAppModeLabel(AppModeEnum.AGENT_CHAT, t)).toBe('app.types.agent')+ expect(getAppModeLabel('agent-chat', t)).toBe('app.types.agent')})it('should return chatbot label', () => {- expect(getAppModeLabel(AppModeEnum.CHAT, t)).toBe('app.types.chatbot')+ expect(getAppModeLabel('chat', t)).toBe('app.types.chatbot')})it('should return completion label', () => {- expect(getAppModeLabel(AppModeEnum.COMPLETION, t)).toBe('app.types.completion')+ expect(getAppModeLabel('completion', t)).toBe('app.types.completion')})it('should return workflow label for unknown mode', () => {@@ -30,6 +29,6 @@ describe('getAppModeLabel', () => {})it('should return workflow label for workflow mode', () => {- expect(getAppModeLabel(AppModeEnum.WORKFLOW, t)).toBe('app.types.workflow')+ expect(getAppModeLabel('workflow', t)).toBe('app.types.workflow')})})diff --git a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.tsindex 8f7c63d1afd..013ba7ae1a2 100644--- a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts+++ b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts@@ -3,7 +3,6 @@ import { act, waitFor } from '@testing-library/react'import { consoleQuery } from '@/service/console'import { createConsoleQueryClient, renderHookWithConsoleQuery } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'import { useAppInfoActions } from '../use-app-info-actions'@@ -140,7 +139,7 @@ describe('useAppInfoActions', () => {mockAppDetail = createAppDetailFixture({id: 'app-1',name: 'Test App',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,icon: '🤖',icon_type: 'emoji',icon_background: '#FFEAD5',@@ -370,7 +369,7 @@ describe('useAppInfoActions', () => {})it('should open export warning modal for workflow mode', async () => {- mockAppDetail = createAppDetailFixture({ ...mockAppDetail, mode: AppModeEnum.WORKFLOW })+ mockAppDetail = createAppDetailFixture({ ...mockAppDetail, mode: 'workflow' as const })const { result } = renderActions()@@ -382,7 +381,7 @@ describe('useAppInfoActions', () => {})it('should open export warning modal for advanced_chat mode', async () => {- mockAppDetail = createAppDetailFixture({ ...mockAppDetail, mode: AppModeEnum.ADVANCED_CHAT })+ mockAppDetail = createAppDetailFixture({ ...mockAppDetail, mode: 'advanced-chat' as const })const { result } = renderActions()@@ -396,7 +395,7 @@ describe('useAppInfoActions', () => {describe('handleConfirmExport', () => {it('keeps the warning open after failure so the user can retry', async () => {- mockAppDetail = createAppDetailFixture({ ...mockAppDetail, mode: AppModeEnum.WORKFLOW })+ mockAppDetail = createAppDetailFixture({ ...mockAppDetail, mode: 'workflow' as const })mockExportWorkflowAppDsl.mockResolvedValueOnce({ status: 'failed' }).mockResolvedValueOnce({ status: 'downloaded' })@@ -415,7 +414,7 @@ describe('useAppInfoActions', () => {})it('should export directly when no secret env variables', async () => {- mockAppDetail = createAppDetailFixture({ ...mockAppDetail, mode: AppModeEnum.WORKFLOW })+ mockAppDetail = createAppDetailFixture({ ...mockAppDetail, mode: 'workflow' as const })const { result } = renderActions()await act(async () => {@@ -429,7 +428,7 @@ describe('useAppInfoActions', () => {})it('should set secret env list when secret variables exist', async () => {- mockAppDetail = createAppDetailFixture({ ...mockAppDetail, mode: AppModeEnum.WORKFLOW })+ mockAppDetail = createAppDetailFixture({ ...mockAppDetail, mode: 'workflow' as const })const secretVars = [{ value_type: 'secret', name: 'API_KEY', value: 'secret' }]mockExportWorkflowAppDsl.mockResolvedValue({status: 'confirmation-required',diff --git a/web/app/components/app-sidebar/app-info/app-info-trigger.tsx b/web/app/components/app-sidebar/app-info/app-info-trigger.tsxindex ac08c9ff877..c30ef4cbdb9 100644--- a/web/app/components/app-sidebar/app-info/app-info-trigger.tsx+++ b/web/app/components/app-sidebar/app-info/app-info-trigger.tsx@@ -7,7 +7,6 @@ import * as React from 'react'import { useTranslation } from 'react-i18next'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'-import { AppModeEnum } from '@/types/app'import { getAppACLCapabilities, hasPermission } from '@/utils/permission'import AppInfoHeader from './app-info-header'import { getAppModeLabel } from './app-mode-labels'@@ -74,7 +73,7 @@ const AppInfoTrigger = ({]: []),...(appACLCapabilities.canImportExportDSL &&- (appDetail.mode === AppModeEnum.ADVANCED_CHAT || appDetail.mode === AppModeEnum.WORKFLOW)+ (appDetail.mode === 'advanced-chat' || appDetail.mode === 'workflow')? [{id: 'import',@@ -99,8 +98,7 @@ const AppInfoTrigger = ({: []const workflowConversionOperations: Operation[] =- appACLCapabilities.canEdit &&- (appDetail.mode === AppModeEnum.COMPLETION || appDetail.mode === AppModeEnum.CHAT)+ appACLCapabilities.canEdit && (appDetail.mode === 'completion' || appDetail.mode === 'chat')? [{id: 'switch',diff --git a/web/app/components/app-sidebar/app-info/app-mode-labels.ts b/web/app/components/app-sidebar/app-info/app-mode-labels.tsindex 260ff3b95e5..101cea4c930 100644--- a/web/app/components/app-sidebar/app-info/app-mode-labels.ts+++ b/web/app/components/app-sidebar/app-info/app-mode-labels.ts@@ -1,15 +1,14 @@import type { TFunction } from 'i18next'-import { AppModeEnum } from '@/types/app'export function getAppModeLabel(mode: string, t: TFunction<['app']>): string {switch (mode) {- case AppModeEnum.ADVANCED_CHAT:+ case 'advanced-chat':return t(($) => $['types.advanced'], { ns: 'app' })- case AppModeEnum.AGENT_CHAT:+ case 'agent-chat':return t(($) => $['types.agent'], { ns: 'app' })- case AppModeEnum.CHAT:+ case 'chat':return t(($) => $['types.chatbot'], { ns: 'app' })- case AppModeEnum.COMPLETION:+ case 'completion':return t(($) => $['types.completion'], { ns: 'app' })default:return t(($) => $['types.workflow'], { ns: 'app' })diff --git a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts b/web/app/components/app-sidebar/app-info/use-app-info-actions.tsindex 7b3e48f8b3f..39629dde37f 100644--- a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts+++ b/web/app/components/app-sidebar/app-info/use-app-info-actions.ts@@ -17,7 +17,6 @@ import {markAppDeletionSucceeded,} from '@/service/app-deletion'import { consoleClient, consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'export type AppInfoModalType =@@ -234,7 +233,7 @@ export function useAppInfoActions({const exportCheck = useCallback(async () => {if (isExporting) return- if (appMode !== AppModeEnum.WORKFLOW && appMode !== AppModeEnum.ADVANCED_CHAT) {+ if (appMode !== 'workflow' && appMode !== 'advanced-chat') {onExport()return}diff --git a/web/app/components/app/access-config/__tests__/index.spec.tsx b/web/app/components/app/access-config/__tests__/index.spec.tsxindex f77c906df52..957f347bffa 100644--- a/web/app/components/app/access-config/__tests__/index.spec.tsx+++ b/web/app/components/app/access-config/__tests__/index.spec.tsx@@ -10,7 +10,6 @@ import {import { consoleQuery } from '@/service/console'import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import AppAccessConfigPage from '../index'@@ -375,7 +374,7 @@ describe('AppAccessConfigPage', () => {it('should not mount access config data hooks for Agent apps', () => {appDetail = createAppDetailFixture({id: 'app-1',- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,maintainer: 'account-1',permission_keys: [AppACLPermission.AccessConfig],})diff --git a/web/app/components/app/access-config/index.tsx b/web/app/components/app/access-config/index.tsxindex 1088e44fbfe..ec7416a0154 100644--- a/web/app/components/app/access-config/index.tsx+++ b/web/app/components/app/access-config/index.tsx@@ -23,7 +23,6 @@ import {useUpdateAppUserAccessSettings,} from '@/service/access-control/use-app-access-config'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { getAppACLCapabilities } from '@/utils/permission'type AppAccessConfigPageProps = {@@ -265,7 +264,7 @@ const AppAccessConfigPage = ({ appId }: AppAccessConfigPageProps) => {],)- if (appDetail.mode === AppModeEnum.AGENT || !appACLCapabilities.canAccessConfig) return null+ if (appDetail.mode === 'agent' || !appACLCapabilities.canAccessConfig) return nullreturn <AppAccessConfigContent appId={appId} maintainerId={appDetail.maintainer} />}diff --git a/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx b/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsxindex 1f2b648bebf..74bf32fe3ef 100644--- a/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx+++ b/web/app/components/app/access-point/__tests__/built-in-access-points.spec.tsx@@ -1,5 +1,5 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { ReactElement } from 'react'-import type { AppModeEnum } from '@/types/app'import { screen } from '@testing-library/react'import { consoleQuery } from '@/service/console'import { createHttpError } from '@/service/http-error'@@ -43,7 +43,7 @@ function render(ui: ReactElement) {queryClient.setQueryData(['system-features'], { webapp_auth: { enabled: true } })queryClient.setQueryData(consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),- createAppDetailFixture({ ...mocks.appInfo, mode: mocks.appInfo.mode as AppModeEnum }),+ createAppDetailFixture({ ...mocks.appInfo, mode: mocks.appInfo.mode as AppMode }),)return renderWithConsole(ui, { wrapper: createQueryClientWrapper(queryClient) })}diff --git a/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx b/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsxindex e47bb6b609e..c2d8588b87b 100644--- a/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx+++ b/web/app/components/app/access-point/__tests__/environment-access-point-cards.spec.tsx@@ -1,3 +1,4 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { ReactElement } from 'react'import { screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'@@ -9,7 +10,6 @@ import { QueryClientTestProvider } from '@/test/console/query-provider'import { render } from '@/test/console/render'import { createAppDetailFixture, createAppSiteFixture } from '@/test/fixtures/app'import { createTestQueryClient } from '@/test/query-client'-import { AppModeEnum } from '@/types/app'import { EnvironmentServiceApiCard } from '../deployed-environment-access-points/environment-service-api-card'import { EnvironmentWebAppCard } from '../deployed-environment-access-points/environment-web-app-card'@@ -32,7 +32,7 @@ vi.mock('@/features/system-features/client', () => ({}),}))-let mockAppMode: AppModeEnum = AppModeEnum.WORKFLOW+let mockAppMode: AppMode = 'workflow'vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.example.test/en${path}`,@@ -149,7 +149,7 @@ describe('environment access point cards', () => {beforeEach(() => {vi.clearAllMocks()mocks.saveSiteConfig.mockResolvedValue(true)- mockAppMode = AppModeEnum.WORKFLOW+ mockAppMode = 'workflow'vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => {const request = new Request(input, init)const path = new URL(request.url).pathname@@ -247,7 +247,7 @@ describe('environment access point cards', () => {)it('sends a chatflow app to the chat web app shell', async () => {- mockAppMode = AppModeEnum.ADVANCED_CHAT+ mockAppMode = 'advanced-chat'renderCard(<EnvironmentWebAppCard appId="app-1" environmentId="staging" canManageAccessPoint />)diff --git a/web/app/components/app/access-point/__tests__/index.spec.tsx b/web/app/components/app/access-point/__tests__/index.spec.tsxindex bdc3b28e15b..5ea1a003da9 100644--- a/web/app/components/app/access-point/__tests__/index.spec.tsx+++ b/web/app/components/app/access-point/__tests__/index.spec.tsx@@ -1,3 +1,4 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { AppEnvironment } from '@dify/contracts/enterprise-app-deploy/types.gen'import type { ReactNode } from 'react'import type { AccessPoint as AccessPointType } from '@/app/components/app/deploy/utils/access-point'@@ -11,11 +12,10 @@ import { QueryClientTestProvider } from '@/test/console/query-provider'import { render } from '@/test/console/render'import { createAppDetailFixture } from '@/test/fixtures/app'import { createTestQueryClient } from '@/test/query-client'-import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import AccessPoint from '..'-let appMode: AppModeEnum = AppModeEnum.WORKFLOW+let appMode: AppMode = 'workflow'let appPermissionKeys: string[] = [AppACLPermission.AccessPointView]const accessPointMocks = vi.hoisted(() => ({builtIn: vi.fn(),@@ -133,7 +133,7 @@ const renderAccessPoint = ({describe('AccessPoint', () => {beforeEach(() => {vi.clearAllMocks()- appMode = AppModeEnum.WORKFLOW+ appMode = 'workflow'appPermissionKeys = [AppACLPermission.AccessPointView]})@@ -243,7 +243,7 @@ describe('AccessPoint', () => {})it('hides environment tabs for app types without multi-environment support', () => {- appMode = AppModeEnum.CHAT+ appMode = 'chat'renderAccessPoint()diff --git a/web/app/components/app/access-point/__tests__/mcp-card.spec.tsx b/web/app/components/app/access-point/__tests__/mcp-card.spec.tsxindex 4fd5ec63630..c5582800c69 100644--- a/web/app/components/app/access-point/__tests__/mcp-card.spec.tsx+++ b/web/app/components/app/access-point/__tests__/mcp-card.spec.tsx@@ -8,7 +8,6 @@ import { toast } from '@/app/notifications'import { render } from '@/test/console/render'import { createAppDetailFixture, createAppModelConfigFixture } from '@/test/fixtures/app'import { createTestQueryClient } from '@/test/query-client'-import { AppModeEnum } from '@/types/app'import { MCPAccessPointCard } from '../built-in-access-points/mcp-card'const mocks = vi.hoisted(() => ({@@ -65,7 +64,7 @@ vi.mock('@/app/components/tools/mcp/mcp-server-modal', () => ({const appInfo = createAppDetailFixture({api_base_url: 'https://api.example.test/v1',id: 'app-1',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,model_config: createAppModelConfigFixture({updated_at: 1_710_000_000,user_input_form: [@@ -82,7 +81,7 @@ const appInfo = createAppDetailFixture({const workflowAppInfo = createAppDetailFixture({...appInfo,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,model_config: null,})diff --git a/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx b/web/app/components/app/access-point/__tests__/service-api-card.spec.tsxindex 48624195066..e5b6805ee09 100644--- a/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx+++ b/web/app/components/app/access-point/__tests__/service-api-card.spec.tsx@@ -1,4 +1,4 @@-import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'+import type { AppDetailWithSite, AppMode } from '@dify/contracts/api/console/apps/types.gen'import { QueryClientProvider, useSuspenseQuery } from '@tanstack/react-query'import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'@@ -7,7 +7,6 @@ import { consoleQuery } from '@/service/console'import { render } from '@/test/console/render'import { createAppDetailFixture } from '@/test/fixtures/app'import { createTestQueryClient } from '@/test/query-client'-import { AppModeEnum } from '@/types/app'import { ServiceApiAccessPointCard } from '../built-in-access-points/service-api-card'const mocks = vi.hoisted(() => ({@@ -53,7 +52,7 @@ vi.mock('../built-in-access-points/api-secret-key-button', () => ({}))function createAppInfo(- mode: AppModeEnum,+ mode: AppMode,overrides: Partial<AppDetailWithSite> = {},): AppDetailWithSite {return createAppDetailFixture({@@ -66,7 +65,7 @@ function createAppInfo(}function renderCard(- mode: AppModeEnum,+ mode: AppMode,availability: 'available' | 'loading' | 'unavailable' = 'available',canManage = true,overrides: Partial<AppDetailWithSite> = {},@@ -124,12 +123,12 @@ describe('ServiceApiAccessPointCard', () => {})it.each([- [AppModeEnum.ADVANCED_CHAT, '/api-reference/guides/chatflow'],- [AppModeEnum.WORKFLOW, '/api-reference/guides/workflow'],- [AppModeEnum.CHAT, '/api-reference/guides/chat'],- [AppModeEnum.AGENT_CHAT, '/api-reference/guides/chat'],- [AppModeEnum.COMPLETION, '/api-reference/guides/completion'],- ])('links %s apps to the matching external API reference', (mode, path) => {+ ['advanced-chat', '/api-reference/guides/chatflow'],+ ['workflow', '/api-reference/guides/workflow'],+ ['chat', '/api-reference/guides/chat'],+ ['agent-chat', '/api-reference/guides/chat'],+ ['completion', '/api-reference/guides/completion'],+ ] as const)('links %s apps to the matching external API reference', (mode, path) => {renderCard(mode)const apiReferenceLink = screen.getByRole('link', { name: /apiInfo\.doc/ })@@ -141,7 +140,7 @@ describe('ServiceApiAccessPointCard', () => {it('updates API status through the generated contract', async () => {const user = userEvent.setup()- renderCard(AppModeEnum.WORKFLOW)+ renderCard('workflow')await user.click(screen.getByRole('switch'))@@ -154,7 +153,7 @@ describe('ServiceApiAccessPointCard', () => {})it('shows loading without reporting an environment failure', () => {- renderCard(AppModeEnum.WORKFLOW, 'loading')+ renderCard('workflow', 'loading')const card = screen.getByRole('region', { name: /serviceApi\.title/ })expect(card).toHaveAttribute('aria-busy', 'true')@@ -165,7 +164,7 @@ describe('ServiceApiAccessPointCard', () => {})it('keeps API keys and external documentation available when the API is stopped', () => {- renderCard(AppModeEnum.WORKFLOW, 'available', true, { enable_api: false })+ renderCard('workflow', 'available', true, { enable_api: false })expect(screen.getByRole('button', { name: 'api-secret-keys' })).toBeEnabled()const apiReferenceLink = screen.getByRole('link', { name: /apiInfo\.doc/ })@@ -176,14 +175,14 @@ describe('ServiceApiAccessPointCard', () => {})it('disables API management without Access Point management permission', () => {- renderCard(AppModeEnum.WORKFLOW, 'available', false)+ renderCard('workflow', 'available', false)expect(screen.getByRole('button', { name: 'api-secret-keys' })).toBeDisabled()expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')})it('disables API keys and external documentation when the access point is unavailable', () => {- renderCard(AppModeEnum.WORKFLOW, 'unavailable')+ renderCard('workflow', 'unavailable')expect(screen.getByRole('button', { name: 'api-secret-keys' })).toBeDisabled()expect(screen.getByRole('button', { name: /apiInfo\.doc/ })).toBeDisabled()@@ -193,7 +192,7 @@ describe('ServiceApiAccessPointCard', () => {const user = userEvent.setup()const toggle = createDeferredPromise<{ enable_api: boolean }>()mocks.apiEnable.mockReturnValueOnce(toggle.promise)- renderCard(AppModeEnum.WORKFLOW)+ renderCard('workflow')const accessSwitch = screen.getByRole('switch')await user.click(accessSwitch)@@ -212,7 +211,7 @@ describe('ServiceApiAccessPointCard', () => {it('keeps successful status changes silent', async () => {const user = userEvent.setup()mocks.apiEnable.mockResolvedValueOnce(createAppDetailFixture({ enable_api: false }))- renderCard(AppModeEnum.WORKFLOW)+ renderCard('workflow')const accessSwitch = screen.getByRole('switch')await user.click(accessSwitch)diff --git a/web/app/components/app/access-point/__tests__/trigger-card.spec.tsx b/web/app/components/app/access-point/__tests__/trigger-card.spec.tsxindex a0d9de65e82..d478942b42e 100644--- a/web/app/components/app/access-point/__tests__/trigger-card.spec.tsx+++ b/web/app/components/app/access-point/__tests__/trigger-card.spec.tsx@@ -6,7 +6,6 @@ import { toast } from '@/app/notifications'import { render } from '@/test/console/render'import { createAppDetailFixture } from '@/test/fixtures/app'import { createTestQueryClient } from '@/test/query-client'-import { AppModeEnum } from '@/types/app'import { TriggerAccessPointCard } from '../built-in-access-points/trigger-card'const mocks = vi.hoisted(() => ({@@ -71,7 +70,7 @@ vi.mock('@/app/components/workflow/block-icon', () => ({const appInfo = createAppDetailFixture({id: 'app-1',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,})function createTrigger(id: string, status: AppTrigger['status']): AppTrigger {diff --git a/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx b/web/app/components/app/access-point/__tests__/web-app-card.spec.tsxindex 622a800cb8b..911c054d2f4 100644--- a/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx+++ b/web/app/components/app/access-point/__tests__/web-app-card.spec.tsx@@ -1,4 +1,8 @@-import type { AppDetailWithSite, AppSiteResponse } from '@dify/contracts/api/console/apps/types.gen'+import type {+ AppDetailWithSite,+ AppMode,+ AppSiteResponse,+} from '@dify/contracts/api/console/apps/types.gen'import type { PublishedWorkflow } from '../shared/utils'import type { InputVar, Node } from '@/app/components/workflow/types'import { QueryClientProvider, useSuspenseQuery } from '@tanstack/react-query'@@ -12,7 +16,6 @@ import { seedAccountProfileQuery } from '@/test/console/account-profile'import { render } from '@/test/console/render'import { createAppDetailFixture, createAppSiteFixture } from '@/test/fixtures/app'import { createTestQueryClient } from '@/test/query-client'-import { AppModeEnum } from '@/types/app'import { basePath } from '@/utils/var'import { WebAppAccessPointCard } from '../built-in-access-points/web-app-card'@@ -92,7 +95,7 @@ vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.example.test/en${path}`,}))-function createAppInfo(mode: AppModeEnum): AppDetailWithSite {+function createAppInfo(mode: AppMode): AppDetailWithSite {return createAppDetailFixture({access_mode: AccessMode.PUBLIC,api_base_url: 'https://api.example.test/v1',@@ -111,7 +114,7 @@ function createAppInfo(mode: AppModeEnum): AppDetailWithSite {}function renderCard(- mode: AppModeEnum,+ mode: AppMode,availability: 'available' | 'loading' | 'unavailable' = 'available',workflow?: PublishedWorkflow,{@@ -259,7 +262,7 @@ describe('WebAppAccessPointCard', () => {})it('disables site actions when the app has no site', () => {- renderCard(AppModeEnum.CHAT, 'available', undefined, { appOverrides: { site: null } })+ renderCard('chat', 'available', undefined, { appOverrides: { site: null } })expect(screen.getByRole('button', { name: /settings\.settings/ })).toBeDisabled()expect(@@ -272,7 +275,7 @@ describe('WebAppAccessPointCard', () => {})it('does not present an unknown access mode as public or allow launching', () => {- renderCard(AppModeEnum.CHAT, 'available', undefined, { accessMode: null })+ renderCard('chat', 'available', undefined, { accessMode: null })expect(screen.queryByRole('button', { name: /accessControlDialog\.accessItems\.anyone/ }),@@ -287,7 +290,7 @@ describe('WebAppAccessPointCard', () => {})it('shows the current access mode without a redundant section label', () => {- renderCard(AppModeEnum.CHAT)+ renderCard('chat')expect(screen.queryByText(/publishApp\.title/)).not.toBeInTheDocument()expect(@@ -298,7 +301,7 @@ describe('WebAppAccessPointCard', () => {it('disables Open and explains when the user cannot access the Web App', async () => {const user = userEvent.setup()mocks.getUserCanAccess.mockResolvedValue({ result: false })- renderCard(AppModeEnum.WORKFLOW, 'available', undefined, {+ renderCard('workflow', 'available', undefined, {accessMode: AccessMode.SPECIFIC_GROUPS_MEMBERS,})@@ -319,7 +322,7 @@ describe('WebAppAccessPointCard', () => {it('keeps Open disabled until access is granted', async () => {const permission = createDeferredPromise<{ result: boolean }>()mocks.getUserCanAccess.mockReturnValueOnce(permission.promise)- renderCard(AppModeEnum.WORKFLOW)+ renderCard('workflow')expect(screen.getByRole('button', { name: /studio\.accessPoint\.open/ })).toHaveAttribute('aria-disabled',@@ -336,7 +339,7 @@ describe('WebAppAccessPointCard', () => {it('allows opening external-member Web Apps independently of platform access', () => {mocks.getUserCanAccess.mockResolvedValue({ result: false })- renderCard(AppModeEnum.WORKFLOW, 'available', undefined, {+ renderCard('workflow', 'available', undefined, {accessMode: AccessMode.EXTERNAL_MEMBERS,})@@ -347,7 +350,7 @@ describe('WebAppAccessPointCard', () => {})it('allows opening Web Apps without querying permissions when access control is disabled', () => {- renderCard(AppModeEnum.CHAT, 'available', undefined, { showAccessControl: false })+ renderCard('chat', 'available', undefined, { showAccessControl: false })expect(screen.getByRole('link', { name: /studio\.accessPoint\.open/ })).toHaveAttribute('href',@@ -359,7 +362,7 @@ describe('WebAppAccessPointCard', () => {it('updates Open after saving Web App access permissions', async () => {const user = userEvent.setup()mocks.getUserCanAccess.mockResolvedValue({ result: false })- renderCard(AppModeEnum.CHAT, 'available', undefined, {+ renderCard('chat', 'available', undefined, {accessMode: AccessMode.SPECIFIC_GROUPS_MEMBERS,})@@ -380,7 +383,7 @@ describe('WebAppAccessPointCard', () => {)})- it.each([AppModeEnum.WORKFLOW, AppModeEnum.COMPLETION])(+ it.each(['workflow', 'completion'] as const)('does not offer Embed into site for %s apps',(mode) => {renderCard(mode)@@ -393,7 +396,7 @@ describe('WebAppAccessPointCard', () => {it('keeps Embed into site for non-workflow Web apps', async () => {const user = userEvent.setup()- renderCard(AppModeEnum.CHAT)+ renderCard('chat')await user.click(screen.getByRole('button', { name: /embedIntoSite/ }))@@ -404,7 +407,7 @@ describe('WebAppAccessPointCard', () => {it('updates site status through the generated contract', async () => {const user = userEvent.setup()- renderCard(AppModeEnum.CHAT)+ renderCard('chat')await user.click(screen.getByRole('switch'))@@ -418,7 +421,7 @@ describe('WebAppAccessPointCard', () => {it('keeps site status changes behind Access Point management permission', async () => {const user = userEvent.setup()- renderCard(AppModeEnum.CHAT, 'available', undefined, { canManageAccessPoint: false })+ renderCard('chat', 'available', undefined, { canManageAccessPoint: false })await user.click(screen.getByRole('switch'))@@ -429,7 +432,7 @@ describe('WebAppAccessPointCard', () => {const user = userEvent.setup()const refresh = createDeferredPromise<AppDetailWithSite | null>()mocks.getAppDetail.mockReturnValueOnce(refresh.promise)- renderCard(AppModeEnum.CHAT)+ renderCard('chat')await user.click(screen.getByRole('button', { name: /overview\.appInfo\.regenerate/ }))await user.click(screen.getByRole('button', { name: /operation\.confirm/ }))@@ -456,7 +459,7 @@ describe('WebAppAccessPointCard', () => {const user = userEvent.setup()const error = new Error('request failed')mocks.siteEnable.mockRejectedValueOnce(error)- renderCard(AppModeEnum.CHAT)+ renderCard('chat')await user.click(screen.getByRole('switch'))@@ -467,7 +470,7 @@ describe('WebAppAccessPointCard', () => {it('passes hidden Chatflow inputs to the embed dialog', async () => {const user = userEvent.setup()- renderCard(AppModeEnum.ADVANCED_CHAT, 'available', workflowWithHiddenInput)+ renderCard('advanced-chat', 'available', workflowWithHiddenInput)await user.click(screen.getByRole('button', { name: /embedIntoSite/ }))@@ -478,7 +481,7 @@ describe('WebAppAccessPointCard', () => {it('configures hidden workflow inputs before opening the Web App', async () => {const user = userEvent.setup()const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null)- renderCard(AppModeEnum.WORKFLOW, 'available', workflowWithHiddenInput)+ renderCard('workflow', 'available', workflowWithHiddenInput)await user.click(screen.getByRole('button', { name: /operation\.config/ }))await user.type(screen.getByLabelText('Secret'), 'top-secret')@@ -496,7 +499,7 @@ describe('WebAppAccessPointCard', () => {const user = userEvent.setup()const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null)mocks.getUserCanAccess.mockResolvedValue({ result: false })- renderCard(AppModeEnum.WORKFLOW, 'available', workflowWithHiddenInput, {+ renderCard('workflow', 'available', workflowWithHiddenInput, {accessMode: AccessMode.SPECIFIC_GROUPS_MEMBERS,})@@ -514,7 +517,7 @@ describe('WebAppAccessPointCard', () => {})it('shows loading without reporting an environment failure', () => {- renderCard(AppModeEnum.WORKFLOW, 'loading')+ renderCard('workflow', 'loading')const card = screen.getByRole('region', { name: /webApp\.title/ })expect(card).toHaveAttribute('aria-busy', 'true')@@ -525,7 +528,7 @@ describe('WebAppAccessPointCard', () => {})it('does not announce an unavailable access control entry as loading', () => {- renderCard(AppModeEnum.WORKFLOW, 'unavailable')+ renderCard('workflow', 'unavailable')const card = screen.getByRole('region', { name: /webApp\.title/ })expect(within(card).queryByRole('status', { name: 'common.loading' })).not.toBeInTheDocument()@@ -538,7 +541,7 @@ describe('WebAppAccessPointCard', () => {mocks.siteEnable.mockReturnValueOnce(firstToggle.promise).mockReturnValueOnce(secondToggle.promise)- renderCard(AppModeEnum.CHAT)+ renderCard('chat')const accessSwitch = screen.getByRole('switch')await user.click(accessSwitch)@@ -573,7 +576,7 @@ describe('WebAppAccessPointCard', () => {it('disables Web App management actions without Access Point management', async () => {const user = userEvent.setup()- renderCard(AppModeEnum.CHAT, 'available', undefined, { canManageAccessPoint: false })+ renderCard('chat', 'available', undefined, { canManageAccessPoint: false })expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')expect(screen.getByRole('button', { name: /embedIntoSite/ })).toBeDisabled()diff --git a/web/app/components/app/access-point/built-in-access-points/mcp-card.tsx b/web/app/components/app/access-point/built-in-access-points/mcp-card.tsxindex 5e2c4f5ae08..c88200249e4 100644--- a/web/app/components/app/access-point/built-in-access-points/mcp-card.tsx+++ b/web/app/components/app/access-point/built-in-access-points/mcp-card.tsx@@ -26,7 +26,6 @@ import {useMCPServerDetail,useRefreshMCPServerCode,} from '@/service/use-tools'-import { AppModeEnum } from '@/types/app'import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label'import { getPublishedWorkflowNodes, isAdvancedApp } from '../shared/utils'@@ -50,7 +49,7 @@ export function MCPAccessPointCard({const { t } = useTranslation(['appOverview', 'common', 'deployments', 'tools'])const advancedApp = isAdvancedApp(appInfo)const basicApp = !advancedApp- const workflowApp = appInfo.mode === AppModeEnum.WORKFLOW+ const workflowApp = appInfo.mode === 'workflow'const [showServerModal, setShowServerModal] = useState(false)const [showRegenerate, setShowRegenerate] = useState(false)const basicConfig = appInfo.model_configdiff --git a/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx b/web/app/components/app/access-point/built-in-access-points/web-app-card.tsxindex 724a989abcd..7e0acf7845d 100644--- a/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx+++ b/web/app/components/app/access-point/built-in-access-points/web-app-card.tsx@@ -37,7 +37,6 @@ import {useGetUserCanAccessApp,} from '@/service/access-control/use-app-access-control'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { useAccessPointStatusLabel } from '../shared/use-access-point-status-label'import { getBuiltInAccessUrls, getHiddenStartInputs } from '../shared/utils'import {@@ -122,8 +121,7 @@ export function WebAppAccessPointCard({: appInfo.enable_siteconst running = siteAvailability === 'available' && optimisticEnabledconst actionsAvailable = running && Boolean(webAppUrl) && !toggleSiteMutation.isPending- const supportsEmbedded =- appInfo.mode !== AppModeEnum.COMPLETION && appInfo.mode !== AppModeEnum.WORKFLOW+ const supportsEmbedded = appInfo.mode !== 'completion' && appInfo.mode !== 'workflow'const hiddenLaunchVariables = getHiddenStartInputs(workflow)const { data: accessSubjects } = useAppWhiteListSubjects(appInfo.id,@@ -220,9 +218,7 @@ export function WebAppAccessPointCard({/><SettingsDialogkey={appInfo.id}- isChat={- appInfo.mode !== AppModeEnum.COMPLETION && appInfo.mode !== AppModeEnum.WORKFLOW- }+ isChat={appInfo.mode !== 'completion' && appInfo.mode !== 'workflow'}canDeploy={canDeploy}appInfo={site ? { id: appInfo.id, mode: appInfo.mode, site } : undefined}disabled={siteAvailability !== 'available' || !canManageAccessPoint}diff --git a/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-utils.ts b/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-utils.tsindex 0f11f208586..9a914a81f70 100644--- a/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-utils.ts+++ b/web/app/components/app/access-point/deployed-environment-access-points/environment-web-app-utils.ts@@ -1,10 +1,9 @@import type { EnvironmentSite } from '@dify/contracts/enterprise-app-deploy/types.gen'-import { AppModeEnum } from '@/types/app'import { basePath } from '@/utils/var'export function getEnvironmentWebAppUrl(site?: EnvironmentSite, mode?: string) {if (!site?.app_base_url || !site.code) return ''- const route = mode === AppModeEnum.ADVANCED_CHAT ? 'chat' : 'workflow'+ const route = mode === 'advanced-chat' ? 'chat' : 'workflow'return `${site.app_base_url.replace(/\/$/, '')}${basePath}/environment/${route}/${site.code}`}diff --git a/web/app/components/app/access-point/index.tsx b/web/app/components/app/access-point/index.tsxindex 5d4465e0ce6..c20ab19dec0 100644--- a/web/app/components/app/access-point/index.tsx+++ b/web/app/components/app/access-point/index.tsx@@ -16,7 +16,6 @@ import { ACCESS_POINT_ORDER } from '@/app/components/app/deploy/utils/access-poiimport { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { getAppACLCapabilities } from '@/utils/permission'import { BuiltInAccessPoints } from './built-in-access-points'import { DeployedEnvironmentAccessPoints } from './deployed-environment-access-points'@@ -162,7 +161,7 @@ export default function AccessPoint({ appId }: AccessPointProps) {workspacePermissionKeys,})const showEnvironmentTabs =- (appDetail?.mode === AppModeEnum.WORKFLOW || appDetail?.mode === AppModeEnum.ADVANCED_CHAT) &&+ (appDetail?.mode === 'workflow' || appDetail?.mode === 'advanced-chat') &&capabilities.canViewAccessPointreturn (diff --git a/web/app/components/app/access-point/shared/utils.ts b/web/app/components/app/access-point/shared/utils.tsindex 53b147a581f..a554ca268af 100644--- a/web/app/components/app/access-point/shared/utils.ts+++ b/web/app/components/app/access-point/shared/utils.ts@@ -5,7 +5,6 @@ import type {import type { InputVar, Node } from '@/app/components/workflow/types'import type { DocPathWithoutLang } from '@/types/doc-paths'import { BlockEnum, isTriggerNode } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import { basePath } from '@/utils/var'export type PublishedWorkflow = WorkflowResponse | null | undefined@@ -25,7 +24,7 @@ export function getAppApiReferencePath(appMode: AppDetailWithSite['mode']) {}export function getPublishedWorkflowState(appInfo: AppDetailWithSite, workflow: PublishedWorkflow) {- const isWorkflowApp = appInfo.mode === AppModeEnum.WORKFLOW+ const isWorkflowApp = appInfo.mode === 'workflow'const nodes = getPublishedWorkflowNodes(workflow)const hasStartNode = nodes.some((node) => node.data.type === BlockEnum.Start)const hasTriggerNode = nodes.some((node) => isTriggerNode(node.data.type))@@ -46,9 +45,7 @@ export function getPublishedWorkflowNodes(workflow: PublishedWorkflow) {export function getBuiltInAccessUrls(appInfo: AppDetailWithSite) {const appMode =- appInfo.mode === AppModeEnum.COMPLETION || appInfo.mode === AppModeEnum.WORKFLOW- ? appInfo.mode- : AppModeEnum.CHAT+ appInfo.mode === 'completion' || appInfo.mode === 'workflow' ? appInfo.mode : 'chat'return {api: appInfo.api_base_url ?? '',@@ -69,5 +66,5 @@ export function getHiddenStartInputs(workflow: PublishedWorkflow) {}export function isAdvancedApp(appInfo: AppDetailWithSite) {- return appInfo.mode === AppModeEnum.WORKFLOW || appInfo.mode === AppModeEnum.ADVANCED_CHAT+ return appInfo.mode === 'workflow' || appInfo.mode === 'advanced-chat'}diff --git a/web/app/components/app/annotation/__tests__/index.spec.tsx b/web/app/components/app/annotation/__tests__/index.spec.tsxindex b919d82bd65..6a10430d40c 100644--- a/web/app/components/app/annotation/__tests__/index.spec.tsx+++ b/web/app/components/app/annotation/__tests__/index.spec.tsx@@ -17,7 +17,6 @@ import {} from '@/service/annotation'import { renderWithConsoleQuery } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import Annotation from '../index'import { AnnotationEnableStatus, JobStatus } from '../type'@@ -181,7 +180,7 @@ const updateAnnotationStatusMock = updateAnnotationStatus as Mockconst appDetail = createAppDetailFixture({id: 'app-id',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})const createAnnotation = (overrides: Partial<AnnotationItem> = {}): AnnotationItem => ({diff --git a/web/app/components/app/annotation/index.tsx b/web/app/components/app/annotation/index.tsxindex 148e57122ec..8f7ad84a322 100644--- a/web/app/components/app/annotation/index.tsx+++ b/web/app/components/app/annotation/index.tsx@@ -35,7 +35,6 @@ import {updateAnnotationStatus,} from '@/service/annotation'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { sleep } from '@/utils'import PageTitle from '../log-annotation/page-title'import EmptyElement from './empty-element'@@ -55,7 +54,7 @@ const Annotation: FC<Props> = (props) => {const docLink = useDocLink()const [isShowEdit, setIsShowEdit] = useState(false)const [annotationConfig, setAnnotationConfig] = useState<AnnotationReplyConfig | null>(null)- const [isChatApp] = useState(appDetail.mode !== AppModeEnum.COMPLETION)+ const [isChatApp] = useState(appDetail.mode !== 'completion')const [controlRefreshSwitch, setControlRefreshSwitch] = useState(() => Date.now())const deploymentEdition = useAtomValue(deploymentEditionAtom)const { data: annotationQuota } = useQuery(diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsxindex dcb0abf3421..b2c76e2b488 100644--- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx@@ -11,7 +11,6 @@ import {renderWithConsoleQuery as renderWithQuery,} from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import { basePath } from '@/utils/var'import { AppPublisher } from '../index'@@ -269,7 +268,7 @@ describe('AppPublisher', () => {mockAppDetail = {id: 'app-1',name: 'Demo App',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,maintainer: 'user-2',permission_keys: [],access_mode: AccessMode.SPECIFIC_GROUPS_MEMBERS,@@ -346,7 +345,7 @@ describe('AppPublisher', () => {const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.Deploy],}mockOnPublish.mockResolvedValue(undefined)@@ -398,7 +397,7 @@ describe('AppPublisher', () => {const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [],}mockOnPublish.mockResolvedValue(undefined)@@ -423,7 +422,7 @@ describe('AppPublisher', () => {const user = userEvent.setup()mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,}mockPublishedWorkflow = {created_at: Math.floor(Date.now() / 1000),@@ -458,7 +457,7 @@ describe('AppPublisher', () => {expect(mockUpdateWorkflow).toHaveBeenCalledWith({appId: 'app-1',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,url: '/apps/app-1/workflows/workflow-version-5',title: 'Release 6',releaseNotes: 'Updated notes',@@ -480,7 +479,7 @@ describe('AppPublisher', () => {const queryClient = createConsoleQueryClient()mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.Deploy],}const environmentsQuery =@@ -513,7 +512,7 @@ describe('AppPublisher', () => {it('should keep the workflow publisher single-environment without app deploy ACL', () => {mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [],}@@ -581,7 +580,7 @@ describe('AppPublisher', () => {}mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.Deploy],}const environmentsQuery =@@ -684,7 +683,7 @@ describe('AppPublisher', () => {const detailRequests: Request[] = []mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.Deploy],}const environmentsQuery =@@ -832,7 +831,7 @@ describe('AppPublisher', () => {it('should keep workflow tool drawer mounted after closing the publish popover', () => {mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,}render(<AppPublisher appId="app-1" publishedAt={Date.now()} toolPublished />)@@ -853,7 +852,7 @@ describe('AppPublisher', () => {it('should show one success toast when automatically publishing a workflow tool', async () => {mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,}mockOnPublish.mockImplementation(async (_params, options?: { showSuccessToast?: boolean }) => {if (options?.showSuccessToast !== false) mockToastSuccess('common.api.actionSuccess')@@ -876,7 +875,7 @@ describe('AppPublisher', () => {it('should not show a success toast when workflow tool creation fails after publishing', async () => {mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,}mockOnPublish.mockImplementation(async (_params, options?: { showSuccessToast?: boolean }) => {if (options?.showSuccessToast !== false) mockToastSuccess('common.api.actionSuccess')@@ -900,7 +899,7 @@ describe('AppPublisher', () => {const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined)mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,}mockOnPublish.mockRejectedValueOnce(new Error('publish failed'))@@ -922,7 +921,7 @@ describe('AppPublisher', () => {mockWorkspacePermissionKeys = []mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,}render(<AppPublisher appId="app-1" publishedAt={Date.now()} />)@@ -1066,7 +1065,7 @@ describe('AppPublisher', () => {const user = userEvent.setup()mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,}mockPublishedWorkflow = {created_at: 1_710_000_100,@@ -1102,7 +1101,7 @@ describe('AppPublisher', () => {}mockAppDetail = {...mockAppDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,}mockFetchPublishedWorkflow.mockResolvedValue({created_at: 1_710_000_300,diff --git a/web/app/components/app/app-publisher/__tests__/publisher-panel.spec.tsx b/web/app/components/app/app-publisher/__tests__/publisher-panel.spec.tsxindex b9196155f7e..157daebc275 100644--- a/web/app/components/app/app-publisher/__tests__/publisher-panel.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/publisher-panel.spec.tsx@@ -2,7 +2,6 @@ import { detectPlatform } from '@tanstack/react-hotkeys'import { act, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'-import { AppModeEnum } from '@/types/app'import { PublisherPanel } from '../publisher-content/publisher-panel'vi.mock('../environment-deployment-flow', () => ({@@ -38,7 +37,7 @@ function PublisherPanelHarness({builtInPublisher={{actions: {appId: 'app-1',- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,appURL: 'https://example.com/app',canViewAccessPoint: false,disabledFunctionButton: false,diff --git a/web/app/components/app/app-publisher/__tests__/sections.spec.tsx b/web/app/components/app/app-publisher/__tests__/sections.spec.tsxindex 7acbe20d41c..080cb1a10d2 100644--- a/web/app/components/app/app-publisher/__tests__/sections.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/sections.spec.tsx@@ -8,7 +8,6 @@ import { useRef } from 'react'import { expectLoadingButton } from '@/test/button'import { createConsoleQueryWrapper } from '@/test/console/query-data'import { render as renderWithConsoleState } from '@/test/console/render'-import { AppModeEnum } from '@/types/app'import { PublisherActionsSection } from '../built-in-publisher/actions-section'import { PublisherSummarySection } from '../built-in-publisher/summary-section'import { usePublishController } from '../publisher-content/use-publish-controller'@@ -82,7 +81,7 @@ function PublisherPopup({function PublishingPopup({ onPublish }: { onPublish: () => Promise<void> }) {const publish = usePublishController({- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,supportsMultiEnvironment: false,onClose: () => {},onPublish,@@ -535,7 +534,7 @@ describe('app-publisher sections', () => {render(<PublisherActionsSectionappId={'workflow-app'}- appMode={AppModeEnum.WORKFLOW}+ appMode={'workflow'}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButton={false}@@ -595,7 +594,7 @@ describe('app-publisher sections', () => {render(<PublisherActionsSectionappId={'workflow-app'}- appMode={AppModeEnum.WORKFLOW}+ appMode={'workflow'}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButton={false}@@ -626,7 +625,7 @@ describe('app-publisher sections', () => {it('should show the disabled reason below setup and configured workflow tool actions', () => {const commonProps = {appId: 'workflow-app',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,appURL: 'https://example.com/app',canViewAccessPoint: true,disabledFunctionButton: false,@@ -666,7 +665,7 @@ describe('app-publisher sections', () => {const onConfigureWorkflowTool = vi.fn()const commonProps = {appId: 'workflow-app',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,appURL: 'https://example.com/app',canViewAccessPoint: true,disabledFunctionButton: false,@@ -710,7 +709,7 @@ describe('app-publisher sections', () => {render(<PublisherActionsSectionappId={'trigger-app'}- appMode={AppModeEnum.WORKFLOW}+ appMode={'workflow'}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButton={false}@@ -740,7 +739,7 @@ describe('app-publisher sections', () => {render(<PublisherActionsSectionappId={'workflow-app'}- appMode={AppModeEnum.WORKFLOW}+ appMode={'workflow'}appURL="https://example.com/app"canViewAccessPoint={false}disabledFunctionButton={false}@@ -765,7 +764,7 @@ describe('app-publisher sections', () => {render(<PublisherActionsSectionappId={'workflow-app'}- appMode={AppModeEnum.WORKFLOW}+ appMode={'workflow'}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButton@@ -795,7 +794,7 @@ describe('app-publisher sections', () => {render(<PublisherActionsSectionappId={'workflow-app'}- appMode={AppModeEnum.WORKFLOW}+ appMode={'workflow'}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButton@@ -822,7 +821,7 @@ describe('app-publisher sections', () => {render(<PublisherActionsSectionappId={'workflow-app'}- appMode={AppModeEnum.WORKFLOW}+ appMode={'workflow'}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButtondiff --git a/web/app/components/app/app-publisher/__tests__/utils.spec.ts b/web/app/components/app/app-publisher/__tests__/utils.spec.tsindex 7dc8e2e209e..bdb16a11785 100644--- a/web/app/components/app/app-publisher/__tests__/utils.spec.ts+++ b/web/app/components/app/app-publisher/__tests__/utils.spec.ts@@ -1,17 +1,16 @@import type { TFunction } from 'i18next'import { withSelectorKey } from '@/test/i18n-mock'-import { AppModeEnum } from '@/types/app'import { basePath } from '@/utils/var'import { getDisabledFunctionTooltip, getPublisherAppMode, getPublisherAppUrl } from '../utils'describe('app-publisher utils', () => {describe('getPublisherAppMode', () => {it('should normalize chat-like apps to chat mode', () => {- expect(getPublisherAppMode(AppModeEnum.AGENT_CHAT)).toBe(AppModeEnum.CHAT)+ expect(getPublisherAppMode('agent-chat')).toBe('chat')})it('should keep completion mode unchanged', () => {- expect(getPublisherAppMode(AppModeEnum.COMPLETION)).toBe(AppModeEnum.COMPLETION)+ expect(getPublisherAppMode('completion')).toBe('completion')})})@@ -21,7 +20,7 @@ describe('app-publisher utils', () => {getPublisherAppUrl({appBaseUrl: 'https://example.com',accessToken: 'token-1',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,}),).toBe(`https://example.com${basePath}/chat/token-1`)})diff --git a/web/app/components/app/app-publisher/built-in-publisher/actions-section.tsx b/web/app/components/app/app-publisher/built-in-publisher/actions-section.tsxindex 6328556effd..bde731af56c 100644--- a/web/app/components/app/app-publisher/built-in-publisher/actions-section.tsx+++ b/web/app/components/app/app-publisher/built-in-publisher/actions-section.tsx@@ -3,7 +3,6 @@ import type { AppPublisherProps } from '../types'import { cn } from '@langgenius/dify-ui/cn'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { useTranslation } from 'react-i18next'-import { AppModeEnum } from '@/types/app'import SuggestedAction from '../suggested-action'import WorkflowToolAction from '../workflow-tool-action'@@ -58,7 +57,7 @@ export function PublisherActionsSection({const hasPublishedVersion = Boolean(publishedAt)const showOpenWebApp = !hasTriggerNode- const showWorkflowTool = appMode === AppModeEnum.WORKFLOW && !hasHumanInputNode && !hasTriggerNode+ const showWorkflowTool = appMode === 'workflow' && !hasHumanInputNode && !hasTriggerNodeconst navigationDisabled = !hasPublishedVersionconst workflowToolDisabled =!hasPublishedVersion || !workflowToolAvailable || (toolPublished && workflowToolIsLoading)diff --git a/web/app/components/app/app-publisher/index.tsx b/web/app/components/app/app-publisher/index.tsxindex 85db4642f88..2cfc74f560d 100644--- a/web/app/components/app/app-publisher/index.tsx+++ b/web/app/components/app/app-publisher/index.tsx@@ -7,13 +7,12 @@ import { useTranslation } from 'react-i18next'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { getAppACLCapabilities } from '@/utils/permission'import { PublisherContent } from './publisher-content'import { appPublisherOpenAtom, AppPublisherStateBoundary } from './state'export function AppPublisher(props: AppPublisherProps) {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)return (<Suspensefallback={@@ -45,8 +44,7 @@ function AppPublisherContent(props: AppPublisherProps) {workspacePermissionKeys,})const supportsMultiEnvironment =- (appDetail.mode === AppModeEnum.WORKFLOW || appDetail.mode === AppModeEnum.ADVANCED_CHAT) &&- canDeploy+ (appDetail.mode === 'workflow' || appDetail.mode === 'advanced-chat') && canDeployreturn (<AppPublisherStateBoundarydiff --git a/web/app/components/app/app-publisher/publisher-content/use-publish-controller.ts b/web/app/components/app/app-publisher/publisher-content/use-publish-controller.tsindex 14cbc351779..0d26a39a0e4 100644--- a/web/app/components/app/app-publisher/publisher-content/use-publish-controller.ts+++ b/web/app/components/app/app-publisher/publisher-content/use-publish-controller.ts@@ -18,7 +18,6 @@ import {appWorkflowQueryOptions,appWorkflowVersionsInfiniteQueryOptions,} from '@/service/workflow-queries'-import { AppModeEnum } from '@/types/app'type UsePublishControllerParams = Pick<AppPublisherProps,@@ -66,11 +65,8 @@ export function usePublishController({const queryClient = useQueryClient()const workflowStore = use(WorkflowContext)const invalidateAppWorkflow = useInvalidateAppWorkflow()- const isWorkflowApp = appMode === AppModeEnum.WORKFLOW || appMode === AppModeEnum.ADVANCED_CHAT- const isChatApp =- appMode === AppModeEnum.CHAT ||- appMode === AppModeEnum.AGENT_CHAT ||- appMode === AppModeEnum.COMPLETION+ const isWorkflowApp = appMode === 'workflow' || appMode === 'advanced-chat'+ const isChatApp = appMode === 'chat' || appMode === 'agent-chat' || appMode === 'completion'const {data: publishedWorkflow,isError: isPublishedWorkflowError,diff --git a/web/app/components/app/app-publisher/publisher-content/use-workflow-tool.ts b/web/app/components/app/app-publisher/publisher-content/use-workflow-tool.tsindex 6efa2fb6bde..85c362a9fa2 100644--- a/web/app/components/app/app-publisher/publisher-content/use-workflow-tool.ts+++ b/web/app/components/app/app-publisher/publisher-content/use-workflow-tool.ts@@ -7,7 +7,6 @@ import { useTranslation } from 'react-i18next'import { useCanManageTools } from '@/app/components/tools/hooks/use-tool-permissions'import { useConfigureButton } from '@/app/components/tools/workflow-tool/hooks/use-configure-button'import { appDefaultIconBackground } from '@/config'-import { AppModeEnum } from '@/types/app'type UseWorkflowToolParams = {appDescription?: string@@ -50,10 +49,10 @@ export function useWorkflowTool({toolPublished,workflowToolAvailable,}: UseWorkflowToolParams) {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const [drawerOpen, setDrawerOpen] = useState(false)const canManageTools = useCanManageTools()- const visible = appMode === AppModeEnum.WORKFLOW && !hasHumanInputNode && !hasTriggerNode+ const visible = appMode === 'workflow' && !hasHumanInputNode && !hasTriggerNodeconst published = Boolean(toolPublished)const message =!hasPublishedVersion || !workflowToolAvailablediff --git a/web/app/components/app/app-publisher/utils.ts b/web/app/components/app/app-publisher/utils.tsindex b6652e7a1e6..d5999efdc42 100644--- a/web/app/components/app/app-publisher/utils.ts+++ b/web/app/components/app/app-publisher/utils.ts@@ -1,10 +1,9 @@import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { TFunction } from 'i18next'-import { AppModeEnum } from '@/types/app'import { basePath } from '@/utils/var'export const getPublisherAppMode = (mode?: AppMode) => {- if (mode !== AppModeEnum.COMPLETION && mode !== AppModeEnum.WORKFLOW) return AppModeEnum.CHAT+ if (mode !== 'completion' && mode !== 'workflow') return 'chat'return mode}diff --git a/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx b/web/app/components/app/configuration/__tests__/configuration-view.spec.tsxindex 72793efaaf6..a8bf13af7bc 100644--- a/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx+++ b/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx@@ -9,7 +9,7 @@ import { fireEvent, render, screen } from '@testing-library/react'import * as React from 'react'import { PluginCategoryEnum } from '@/app/components/plugins/types'import { CollectionType } from '@/app/components/tools/types'-import { AppModeEnum, ModelModeType } from '@/types/app'+import { ModelModeType } from '@/types/app'import ConfigurationView from '../configuration-view'const mockIsAgentV2Enabled = vi.hoisted(() => vi.fn(() => false))@@ -96,7 +96,7 @@ const createContextValue = (): ComponentProps<typeof ConfigContext.Provider>['vaappId: 'app-1',onOpenFeatures: vi.fn(),isTrailFinished: false,- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,modelModeType: ModelModeType.chat,promptMode: 'simple' as never,setPromptMode: vi.fn(),@@ -351,7 +351,7 @@ describe('ConfigurationView', () => {it('should show the legacy Agent badge for legacy Agent apps when Agent v2 is enabled', async () => {mockIsAgentV2Enabled.mockReturnValue(true)const contextValue = createContextValue()- contextValue.mode = AppModeEnum.AGENT_CHAT+ contextValue.mode = 'agent-chat'render(<ConfigurationView {...createViewModel({ contextValue })} />)@@ -375,7 +375,7 @@ describe('ConfigurationView', () => {it('should not show the legacy Agent badge when Agent v2 is disabled', () => {const contextValue = createContextValue()- contextValue.mode = AppModeEnum.AGENT_CHAT+ contextValue.mode = 'agent-chat'render(<ConfigurationView {...createViewModel({ contextValue })} />)diff --git a/web/app/components/app/configuration/__tests__/utils.spec.ts b/web/app/components/app/configuration/__tests__/utils.spec.tsindex 5ee8fe2e37c..0d68301899c 100644--- a/web/app/components/app/configuration/__tests__/utils.spec.ts+++ b/web/app/components/app/configuration/__tests__/utils.spec.ts@@ -1,5 +1,5 @@import type { ModelConfig } from '@/models/debug'-import { AppModeEnum, ModelModeType, Resolution, TransferMethod } from '@/types/app'+import { ModelModeType, Resolution, TransferMethod } from '@/types/app'import {buildConfigurationFeaturesData,getConfigurationPublishingState,@@ -129,7 +129,7 @@ describe('configuration utils', () => {hasSetContextVar: false,hasSelectedDataSets: false,isAdvancedMode: true,- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,modelModeType: ModelModeType.completion,promptTemplate: 'ignored',})@@ -158,7 +158,7 @@ describe('configuration utils', () => {hasSetContextVar: false,hasSelectedDataSets: true,isAdvancedMode: false,- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,modelModeType: ModelModeType.completion,promptTemplate: 'Prompt',})@@ -188,7 +188,7 @@ describe('configuration utils', () => {hasSetContextVar: true,hasSelectedDataSets: false,isAdvancedMode: true,- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,modelModeType: ModelModeType.chat,promptTemplate: 'ignored',})@@ -217,7 +217,7 @@ describe('configuration utils', () => {hasSetContextVar: true,hasSelectedDataSets: false,isAdvancedMode: true,- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,modelModeType: ModelModeType.completion,promptTemplate: 'ignored',})diff --git a/web/app/components/app/configuration/config-prompt/__tests__/advanced-prompt-input.spec.tsx b/web/app/components/app/configuration/config-prompt/__tests__/advanced-prompt-input.spec.tsxindex 1f3b2bddab8..45f512d058d 100644--- a/web/app/components/app/configuration/config-prompt/__tests__/advanced-prompt-input.spec.tsx+++ b/web/app/components/app/configuration/config-prompt/__tests__/advanced-prompt-input.spec.tsx@@ -4,7 +4,6 @@ import { fireEvent, render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { INSERT_VARIABLE_VALUE_BLOCK_COMMAND } from '@/app/components/base/prompt-editor/plugins/variable-block'import ConfigContext from '@/context/debug-configuration'-import { AppModeEnum } from '@/types/app'import AdvancedPromptInput from '../advanced-prompt-input'const mockEmit = vi.fn()@@ -82,7 +81,7 @@ vi.mock('../prompt-editor-height-resize-wrap', () => ({const createContextValue = () =>({- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,hasSetBlockStatus: {context: false,history: false,diff --git a/web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsx b/web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsxindex 06ec5c116c6..bd0518b638b 100644--- a/web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/config-prompt/__tests__/index.spec.tsx@@ -5,7 +5,7 @@ import * as React from 'react'import { MAX_PROMPT_MESSAGE_LENGTH } from '@/config'import ConfigContext from '@/context/debug-configuration'import { PromptRole } from '@/models/debug'-import { AppModeEnum, ModelModeType } from '@/types/app'+import { ModelModeType } from '@/types/app'import Prompt from '../index'type DebugConfiguration = {@@ -113,7 +113,7 @@ const renderComponent = (contextOverrides: Partial<DebugConfiguration> = {},) => {const mergedProps: IPromptProps = {- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,promptTemplate: 'initial template',promptVariables: defaultPromptVariables,onChange: vi.fn(),@@ -144,7 +144,7 @@ describe('Prompt config component', () => {const simplePrompt = screen.getByTestId('simple-prompt-input')expect(simplePrompt)!.toBeInTheDocument()- expect(simplePrompt)!.toHaveAttribute('data-mode', AppModeEnum.CHAT)+ expect(simplePrompt)!.toHaveAttribute('data-mode', 'chat')expect(mockSimplePromptInputProps?.promptTemplate).toBe('initial template')fireEvent.click(simplePrompt)expect(onChange).toHaveBeenCalledWith('mocked prompt', defaultPromptVariables)diff --git a/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input-accessibility.spec.tsx b/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input-accessibility.spec.tsxindex ae4bc5aa971..7aeac6de217 100644--- a/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input-accessibility.spec.tsx+++ b/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input-accessibility.spec.tsx@@ -1,5 +1,4 @@import { render, screen } from '@testing-library/react'-import { AppModeEnum } from '@/types/app'import Prompt from '../simple-prompt-input'vi.mock('@/app/components/base/features/hooks', () => ({@@ -9,7 +8,7 @@ vi.mock('@/app/components/base/features/hooks', () => ({}))describe('SimplePromptInput accessibility', () => {- it.each([AppModeEnum.CHAT, AppModeEnum.COMPLETION])(+ it.each(['chat', 'completion'] as const)('names the real editor from the visible section heading in %s mode',(mode) => {render(<Prompt mode={mode} promptTemplate="" promptVariables={[]} noResize />)@@ -22,9 +21,7 @@ describe('SimplePromptInput accessibility', () => {)it('keeps an accessible editor name when embedded without a section heading', () => {- render(- <Prompt mode={AppModeEnum.CHAT} promptTemplate="" promptVariables={[]} noTitle noResize />,- )+ render(<Prompt mode={'chat'} promptTemplate="" promptVariables={[]} noTitle noResize />)expect(screen.getByRole('textbox', { name: 'appDebug.chatSubTitle' })).toBeInTheDocument()expect(screen.queryByRole('heading')).not.toBeInTheDocument()})diff --git a/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx b/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsxindex d1c8359a2d4..640888f1815 100644--- a/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx+++ b/web/app/components/app/configuration/config-prompt/__tests__/simple-prompt-input.spec.tsx@@ -2,7 +2,6 @@ import type { ReactNode } from 'react'import { fireEvent, render, screen } from '@testing-library/react'import { INSERT_VARIABLE_VALUE_BLOCK_COMMAND } from '@/app/components/base/prompt-editor/plugins/variable-block'import ConfigContext from '@/context/debug-configuration'-import { AppModeEnum } from '@/types/app'import Prompt from '../simple-prompt-input'const mockEmit = vi.fn()@@ -144,7 +143,7 @@ describe('SimplePromptInput', () => {render(<ConfigContext.Provider value={createContextValue()}><Prompt- mode={AppModeEnum.CHAT}+ mode={'chat'}promptTemplate="Hello {{new_var}}"promptVariables={[]}onChange={mockOnChange}@@ -170,7 +169,7 @@ describe('SimplePromptInput', () => {render(<ConfigContext.Provider value={createContextValue()}><Prompt- mode={AppModeEnum.CHAT}+ mode={'chat'}promptTemplate="Hello"promptVariables={[{ key: 'existing_var', name: 'Existing', type: 'string', required: true },@@ -215,12 +214,7 @@ describe('SimplePromptInput', () => {it('should apply automatic generation results to prompt and opening statement', () => {render(<ConfigContext.Provider value={createContextValue()}>- <Prompt- mode={AppModeEnum.CHAT}- promptTemplate="Hello"- promptVariables={[]}- onChange={mockOnChange}- />+ <Prompt mode={'chat'} promptTemplate="Hello" promptVariables={[]} onChange={mockOnChange} /></ConfigContext.Provider>,)@@ -275,7 +269,7 @@ describe('SimplePromptInput', () => {})}><Prompt- mode={AppModeEnum.CHAT}+ mode={'chat'}promptTemplate="Hello {{existing_var}}"promptVariables={[{ key: 'existing_var', name: 'Existing', type: 'string', required: true },@@ -300,7 +294,7 @@ describe('SimplePromptInput', () => {})}><Prompt- mode={AppModeEnum.CHAT}+ mode={'chat'}promptTemplate="Hello {{search_api}} {{existing_var}}"promptVariables={[{ key: 'existing_var', name: 'Existing', type: 'string', required: true },@@ -321,7 +315,7 @@ describe('SimplePromptInput', () => {render(<ConfigContext.Provider value={createContextValue()}><Prompt- mode={AppModeEnum.CHAT}+ mode={'chat'}promptTemplate="Hello {{existing_var}}"promptVariables={[{ key: 'existing_var', name: '', type: 'string', required: true }]}onChange={mockOnChange}diff --git a/web/app/components/app/configuration/config-prompt/advanced-prompt-input.tsx b/web/app/components/app/configuration/config-prompt/advanced-prompt-input.tsxindex 91d6dd4ae56..28d43f9089c 100644--- a/web/app/components/app/configuration/config-prompt/advanced-prompt-input.tsx+++ b/web/app/components/app/configuration/config-prompt/advanced-prompt-input.tsx@@ -1,4 +1,5 @@'use client'+import type { FC } from 'react'import type { ExternalDataTool } from '@/models/common'import type { PromptRole, PromptVariable } from '@/models/debug'@@ -20,7 +21,6 @@ import { INSERT_VARIABLE_VALUE_BLOCK_COMMAND } from '@/app/components/base/prompimport ConfigContext from '@/context/debug-configuration'import { useEventEmitterContextContext } from '@/context/event-emitter'import { useModalContext } from '@/context/modal-context'-import { AppModeEnum } from '@/types/app'import { getNewVar, getVars } from '@/utils/var'import ConfirmAddVar from './confirm-add-var'import MessageTypeSelector from './message-type-selector'@@ -102,7 +102,7 @@ const AdvancedPromptInput: FC<Props> = ({},})}- const isChatApp = mode !== AppModeEnum.COMPLETION+ const isChatApp = mode !== 'completion'const [isCopied, setIsCopied] = React.useState(false)const promptVariablesObj = (() => {diff --git a/web/app/components/app/configuration/config-prompt/index.tsx b/web/app/components/app/configuration/config-prompt/index.tsxindex 0841a650e0a..ef97e8cd76c 100644--- a/web/app/components/app/configuration/config-prompt/index.tsx+++ b/web/app/components/app/configuration/config-prompt/index.tsx@@ -1,7 +1,8 @@'use client'+import type { FC } from 'react'+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { PromptItem, PromptVariable } from '@/models/debug'-import type { AppModeEnum } from '@/types/app'import { Button } from '@langgenius/dify-ui/button'import { RiAddLine } from '@remixicon/react'import { produce } from 'immer'@@ -16,7 +17,7 @@ import { ModelModeType } from '@/types/app'import SimplePromptInput from './simple-prompt-input'export type IPromptProps = {- mode: AppModeEnum+ mode: ConfigurationAppModepromptTemplate: stringpromptVariables: PromptVariable[]readonly?: booleandiff --git a/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx b/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsxindex 70896efdbfb..a5e915df6d2 100644--- a/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx+++ b/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx@@ -1,5 +1,7 @@'use client'+import type { FC } from 'react'+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { ExternalDataTool } from '@/models/common'import type { PromptVariable } from '@/models/debug'import type { GenRes } from '@/service/debug'@@ -24,13 +26,12 @@ import ConfigContext from '@/context/debug-configuration'import { useEventEmitterContextContext } from '@/context/event-emitter'import { useModalContext } from '@/context/modal-context'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'-import { AppModeEnum } from '@/types/app'import { getNewVar, getVars } from '@/utils/var'import ConfirmAddVar from './confirm-add-var'import PromptEditorHeightResizeWrap from './prompt-editor-height-resize-wrap'type ISimplePromptInput = {- mode: AppModeEnum+ mode: ConfigurationAppModepromptTemplate: stringpromptVariables: PromptVariable[]readonly?: boolean@@ -54,7 +55,7 @@ const Prompt: FC<ISimplePromptInput> = ({const { t } = useTranslation(['appDebug'])const titleId = useId()const title =- mode !== AppModeEnum.COMPLETION+ mode !== 'completion'? t(($) => $.chatSubTitle, { ns: 'appDebug' }): t(($) => $.completionSubTitle, { ns: 'appDebug' })const media = useBreakpoints()@@ -66,6 +67,7 @@ const Prompt: FC<ISimplePromptInput> = ({const {appId,modelConfig,+ modelModeType,dataSets,setModelConfig,setPrevPromptConfig,@@ -176,7 +178,7 @@ const Prompt: FC<ISimplePromptInput> = ({setModelConfig(newModelConfig)setPrevPromptConfig(modelConfig.configs)- if (mode !== AppModeEnum.COMPLETION) {+ if (mode !== 'completion') {setIntroduction(res.opening_statement || '')const newFeatures = produce(features, (draft) => {draft.opening = {@@ -314,7 +316,7 @@ const Prompt: FC<ISimplePromptInput> = ({{showAutomatic && (<GetAutomaticResModalflowId={appId}- mode={mode as AppModeEnum}+ modelMode={modelModeType}isShow={showAutomatic}onClose={showAutomaticFalse}onFinished={handleAutomaticRes}diff --git a/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx b/web/app/components/app/configuration/config-var/__tests__/index.spec.tsxindex 03238490d00..5360469f3e0 100644--- a/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/config-var/__tests__/index.spec.tsx@@ -9,7 +9,6 @@ import { vi } from 'vite-plus/test'import { toast } from '@/app/components/app/configuration/toast'import DebugConfigurationContext from '@/context/debug-configuration'import { renderWithConsoleQuery as render } from '@/test/console/query-data'-import { AppModeEnum } from '@/types/app'import ConfigVar, { ADD_EXTERNAL_DATA_TOOL } from '../index'const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')@@ -69,7 +68,7 @@ type DebugConfigurationState = React.ComponentProps<>['value']const defaultDebugConfigValue = {- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,dataSets: [],modelConfig: {model_id: 'test-model',@@ -399,7 +398,7 @@ describe('ConfigVar', () => {onPromptVariablesChange,},{- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,dataSets: [{ id: 'dataset-1' } as DebugConfigurationState['dataSets'][number]],},)diff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsxindex b56a1cf9504..84baf7d5a23 100644--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/index-logic.spec.tsx@@ -10,7 +10,6 @@ import {seedAppDetail,} from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import ConfigModal from '../index'vi.mock('@/next/navigation', async (importOriginal) => ({@@ -116,12 +115,12 @@ const createPayload = (overrides: Partial<InputVar> = {}): InputVar => ({const renderConfigModal = (payload: InputVar = createPayload()) => {const queryClient = createConsoleQueryClient()- seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode: AppModeEnum.CHAT }))+ seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode: 'chat' as const }))return renderWithConsoleQuery(<DebugConfigurationContext.Providervalue={{- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,dataSets: [],modelConfig: { model_id: 'model-1' },} as anydiff --git a/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx b/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsxindex 07d7fbf2b73..815959a94b5 100644--- a/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/config-var/config-modal/__tests__/index.spec.tsx@@ -11,7 +11,7 @@ import {seedAppDetail,} from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum, TransferMethod } from '@/types/app'+import { TransferMethod } from '@/types/app'import ConfigModal from '../index'vi.mock('@/next/navigation', async (importOriginal) => ({@@ -37,7 +37,7 @@ vi.mock('@monaco-editor/react', async () => ({const render = (ui: React.ReactElement) => {const queryClient = createConsoleQueryClient()- seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode: AppModeEnum.CHAT }))+ seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode: 'chat' as const }))return renderWithConsoleQuery(ui, { queryClient })}diff --git a/web/app/components/app/configuration/config-var/config-modal/index.tsx b/web/app/components/app/configuration/config-var/config-modal/index.tsxindex 8d585984a6c..e70cb9de404 100644--- a/web/app/components/app/configuration/config-var/config-modal/index.tsx+++ b/web/app/components/app/configuration/config-var/config-modal/index.tsx@@ -1,4 +1,5 @@'use client'+import type { ChangeEvent, FC } from 'react'import type { Item as SelectItem } from './type-select'import type { ConfigModalValidationError } from './utils'@@ -15,7 +16,6 @@ import ConfigContext from '@/context/debug-configuration'import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { commonQueryKeys } from '@/service/use-common'-import { AppModeEnum } from '@/types/app'import {checkKeys,getNewVarInWorkflow,@@ -69,8 +69,7 @@ const ConfigModal: FC<IConfigModalProps> = ({input: appId ? { params: { app_id: appId } } : skipToken,}),)- const isBasicApp =- appDetail?.mode !== AppModeEnum.ADVANCED_CHAT && appDetail?.mode !== AppModeEnum.WORKFLOW+ const isBasicApp = appDetail?.mode !== 'advanced-chat' && appDetail?.mode !== 'workflow'const jsonSchemaStr = useMemo(() => getJsonSchemaEditorValue(type, tempPayload.json_schema),[tempPayload.json_schema, type],diff --git a/web/app/components/app/configuration/config-var/index.tsx b/web/app/components/app/configuration/config-var/index.tsxindex 5e4d42a445d..3782292cb22 100644--- a/web/app/components/app/configuration/config-var/index.tsx+++ b/web/app/components/app/configuration/config-var/index.tsx@@ -1,4 +1,5 @@'use client'+import type { FC } from 'react'import type { InputVar } from '@/app/components/workflow/types'import type { ExternalDataTool } from '@/models/common'@@ -27,7 +28,6 @@ import { InputVarType } from '@/app/components/workflow/types'import ConfigContext from '@/context/debug-configuration'import { useEventEmitterContextContext } from '@/context/event-emitter'import { useModalContext } from '@/context/modal-context'-import { AppModeEnum } from '@/types/app'import { getNewVar, hasDuplicateStr } from '@/utils/var'import Panel from '../base/feature-panel'import EditModal from './config-modal'@@ -244,7 +244,7 @@ const ConfigVar: FC<IConfigVarProps> = ({ promptVariables, readonly, onPromptVar(index: number) => {const removeVar = promptVariables[index]- if (mode === AppModeEnum.COMPLETION && dataSets.length > 0 && removeVar!.is_context_var) {+ if (mode === 'completion' && dataSets.length > 0 && removeVar!.is_context_var) {showDeleteContextVarModal()setRemoveIndex(index)returndiff --git a/web/app/components/app/configuration/config/__tests__/index.spec.tsx b/web/app/components/app/configuration/config/__tests__/index.spec.tsxindex f98d912247d..49e51c49464 100644--- a/web/app/components/app/configuration/config/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/config/__tests__/index.spec.tsx@@ -1,9 +1,10 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { ModelConfig, PromptVariable } from '@/models/debug'import type { ToolItem } from '@/types/app'import { render, screen } from '@testing-library/react'import * as React from 'react'import * as useContextSelector from 'use-context-selector'-import { AgentStrategy, AppModeEnum, ModelModeType } from '@/types/app'+import { AgentStrategy, ModelModeType } from '@/types/app'import Config from '../index'vi.mock('use-context-selector', async (importOriginal) => {@@ -64,7 +65,7 @@ vi.mock('../../config-prompt/conversation-history/history-panel', () => ({}))type MockContext = {- mode: AppModeEnum+ mode: AppModeisAdvancedMode: booleanmodelModeType: ModelModeTypeisAgent: boolean@@ -118,7 +119,7 @@ const createModelConfig = (overrides: Partial<ModelConfig> = {}): ModelConfig =>})const createContextValue = (overrides: Partial<MockContext> = {}): MockContext => ({- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,isAdvancedMode: false,modelModeType: ModelModeType.chat,isAgent: false,@@ -173,11 +174,11 @@ describe('Config - Rendering', () => {expect(screen.getByTestId('agent-tools')).toBeInTheDocument()})- it('should display HistoryPanel only when advanced chat completion values apply', () => {+ it('should display HistoryPanel for a chat app using an advanced completion prompt', () => {const showHistoryModal = vi.fn()renderConfig({isAdvancedMode: true,- mode: AppModeEnum.ADVANCED_CHAT,+ mode: 'chat' as const,modelModeType: ModelModeType.completion,hasSetBlockStatus: {context: false,diff --git a/web/app/components/app/configuration/config/automatic/__tests__/generator-reflow.browser.spec.tsx b/web/app/components/app/configuration/config/automatic/__tests__/generator-reflow.browser.spec.tsxindex 3d9df3eaaf3..d0a9e193531 100644--- a/web/app/components/app/configuration/config/automatic/__tests__/generator-reflow.browser.spec.tsx+++ b/web/app/components/app/configuration/config/automatic/__tests__/generator-reflow.browser.spec.tsx@@ -1,7 +1,6 @@import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { page } from 'vite-plus/test/browser'import { render } from 'vitest-browser-react'-import { AppModeEnum } from '@/types/app'import GetAutomaticRes from '../get-automatic-res'vi.mock('react-i18next', async () => {@@ -71,7 +70,7 @@ describe('Prompt generator reflow', () => {const screen = await render(<QueryClientProvider client={queryClient}><GetAutomaticRes- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowonClose={vi.fn()}onFinished={vi.fn()}diff --git a/web/app/components/app/configuration/config/automatic/__tests__/get-automatic-res.spec.tsx b/web/app/components/app/configuration/config/automatic/__tests__/get-automatic-res.spec.tsxindex 43981e8cd8f..70e62993be6 100644--- a/web/app/components/app/configuration/config/automatic/__tests__/get-automatic-res.spec.tsx+++ b/web/app/components/app/configuration/config/automatic/__tests__/get-automatic-res.spec.tsx@@ -1,5 +1,4 @@import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'-import { AppModeEnum } from '@/types/app'import GetAutomaticRes from '../get-automatic-res'const mockGenerateBasicAppFirstTimeRule = vi.fn()@@ -53,7 +52,9 @@ vi.mock(}) => (<div><button- onClick={() => setModel({ modelId: 'gpt-4o-mini', provider: 'openai', mode: 'chat' })}+ onClick={() =>+ setModel({ modelId: 'gpt-4o-mini', provider: 'openai', mode: 'chat' as const })+ }>change-model</button>@@ -121,7 +122,7 @@ describe('GetAutomaticRes', () => {it('should apply a basic suggestion and persist model updates', async () => {render(<GetAutomaticRes- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowonClose={mockOnClose}onFinished={mockOnFinished}@@ -152,7 +153,7 @@ describe('GetAutomaticRes', () => {render(<GetAutomaticRes- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowonClose={mockOnClose}onFinished={mockOnFinished}@@ -176,7 +177,7 @@ describe('GetAutomaticRes', () => {it('should block generation when instruction is empty', () => {render(<GetAutomaticRes- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowonClose={mockOnClose}onFinished={mockOnFinished}@@ -203,7 +204,7 @@ describe('GetAutomaticRes', () => {render(<GetAutomaticRes- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowonClose={mockOnClose}onFinished={mockOnFinished}@@ -254,7 +255,7 @@ describe('GetAutomaticRes', () => {render(<GetAutomaticRes- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowonClose={mockOnClose}onFinished={mockOnFinished}@@ -291,7 +292,7 @@ describe('GetAutomaticRes', () => {render(<GetAutomaticRes- mode={AppModeEnum.ADVANCED_CHAT}+ modelMode="chat"isShowonClose={mockOnClose}onFinished={mockOnFinished}@@ -315,6 +316,7 @@ describe('GetAutomaticRes', () => {current: 'current prompt',instruction: 'workflow instruction',ideal_output: 'ideal output',+ model_config: expect.objectContaining({ mode: 'chat' }),}),)})diff --git a/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx b/web/app/components/app/configuration/config/automatic/get-automatic-res.tsxindex bf2598f5087..c75eef3b5f2 100644--- a/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx+++ b/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx@@ -1,9 +1,10 @@'use client'+import type { FC } from 'react'import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'// typeimport type { GenRes } from '@/service/debug'-import type { AppModeEnum, CompletionParams, Model, ModelModeType } from '@/types/app'+import type { CompletionParams, Model, ModelModeType } from '@/types/app'import { Button } from '@langgenius/dify-ui/button'import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'import { useQuery } from '@tanstack/react-query'@@ -31,7 +32,7 @@ import useGenData from './use-gen-data'const i18nPrefix = 'generate'type IGetAutomaticResProps = {- mode: AppModeEnum+ modelMode: ModelModeTypeisShow: booleanonClose: () => voidonFinished: (res: GenRes) => void@@ -60,7 +61,7 @@ const TryLabel: FC<{}const GetAutomaticRes: FC<IGetAutomaticResProps> = ({- mode,+ modelMode,isShow,onClose,flowId,@@ -84,10 +85,10 @@ const GetAutomaticRes: FC<IGetAutomaticResProps> = ({return {name: defaultModel?.model ?? '',provider: defaultModel?.provider.provider ?? '',- mode: mode as unknown as ModelModeType,+ mode: modelMode,completion_params: {} as CompletionParams,}- }, [defaultModel, mode, selectedModel, storedModel])+ }, [defaultModel, modelMode, selectedModel, storedModel])const tryList = [{iconClassName: 'i-ri-terminal-box-line',diff --git a/web/app/components/app/configuration/config/code-generator/__tests__/get-code-generator-res.spec.tsx b/web/app/components/app/configuration/config/code-generator/__tests__/get-code-generator-res.spec.tsxindex 80c5ae8f66d..9ab9941338f 100644--- a/web/app/components/app/configuration/config/code-generator/__tests__/get-code-generator-res.spec.tsx+++ b/web/app/components/app/configuration/config/code-generator/__tests__/get-code-generator-res.spec.tsx@@ -1,6 +1,5 @@import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'-import { AppModeEnum } from '@/types/app'import GetCodeGeneratorResModal from '../get-code-generator-res'const mockGenerateRule = vi.fn()@@ -52,7 +51,9 @@ vi.mock(}) => (<div><button- onClick={() => setModel({ modelId: 'gpt-4o-mini', provider: 'openai', mode: 'chat' })}+ onClick={() =>+ setModel({ modelId: 'gpt-4o-mini', provider: 'openai', mode: 'chat' as const })+ }>change-model</button>@@ -119,7 +120,7 @@ describe('GetCodeGeneratorResModal', () => {flowId="flow-1"nodeId="node-1"currentCode="print(1)"- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowcodeLanguages={CodeLanguage.python3}onClose={mockOnClose}@@ -146,7 +147,7 @@ describe('GetCodeGeneratorResModal', () => {flowId="flow-1"nodeId="node-1"currentCode="print(1)"- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowcodeLanguages={CodeLanguage.python3}onClose={mockOnClose}@@ -173,7 +174,7 @@ describe('GetCodeGeneratorResModal', () => {flowId="flow-1"nodeId="node-1"currentCode="print(1)"- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowcodeLanguages={CodeLanguage.python3}onClose={mockOnClose}@@ -200,7 +201,7 @@ describe('GetCodeGeneratorResModal', () => {flowId="flow-1"nodeId="node-1"currentCode="print(1)"- mode={AppModeEnum.CHAT}+ modelMode="completion"isShowcodeLanguages={CodeLanguage.python3}onClose={mockOnClose}@@ -221,6 +222,7 @@ describe('GetCodeGeneratorResModal', () => {instruction: 'code instruction',ideal_output: 'code output',language: 'python',+ model_config: expect.objectContaining({ mode: 'completion' }),}),)})@@ -255,7 +257,7 @@ describe('GetCodeGeneratorResModal', () => {flowId="flow-1"nodeId="node-1"currentCode="print(1)"- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowcodeLanguages={CodeLanguage.python3}onClose={mockOnClose}@@ -295,7 +297,7 @@ describe('GetCodeGeneratorResModal', () => {flowId="flow-1"nodeId="node-1"currentCode="print(1)"- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowcodeLanguages={CodeLanguage.javascript}onClose={mockOnClose}diff --git a/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx b/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsxindex 4a868b916c8..df61616c307 100644--- a/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx+++ b/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx@@ -2,7 +2,7 @@ import type { FC } from 'react'import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { CodeLanguage } from '@/app/components/workflow/nodes/code/types'import type { GenRes } from '@/service/debug'-import type { AppModeEnum, CompletionParams, Model, ModelModeType } from '@/types/app'+import type { CompletionParams, Model, ModelModeType } from '@/types/app'import { Button } from '@langgenius/dify-ui/button'import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'import { useQuery } from '@tanstack/react-query'@@ -42,7 +42,7 @@ type IGetCodeGeneratorResProps = {flowId: stringnodeId: stringcurrentCode?: string- mode: AppModeEnum+ modelMode: ModelModeTypeisShow: booleancodeLanguages: CodeLanguageonClose: () => void@@ -53,7 +53,7 @@ export const GetCodeGeneratorResModal: FC<IGetCodeGeneratorResProps> = ({flowId,nodeId,currentCode,- mode,+ modelMode,isShow,codeLanguages,onClose,@@ -80,10 +80,10 @@ export const GetCodeGeneratorResModal: FC<IGetCodeGeneratorResProps> = ({return {name: defaultModel?.model ?? '',provider: defaultModel?.provider.provider ?? '',- mode: mode as unknown as ModelModeType,+ mode: modelMode,completion_params: defaultCompletionParams,}- }, [defaultModel, mode, selectedModel, storedModel])+ }, [defaultModel, modelMode, selectedModel, storedModel])const [instructionFromSessionStorage, setInstructionFromSessionStorage] =useSessionStorageState<string>(`improve-instruction-${flowId}-${nodeId}`)diff --git a/web/app/components/app/configuration/config/index.tsx b/web/app/components/app/configuration/config/index.tsxindex 8c049c7601b..430e03b40ad 100644--- a/web/app/components/app/configuration/config/index.tsx+++ b/web/app/components/app/configuration/config/index.tsx@@ -1,4 +1,5 @@'use client'+import type { FC } from 'react'import type { ModelConfig, PromptVariable } from '@/models/debug'import { produce } from 'immer'@@ -7,7 +8,7 @@ import { useContext } from 'use-context-selector'import ConfigPrompt from '@/app/components/app/configuration/config-prompt'import ConfigVar from '@/app/components/app/configuration/config-var'import ConfigContext from '@/context/debug-configuration'-import { AppModeEnum, ModelModeType } from '@/types/app'+import { ModelModeType } from '@/types/app'import HistoryPanel from '../config-prompt/conversation-history/history-panel'import ConfigVision from '../config-vision'import DatasetConfig from '../dataset-config'@@ -30,9 +31,7 @@ const Config: FC = () => {setPrevPromptConfig,dataSets,} = useContext(ConfigContext)- const isChatApp = [AppModeEnum.ADVANCED_CHAT, AppModeEnum.AGENT_CHAT, AppModeEnum.CHAT].includes(- mode,- )+ const isChatApp = mode === 'agent-chat' || mode === 'chat'const formattingChangedDispatcher = useFormattingChangedDispatcher()const promptTemplate = modelConfig.configs.prompt_templatediff --git a/web/app/components/app/configuration/configuration-view/index.tsx b/web/app/components/app/configuration/configuration-view/index.tsxindex 95c2ba7af43..17cdfd8b6c1 100644--- a/web/app/components/app/configuration/configuration-view/index.tsx+++ b/web/app/components/app/configuration/configuration-view/index.tsx@@ -1,4 +1,5 @@'use client'+import type { FC } from 'react'import type { ConfigurationViewModel } from '../hooks/configuration-view-model'import type { InstallBundleCompleteCallback } from '@/app/components/plugins/install-plugin/install-bundle'@@ -40,7 +41,7 @@ import ModelParameterModal from '@/app/components/header/account-setting/model-pimport PluginDependency from '@/app/components/workflow/plugin-dependency'import ConfigContext from '@/context/debug-configuration'import { isAgentV2Enabled } from '@/features/agent-v2/feature-flag'-import { AppModeEnum, ModelModeType } from '@/types/app'+import { ModelModeType } from '@/types/app'import { LegacyAgentBadge } from './legacy-agent-badge'const ConfigurationView: FC<ConfigurationViewModel> = ({@@ -80,7 +81,7 @@ const ConfigurationView: FC<ConfigurationViewModel> = ({}) => {const { t } = useTranslation(['appDebug', 'common'])const debugWithMultipleModel = appPublisherProps.debugWithMultipleModel- const showLegacyAgentBadge = isAgentV2Enabled() && contextValue.mode === AppModeEnum.AGENT_CHAT+ const showLegacyAgentBadge = isAgentV2Enabled() && contextValue.mode === 'agent-chat'const handlePluginInstallComplete: InstallBundleCompleteCallback = (plugins, installStatus) => {if (!installStatus.some((status) => status.success)) return@@ -289,7 +290,7 @@ const ConfigurationView: FC<ConfigurationViewModel> = ({showinWorkflow={false}showFileUpload={false}- isChatMode={contextValue.mode !== AppModeEnum.COMPLETION}+ isChatMode={contextValue.mode !== 'completion'}disabled={!!contextValue.readonly}onChange={onFeaturesChange}onClose={onCloseFeaturePanel}diff --git a/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx b/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsxindex 4ec1f23c33f..75f3ac0ae2a 100644--- a/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/dataset-config/__tests__/index.spec.tsx@@ -11,7 +11,7 @@ import { getSelectedDatasetsMode } from '@/app/components/workflow/nodes/knowledimport { DatasetPermission, DataSourceType } from '@/models/datasets'import { createConsoleQueryWrapper } from '@/test/console/query-data'import { render as renderWithConsoleState } from '@/test/console/render'-import { AppModeEnum, ModelModeType, RETRIEVE_TYPE } from '@/types/app'+import { ModelModeType, RETRIEVE_TYPE } from '@/types/app'import { DatasetACLPermission, getDatasetACLCapabilities } from '@/utils/permission'import DatasetConfig from '../index'@@ -185,7 +185,7 @@ vi.mock(// Mock contextconst mockConfigContext: any = {- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,modelModeType: ModelModeType.chat,isAgent: false,dataSets: [],@@ -516,7 +516,7 @@ describe('DatasetConfig', () => {it('should show context variable selector in completion mode with datasets', () => {const dataset = createMockDataset()renderDatasetConfig({- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,dataSets: [dataset],modelConfig: {configs: {@@ -537,7 +537,7 @@ describe('DatasetConfig', () => {it('should not show context variable selector in chat mode', () => {const dataset = createMockDataset()renderDatasetConfig({- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,dataSets: [dataset],modelConfig: {configs: {@@ -555,7 +555,7 @@ describe('DatasetConfig', () => {const user = userEvent.setup()const dataset = createMockDataset()renderDatasetConfig({- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,dataSets: [dataset],modelConfig: {configs: {@@ -877,7 +877,7 @@ describe('DatasetConfig', () => {// Context var is only shown when datasets exist AND there are prompt_variables// Test with no datasets to ensure context var is not shownrenderDatasetConfig({- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,dataSets: [],modelConfig: {configs: {@@ -960,7 +960,7 @@ describe('DatasetConfig', () => {metadata_model_config: {provider: 'openai',name: 'gpt-3.5-turbo',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.7 },},},@@ -976,7 +976,7 @@ describe('DatasetConfig', () => {metadata_model_config: {provider: 'openai',name: 'gpt-4o-mini',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.7 },},}),@@ -993,7 +993,7 @@ describe('DatasetConfig', () => {metadata_model_config: {provider: 'openai',name: 'gpt-3.5-turbo',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.5, max_tokens: 100 },},},diff --git a/web/app/components/app/configuration/dataset-config/index.tsx b/web/app/components/app/configuration/dataset-config/index.tsxindex 679f6750143..17ef4a510c7 100644--- a/web/app/components/app/configuration/dataset-config/index.tsx+++ b/web/app/components/app/configuration/dataset-config/index.tsx@@ -34,7 +34,6 @@ import {import ConfigContext from '@/context/debug-configuration'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'-import { AppModeEnum } from '@/types/app'import { getDatasetACLCapabilities } from '@/utils/permission'import FeaturePanel from '../base/feature-panel'import { OperationButton } from '../base/operation-button'@@ -269,7 +268,7 @@ const DatasetConfig: FC<Props> = ({ readonly, hideMetadataFilter }) => {draft.metadata_model_config = {provider: model.provider,name: model.modelId,- mode: model.mode || AppModeEnum.CHAT,+ mode: model.mode || 'chat',completion_params: draft.metadata_model_config?.completion_params || { temperature: 0.7 },}})@@ -355,7 +354,7 @@ const DatasetConfig: FC<Props> = ({ readonly, hideMetadataFilter }) => {</div>)}- {!readonly && mode === AppModeEnum.COMPLETION && dataSet.length > 0 && (+ {!readonly && mode === 'completion' && dataSet.length > 0 && (<ContextVarvalue={selectedContextVar?.key}options={promptVariablesToSelect}diff --git a/web/app/components/app/configuration/debug/__tests__/index.spec.tsx b/web/app/components/app/configuration/debug/__tests__/index.spec.tsxindex 6c5dfa75401..6a884273e9f 100644--- a/web/app/components/app/configuration/debug/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/debug/__tests__/index.spec.tsx@@ -6,7 +6,7 @@ import * as React from 'react'import Log from '@/app/components/base/chat/chat/log'import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import ConfigContext from '@/context/debug-configuration'-import { AppModeEnum, ModelModeType, TransferMethod } from '@/types/app'+import { ModelModeType, TransferMethod } from '@/types/app'import Debug from '../index'import { APP_CHAT_WITH_MULTIPLE_MODEL, APP_CHAT_WITH_MULTIPLE_MODEL_RESTART } from '../types'@@ -345,7 +345,7 @@ const createContextValue = (overrides: Partial<DebugContextValue> = {}): DebugCoappId: 'app-id',onOpenFeatures: vi.fn(),isTrailFinished: false,- mode: AppModeEnum.CHAT,+ mode: 'chat',modelModeType: ModelModeType.chat,promptMode: 'simple' as DebugContextValue['promptMode'],setPromptMode: vi.fn(),@@ -676,7 +676,7 @@ describe('Debug', () => {const { notify } = renderDebug({contextValue: {isAdvancedMode: true,- mode: AppModeEnum.CHAT,+ mode: 'chat',modelModeType: ModelModeType.completion,hasSetBlockStatus: { context: false, history: false, query: true },},@@ -693,7 +693,7 @@ describe('Debug', () => {const { notify } = renderDebug({contextValue: {isAdvancedMode: true,- mode: AppModeEnum.CHAT,+ mode: 'chat',modelModeType: ModelModeType.completion,hasSetBlockStatus: { context: false, history: true, query: false },},@@ -711,7 +711,7 @@ describe('Debug', () => {it('should render prompt value panel and no-result placeholder', () => {renderDebug({contextValue: {- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,},})@@ -722,7 +722,7 @@ describe('Debug', () => {it('should notify when required input is missing', () => {const { notify } = renderDebug({contextValue: {- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,inputs: {},modelConfig: {...createContextValue().modelConfig,@@ -752,7 +752,7 @@ describe('Debug', () => {it('should notify when local file upload is still pending', () => {const { notify } = renderDebug({contextValue: {- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,modelConfig: {...createContextValue().modelConfig,configs: {@@ -776,7 +776,7 @@ describe('Debug', () => {it('should show cannot-query-dataset warning when dataset context variable is missing', () => {renderDebug({contextValue: {- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,dataSets: [{ id: 'dataset-1' }] as DebugContextValue['dataSets'],hasSetContextVar: false,modelConfig: {@@ -800,7 +800,7 @@ describe('Debug', () => {const user = userEvent.setup()const { notify } = renderDebug({contextValue: {- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,isAdvancedMode: true,chatPromptConfig: { prompt: [{ text: 'Missing role' }] },},@@ -817,7 +817,7 @@ describe('Debug', () => {const user = userEvent.setup()const file = { ...mockState.mockFeaturesState.file, enabled: true, number_limits: 1.5 }mockState.mockFeaturesState.file = file- const { notify } = renderDebug({ contextValue: { mode: AppModeEnum.COMPLETION } })+ const { notify } = renderDebug({ contextValue: { mode: 'completion' as const } })await user.click(screen.getByRole('button', { name: 'Send' }))@@ -870,7 +870,7 @@ describe('Debug', () => {renderDebug({contextValue: {- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,promptMode: 'simple' as DebugContextValue['promptMode'],textToSpeechConfig: { enabled: true, voice: 'alloy', language: 'en' },modelConfig: {@@ -924,7 +924,7 @@ describe('Debug', () => {mockState.mockSendCompletionMessage.mockImplementation(() => undefined)const { notify } = renderDebug({contextValue: {- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,modelConfig: {...createContextValue().modelConfig,configs: {@@ -975,7 +975,7 @@ describe('Debug', () => {renderDebug({contextValue: {- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,modelConfig: {...createContextValue().modelConfig,configs: {@@ -999,7 +999,7 @@ describe('Debug', () => {handlers.onData('Completion answer', true, { messageId: 'completion-1' })handlers.onCompleted()})- renderDebug({ contextValue: { mode: AppModeEnum.COMPLETION } })+ renderDebug({ contextValue: { mode: 'completion' as const } })await user.click(screen.getByRole('button', { name: 'Send' }))await user.click(within(screen.getByRole('region', { name: 'First answer' })).getByRole('button', {@@ -1080,7 +1080,7 @@ describe('Debug', () => {it('should emit completion event in multiple-model completion mode', () => {renderDebug({contextValue: {- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,modelConfig: {...createContextValue().modelConfig,configs: {@@ -1166,7 +1166,7 @@ describe('Debug', () => {it('should update feature store according to multiple-model vision support', () => {renderDebug({contextValue: {- mode: AppModeEnum.CHAT,+ mode: 'chat',},props: {debugWithMultipleModel: true,diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsxindex 85f4a8a9d4b..6fb5602c583 100644--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/debug-item.spec.tsx@@ -3,7 +3,6 @@ import type { ModelAndParameter } from '../../types'import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { ModelStatusEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'-import { AppModeEnum } from '@/types/app'import DebugItem from '../debug-item'const mockUseDebugConfigurationContext = vi.fn()@@ -98,7 +97,7 @@ describe('DebugItem', () => {capturedModelParameterTriggerProps = nullmockUseDebugConfigurationContext.mockReturnValue({- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})mockUseDebugWithMultipleModelContext.mockReturnValue({@@ -156,7 +155,7 @@ describe('DebugItem', () => {describe('ChatItem rendering', () => {it('should render ChatItem in CHAT mode with active model', () => {- mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.CHAT })+ mockUseDebugConfigurationContext.mockReturnValue({ mode: 'chat' as const })mockModelListQuery.mockReturnValue({data: createTextGenerationModelList([{ provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.active },@@ -170,7 +169,7 @@ describe('DebugItem', () => {})it('should render ChatItem in AGENT_CHAT mode with active model', () => {- mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.AGENT_CHAT })+ mockUseDebugConfigurationContext.mockReturnValue({ mode: 'agent-chat' as const })mockModelListQuery.mockReturnValue({data: createTextGenerationModelList([{ provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.active },@@ -183,7 +182,7 @@ describe('DebugItem', () => {})it('should not render ChatItem when model is not active', () => {- mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.CHAT })+ mockUseDebugConfigurationContext.mockReturnValue({ mode: 'chat' as const })mockModelListQuery.mockReturnValue({data: createTextGenerationModelList([{ provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.disabled },@@ -196,7 +195,7 @@ describe('DebugItem', () => {})it('should not render ChatItem when provider not found', () => {- mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.CHAT })+ mockUseDebugConfigurationContext.mockReturnValue({ mode: 'chat' as const })mockModelListQuery.mockReturnValue({data: createTextGenerationModelList([{ provider: 'anthropic', model: 'claude-3', status: ModelStatusEnum.active },@@ -209,7 +208,7 @@ describe('DebugItem', () => {})it('should not render ChatItem when model not found', () => {- mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.CHAT })+ mockUseDebugConfigurationContext.mockReturnValue({ mode: 'chat' as const })mockModelListQuery.mockReturnValue({data: createTextGenerationModelList([{ provider: 'openai', model: 'gpt-4', status: ModelStatusEnum.active },@@ -224,7 +223,7 @@ describe('DebugItem', () => {describe('TextGenerationItem rendering', () => {it('should render TextGenerationItem in COMPLETION mode with active model', () => {- mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.COMPLETION })+ mockUseDebugConfigurationContext.mockReturnValue({ mode: 'completion' as const })mockModelListQuery.mockReturnValue({data: createTextGenerationModelList([{ provider: 'openai', model: 'gpt-3.5-turbo', status: ModelStatusEnum.active },@@ -238,7 +237,7 @@ describe('DebugItem', () => {})it('should not render TextGenerationItem when provider is not found', () => {- mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.COMPLETION })+ mockUseDebugConfigurationContext.mockReturnValue({ mode: 'completion' as const })mockModelListQuery.mockReturnValue({data: createTextGenerationModelList([{ provider: 'anthropic', model: 'claude-3', status: ModelStatusEnum.active },@@ -503,7 +502,7 @@ describe('DebugItem', () => {})it('should handle model with quotaExceeded status', () => {- mockUseDebugConfigurationContext.mockReturnValue({ mode: AppModeEnum.CHAT })+ mockUseDebugConfigurationContext.mockReturnValue({ mode: 'chat' as const })mockModelListQuery.mockReturnValue({data: createTextGenerationModelList([{ provider: 'anthropic', model: 'not-matching', status: ModelStatusEnum.quotaExceeded },diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsxindex f3c03c11375..e0be61c5725 100644--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/__tests__/index.spec.tsx@@ -1,3 +1,4 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { CSSProperties } from 'react'import type { ModelAndParameter } from '../../types'import type { DebugWithMultipleModelContextType } from '../context'@@ -12,7 +13,7 @@ import {DEFAULT_CHAT_PROMPT_CONFIG,DEFAULT_COMPLETION_PROMPT_CONFIG,} from '@/config'-import { AppModeEnum, ModelModeType, Resolution, TransferMethod } from '@/types/app'+import { ModelModeType, Resolution, TransferMethod } from '@/types/app'import { APP_CHAT_WITH_MULTIPLE_MODEL } from '../../types'import DebugWithMultipleModel from '../index'@@ -161,7 +162,7 @@ const createModelConfig = (promptVariables: PromptVariableWithMeta[] = []): Modetype DebugConfiguration = {onOpenFeatures: () => void- mode: AppModeEnum+ mode: AppModeinputs: InputsmodelConfig: ModelConfigreadonly: boolean@@ -172,7 +173,7 @@ const createDebugConfiguration = (overrides: Partial<DebugConfiguration> = {},): DebugConfiguration => ({onOpenFeatures: vi.fn(),- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,inputs: {},modelConfig: createModelConfig(),readonly: false,@@ -536,7 +537,7 @@ describe('DebugWithMultipleModel', () => {// ArrangemockUseDebugConfigurationContext.mockReturnValue(createDebugConfiguration({- mode: AppModeEnum.AGENT_CHAT,+ mode: 'agent-chat' as const,}),)@@ -552,7 +553,7 @@ describe('DebugWithMultipleModel', () => {// ArrangemockUseDebugConfigurationContext.mockReturnValue(createDebugConfiguration({- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,}),)const multipleModelConfigs = [createModelAndParameter()]@@ -842,7 +843,7 @@ describe('DebugWithMultipleModel', () => {it('should set full height when chat input is hidden', () => {mockUseDebugConfigurationContext.mockReturnValue(createDebugConfiguration({- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,}),)diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.tsxindex 66eb87d8acc..f93ccd94d86 100644--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.tsx+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/debug-item.tsx@@ -17,7 +17,6 @@ import {} from '@/app/components/header/account-setting/model-provider-page/declarations'import { useDebugConfigurationContext } from '@/context/debug-configuration'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import ChatItem from './chat-item'import { useDebugWithMultipleModelContext } from './context'import ModelParameterTrigger from './model-parameter-trigger'@@ -124,13 +123,13 @@ const DebugItem: FC<DebugItemProps> = ({ modelAndParameter, className, style })</DropdownMenu></div><div style={{ height: 'calc(100% - 40px)' }}>- {(mode === AppModeEnum.CHAT || mode === AppModeEnum.AGENT_CHAT) &&+ {(mode === 'chat' || mode === 'agent-chat') &¤tProvider &¤tModel &¤tModel.status === ModelStatusEnum.active && (<ChatItem modelAndParameter={modelAndParameter} />)}- {mode === AppModeEnum.COMPLETION &&+ {mode === 'completion' &¤tProvider &¤tModel &¤tModel.status === ModelStatusEnum.active && (diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/index.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/index.tsxindex 4ec954bc8e2..718118996ed 100644--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/index.tsx+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/index.tsx@@ -7,7 +7,6 @@ import ChatInputArea from '@/app/components/base/chat/chat/chat-input-area'import { useFeatures } from '@/app/components/base/features/hooks'import { useDebugConfigurationContext } from '@/context/debug-configuration'import { useEventEmitterContextContext } from '@/context/event-emitter'-import { AppModeEnum } from '@/types/app'import { APP_CHAT_WITH_MULTIPLE_MODEL } from '../types'import { useDebugWithMultipleModelContext } from './context'import { DebugWithMultipleModelContextProvider } from './context-provider'@@ -28,7 +27,7 @@ const DebugWithMultipleModel = () => {const { multipleModelConfigs, checkCanSend } = useDebugWithMultipleModelContext()const { eventEmitter } = useEventEmitterContextContext()- const isChatMode = mode === AppModeEnum.CHAT || mode === AppModeEnum.AGENT_CHAT+ const isChatMode = mode === 'chat' || mode === 'agent-chat'const handleSend = useCallback((message: string, files?: FileEntity[]) => {diff --git a/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx b/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsxindex 43041781fa3..d6049b27283 100644--- a/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/debug/debug-with-single-model/__tests__/index.spec.tsx@@ -10,7 +10,7 @@ import { CollectionType } from '@/app/components/tools/types'import { SupportUploadFileTypes } from '@/app/components/workflow/types'import { PromptMode } from '@/models/debug'import { renderWithAccountProfile as render } from '@/test/console/account-profile'-import { AgentStrategy, AppModeEnum, ModelModeType, Resolution, TransferMethod } from '@/types/app'+import { AgentStrategy, ModelModeType, Resolution, TransferMethod } from '@/types/app'import DebugWithSingleModel from '../index'// ============================================================================@@ -135,7 +135,7 @@ const mockDebugConfigContext = {appId: 'test-app-id',onOpenFeatures: vi.fn(),isTrailFinished: false,- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,modelModeType: ModelModeType.chat,promptMode: PromptMode.simple,setPromptMode: vi.fn(),diff --git a/web/app/components/app/configuration/debug/index.tsx b/web/app/components/app/configuration/debug/index.tsxindex 01f561aea73..ed1d7f64309 100644--- a/web/app/components/app/configuration/debug/index.tsx+++ b/web/app/components/app/configuration/debug/index.tsx@@ -1,4 +1,5 @@'use client'+import type { AppModelConfigPayload } from '@dify/contracts/api/console/apps/types.gen'import type { FC } from 'react'import type { DebugWithSingleModelRefType } from './debug-with-single-model'@@ -44,7 +45,7 @@ import { useEventEmitterContextContext } from '@/context/event-emitter'import { consoleQuery } from '@/service/console'import { sendCompletionMessage } from '@/service/debug'import { AppSourceType } from '@/service/share'-import { AppModeEnum, ModelModeType, TransferMethod } from '@/types/app'+import { ModelModeType, TransferMethod } from '@/types/app'import { formatBooleanInputs, promptVariablesToUserInputsForm } from '@/utils/model-config'import GroupName from '../base/group-name'import CannotQueryDataset from '../base/warning-mask/cannot-query-dataset'@@ -147,7 +148,7 @@ const Debug: FC<IDebug> = ({const [completionFiles, setCompletionFiles] = useState<VisionFile[]>([])const checkCanSend = useCallback(() => {- if (isAdvancedMode && mode !== AppModeEnum.COMPLETION) {+ if (isAdvancedMode && mode !== 'completion') {if (modelModeType === ModelModeType.completion) {if (!hasSetBlockStatus.history) {toast.error(t(($) => $['otherError.historyNoBeEmpty'], { ns: 'appDebug' }))@@ -413,9 +414,7 @@ const Debug: FC<IDebug> = ({const handleOpenLog = (item: IChatItem) => {const container =- debugWithMultipleModel || mode === AppModeEnum.COMPLETION- ? ref.current- : singleChatContainerRef.current+ debugWithMultipleModel || mode === 'completion' ? ref.current : singleChatContainerRef.currentif (container) setLogModalWidth(document.body.clientWidth - (container.clientWidth + 16) - 8)setSelectedLogItem(item)}@@ -423,9 +422,7 @@ const Debug: FC<IDebug> = ({useEffect(() => {if (!selectedLogItem) returnconst container =- debugWithMultipleModel || mode === AppModeEnum.COMPLETION- ? ref.current- : singleChatContainerRef.current+ debugWithMultipleModel || mode === 'completion' ? ref.current : singleChatContainerRef.currentif (!container) returnconst adjustModalWidth = () => {@@ -471,7 +468,7 @@ const Debug: FC<IDebug> = ({<div className="mx-2 h-3.5 w-px bg-divider-regular" /></>) : null}- {mode !== AppModeEnum.COMPLETION && (+ {mode !== 'completion' && (<>{canTestAndRun && (<Tooltip>@@ -525,14 +522,14 @@ const Debug: FC<IDebug> = ({)}</div></div>- {mode !== AppModeEnum.COMPLETION && (+ {mode !== 'completion' && (<CollapsiblePanel render={<div className="mx-3" />}><ChatUserInput inputs={inputs} /></CollapsiblePanel>)}- {mode === AppModeEnum.COMPLETION && (+ {mode === 'completion' && (<PromptValuePanel- appType={mode as AppModeEnum}+ appType={mode}onSend={handleSendTextCompletion}inputs={inputs}visionConfig={{@@ -582,7 +579,7 @@ const Debug: FC<IDebug> = ({</div>)}{/* Chat */}- {mode !== AppModeEnum.COMPLETION && (+ {mode !== 'completion' && (<div className="h-0 grow overflow-hidden"><DebugWithSingleModelref={debugWithSingleModelRef}@@ -593,7 +590,7 @@ const Debug: FC<IDebug> = ({</div>)}{/* Text Generation */}- {mode === AppModeEnum.COMPLETION && (+ {mode === 'completion' && (<>{(completionRes || isResponding) && (<>diff --git a/web/app/components/app/configuration/hooks/__tests__/use-advanced-prompt-config.spec.tsx b/web/app/components/app/configuration/hooks/__tests__/use-advanced-prompt-config.spec.tsxindex 36d3d7984d3..47088ba26d1 100644--- a/web/app/components/app/configuration/hooks/__tests__/use-advanced-prompt-config.spec.tsx+++ b/web/app/components/app/configuration/hooks/__tests__/use-advanced-prompt-config.spec.tsx@@ -7,7 +7,7 @@ import {} from '@/app/components/base/prompt-editor/constants'import { PromptMode, PromptRole } from '@/models/debug'import { fetchPromptTemplate } from '@/service/debug'-import { AppModeEnum, ModelModeType } from '@/types/app'+import { ModelModeType } from '@/types/app'import useAdvancedPromptConfig from '../use-advanced-prompt-config'vi.mock('@/service/debug', () => ({@@ -25,7 +25,7 @@ describe('useAdvancedPromptConfig', () => {const handleUserChangedPrompt = vi.fn()const { result } = renderHook(() =>useAdvancedPromptConfig({- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,modelModeType: ModelModeType.chat,modelName: 'gpt-4o',promptMode: PromptMode.advanced,@@ -55,7 +55,7 @@ describe('useAdvancedPromptConfig', () => {it('should derive simple prompt block status from the pre-prompt', () => {const { result } = renderHook(() =>useAdvancedPromptConfig({- appMode: AppModeEnum.COMPLETION,+ appMode: 'completion' as const,modelModeType: ModelModeType.completion,modelName: 'gpt-4o',promptMode: PromptMode.simple,@@ -79,7 +79,7 @@ describe('useAdvancedPromptConfig', () => {const handleUserChangedPrompt = vi.fn()const { result } = renderHook(() =>useAdvancedPromptConfig({- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,modelModeType: ModelModeType.chat,modelName: 'gpt-4o',promptMode: PromptMode.simple,@@ -118,7 +118,7 @@ describe('useAdvancedPromptConfig', () => {const { result } = renderHook(() =>useAdvancedPromptConfig({- appMode: AppModeEnum.COMPLETION,+ appMode: 'completion' as const,modelModeType: ModelModeType.completion,modelName: 'gpt-4o',promptMode: PromptMode.simple,@@ -137,7 +137,7 @@ describe('useAdvancedPromptConfig', () => {await waitFor(() => {expect(mockFetchPromptTemplate).toHaveBeenCalledWith({- appMode: AppModeEnum.COMPLETION,+ appMode: 'completion' as const,mode: ModelModeType.completion,modelName: 'gpt-4o',hasSetDataSet: true,@@ -168,7 +168,7 @@ describe('useAdvancedPromptConfig', () => {const { result } = renderHook(() =>useAdvancedPromptConfig({- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,modelModeType: ModelModeType.chat,modelName: 'gpt-4o',promptMode: PromptMode.simple,@@ -211,7 +211,7 @@ describe('useAdvancedPromptConfig', () => {const { result } = renderHook(() =>useAdvancedPromptConfig({- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,modelModeType: ModelModeType.completion,modelName: 'gpt-4o',promptMode: PromptMode.advanced,@@ -268,7 +268,7 @@ describe('useAdvancedPromptConfig', () => {const { result } = renderHook(() =>useAdvancedPromptConfig({- appMode: AppModeEnum.COMPLETION,+ appMode: 'completion' as const,modelModeType: ModelModeType.completion,modelName: 'gpt-4o',promptMode: PromptMode.advanced,diff --git a/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts b/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.tsindex 5772f408eb6..7beac405124 100644--- a/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts+++ b/web/app/components/app/configuration/hooks/__tests__/use-configuration-utils.spec.ts@@ -6,7 +6,6 @@ import { createAppDetailFixture, createAppModelConfigFixture } from '@/test/fixtimport { withSelectorKey } from '@/test/i18n-mock'import {AgentStrategy,- AppModeEnum,ModelModeType,Resolution,RETRIEVE_TYPE,@@ -133,7 +132,7 @@ describe('useConfiguration utils', () => {mockFetchCollectionList.mockResolvedValue([])mockFetchAppDetailDirect.mockResolvedValue(createAppDetailFixture({- mode: AppModeEnum.AGENT_CHAT,+ mode: 'agent-chat' as const,model_config: createAppModelConfigFixture({model: {provider: 'langgenius/openai/openai',@@ -277,7 +276,7 @@ describe('useConfiguration utils', () => {top_k: 4,} as any,deletedTools: [{ type: 'tool', provider_id: 'tool-1', tool_name: 'search' }],- mode: AppModeEnum.AGENT_CHAT,+ mode: 'agent-chat' as const,nextDataSets: [{ id: 'dataset-1' }] as any,})@@ -336,7 +335,7 @@ describe('useConfiguration utils', () => {datasets: { datasets: [] },retrieval_model: RETRIEVE_TYPE.multiWay,} as any,- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,nextDataSets: [],})@@ -369,7 +368,7 @@ describe('useConfiguration utils', () => {datasets: { datasets: [] },retrieval_model: RETRIEVE_TYPE.multiWay,} as any,- mode: AppModeEnum.CHAT,+ mode: 'chat',nextDataSets: [],})@@ -496,7 +495,7 @@ describe('useConfiguration utils', () => {])mockFetchAppDetailDirect.mockResolvedValue({deleted_tools: [],- mode: AppModeEnum.CHAT,+ mode: 'chat',model_config: createAppModelConfigFixture({prompt_type: 'advanced',chat_prompt_config: {@@ -581,7 +580,7 @@ describe('useConfiguration utils', () => {})mockFetchAppDetailDirect.mockResolvedValue({deleted_tools: [],- mode: AppModeEnum.AGENT_CHAT,+ mode: 'agent-chat' as const,model_config: createAppModelConfigFixture({prompt_type: 'simple',chat_prompt_config: { prompt: [] },@@ -642,7 +641,7 @@ describe('useConfiguration utils', () => {mockFetchCollectionList.mockResolvedValue([])mockFetchAppDetailDirect.mockResolvedValue({deleted_tools: [],- mode: AppModeEnum.CHAT,+ mode: 'chat',model_config: createAppModelConfigFixture({prompt_type: 'simple',chat_prompt_config: { prompt: [] },@@ -839,7 +838,7 @@ describe('useConfiguration utils', () => {backendModelConfig,collectionList: [],datasetConfigs: buildConfigurationDatasetConfigs({ backendModelConfig, nextDataSets: [] }),- mode: AppModeEnum.CHAT,+ mode: 'chat',nextDataSets: [],})const setPublishedConfig = vi.fn()@@ -862,7 +861,7 @@ describe('useConfiguration utils', () => {hasSetBlockStatus: { history: true, query: true },isAdvancedMode: true,isFunctionCall: false,- mode: AppModeEnum.CHAT,+ mode: 'chat',modelConfig: config.modelConfig,promptEmpty: false,promptMode: 'advanced',@@ -911,7 +910,7 @@ describe('useConfiguration utils', () => {},isAdvancedMode: true,isFunctionCall: true,- mode: AppModeEnum.CHAT,+ mode: 'chat',modelConfig: {agentConfig: {enabled: true,@@ -1019,7 +1018,7 @@ describe('useConfiguration utils', () => {},isAdvancedMode: true,isFunctionCall: false,- mode: AppModeEnum.CHAT,+ mode: 'chat',modelConfig: {configs: {prompt_template: 'hello',@@ -1080,7 +1079,7 @@ describe('useConfiguration utils', () => {handleSetVisionConfig,isAdvancedMode: true,migrateToDefaultPrompt,- mode: AppModeEnum.CHAT,+ mode: 'chat',modelConfig: {model_id: 'gpt-4o-mini',provider: 'langgenius/openai/openai',@@ -1137,7 +1136,7 @@ describe('useConfiguration utils', () => {handleSetVisionConfig,isAdvancedMode: true,migrateToDefaultPrompt,- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,modelConfig: {model_id: 'gpt-4o-mini',provider: 'langgenius/openai/openai',diff --git a/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx b/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsxindex 4067aaece94..11ebc94ba1c 100644--- a/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx+++ b/web/app/components/app/configuration/hooks/__tests__/use-configuration.spec.tsx@@ -12,7 +12,7 @@ import { seedAppDetail } from '@/test/console/query-data'import { renderHook as renderHookWithConsoleState } from '@/test/console/render'import { createAppDetailFixture, createAppModelConfigFixture } from '@/test/fixtures/app'import { createTestQueryClient } from '@/test/query-client'-import { AppModeEnum, ModelModeType } from '@/types/app'+import { ModelModeType } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import { useConfiguration } from '../use-configuration'@@ -24,7 +24,7 @@ const createRouteAppDetail = (overrides: Partial<AppDetailWithSite> = {}) =>model_config: createAppModelConfigFixture({updated_at: 1710000000,}),- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: mockAppPermissionKeys,...overrides,})@@ -252,7 +252,7 @@ describe('useConfiguration', () => {vi.mocked(consoleClient.apps.byAppId.modelConfig.post).mockResolvedValue(undefined as never)mockFetchAppDetailDirect.mockResolvedValue({deleted_tools: [],- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,model_config: createAppModelConfigFixture({prompt_type: 'advanced',chat_prompt_config: {@@ -675,7 +675,7 @@ describe('useConfiguration', () => {mockCurrentModelFeatures = ['vision', 'document', 'audio', 'video']mockFetchAppDetailDirect.mockResolvedValueOnce({deleted_tools: [],- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,model_config: createAppModelConfigFixture({prompt_type: 'simple',chat_prompt_config: { prompt: [] },@@ -788,7 +788,7 @@ describe('useConfiguration', () => {})mockFetchAppDetailDirect.mockResolvedValueOnce({deleted_tools: [],- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,model_config: createAppModelConfigFixture({prompt_type: 'simple',chat_prompt_config: { prompt: [] },diff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/load.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/load.tsindex de4b0ff46d6..4633cd27dc8 100644--- a/web/app/components/app/configuration/hooks/configuration-lifecycle/load.ts+++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/load.ts@@ -4,7 +4,6 @@ import { PromptMode } from '@/models/debug'import { consoleClient } from '@/service/console'import { fetchDatasets } from '@/service/datasets'import { fetchCollectionList } from '@/service/tools'-import { AppModeEnum } from '@/types/app'import { withCollectionIconBasePath } from '../../utils'import { buildConfigurationDatasetConfigs } from './dataset'import { normalizeChatPromptConfig, normalizeCompletionPromptConfig } from './prompt-config'@@ -24,11 +23,7 @@ export async function loadConfigurationState({const collectionList = withCollectionIconBasePath(await fetchCollectionList(), basePath)const response = await consoleClient.apps.byAppId.get({ params: { app_id: appId } })const mode = response.mode- if (- mode !== AppModeEnum.CHAT &&- mode !== AppModeEnum.AGENT_CHAT &&- mode !== AppModeEnum.COMPLETION- )+ if (mode !== 'chat' && mode !== 'agent-chat' && mode !== 'completion')throw new Error(`App mode ${mode} does not use model configuration`)const backendModelConfig = response.model_configif (!backendModelConfig) throw new Error(`App ${appId} has no model configuration`)diff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/model.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/model.tsindex 96c61847265..0da418ca535 100644--- a/web/app/components/app/configuration/hooks/configuration-lifecycle/model.ts+++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/model.ts@@ -1,11 +1,12 @@import type { TFunction } from 'i18next'+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { ModelConfig } from '@/models/debug'import type { VisionSettings } from '@/types/app'import { produce } from 'immer'import { useMemo } from 'react'import { toast } from '@/app/components/app/configuration/toast'-import { AppModeEnum, ModelModeType } from '@/types/app'+import { ModelModeType } from '@/types/app'import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'type ModelChangeHandlerOptions = {@@ -23,7 +24,7 @@ type ModelChangeHandlerOptions = {handleSetVisionConfig: (config: VisionSettings, notNoticeFormattingChanged?: boolean) => voidisAdvancedMode: booleanmigrateToDefaultPrompt: (force?: boolean, modelModeType?: ModelModeType) => Promise<void>- mode: AppModeEnum+ mode: ConfigurationAppModemodelConfig: ModelConfigresolvedModelModeType: ModelModeTypesetCompletionParams: (value: FormValue) => void@@ -61,7 +62,7 @@ export const createModelChangeHandler =}) => {if (isAdvancedMode) {if (nextModelMode === ModelModeType.completion) {- if (mode !== AppModeEnum.COMPLETION) {+ if (mode !== 'completion') {if (!completionPromptConfig.prompt?.text ||!completionPromptConfig.conversation_histories_role.assistant_prefix ||diff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/publish.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/publish.tsindex 1dde80fad2d..14fd005378c 100644--- a/web/app/components/app/configuration/hooks/configuration-lifecycle/publish.ts+++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/publish.ts@@ -1,6 +1,7 @@import type { AppModelConfigPayload } from '@dify/contracts/api/console/apps/types.gen'import type { TFunction } from 'i18next'import type { ConfigurationPublishConfig } from './types'+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { Features as FeaturesData } from '@/app/components/base/features/types'import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { DataSet } from '@/models/datasets'@@ -21,7 +22,7 @@ import { produce } from 'immer'import { toast } from '@/app/components/app/configuration/toast'import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'import { PromptMode } from '@/models/debug'-import { AgentStrategy, AppModeEnum, ModelModeType } from '@/types/app'+import { AgentStrategy, ModelModeType } from '@/types/app'import { promptVariablesToUserInputsForm } from '@/utils/model-config'import { normalizeChatPromptConfig, normalizeCompletionPromptConfig } from './prompt-config'@@ -152,7 +153,7 @@ export const createPublishHandler =hasSetBlockStatus: { history: boolean; query: boolean }isAdvancedMode: booleanisFunctionCall: boolean- mode: AppModeEnum+ mode: ConfigurationAppModemodelConfig: ModelConfigpromptEmpty: booleanpromptMode: PromptMode@@ -178,7 +179,7 @@ export const createPublishHandler =}if (isAdvancedMode &&- mode !== AppModeEnum.COMPLETION &&+ mode !== 'completion' &&resolvedModelModeType === ModelModeType.completion) {if (!hasSetBlockStatus.history) {diff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/published-config.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/published-config.tsindex c1547c951e0..55d3a37031d 100644--- a/web/app/components/app/configuration/hooks/configuration-lifecycle/published-config.ts+++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/published-config.ts@@ -3,6 +3,7 @@ import type {DeletedTool,} from '@dify/contracts/api/console/apps/types.gen'import type { ConfigurationPublishConfig } from './types'+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { Collection } from '@/app/components/tools/types'import type { DataSet } from '@/models/datasets'import type { AnnotationReplyConfig, DatasetConfigs, ModelConfig } from '@/models/debug'@@ -12,7 +13,7 @@ import {} from '@dify/contracts/api/console/apps/zod.gen'import { ANNOTATION_DEFAULT, DEFAULT_AGENT_SETTING } from '@/config'import { PromptMode } from '@/models/debug'-import { AgentStrategy, AppModeEnum } from '@/types/app'+import { AgentStrategy } from '@/types/app'import { correctModelProvider, correctToolProvider } from '@/utils'import { userInputsFormToPromptVariables } from '@/utils/model-config'import { matchesProviderReference } from '@/utils/provider-reference'@@ -50,7 +51,7 @@ function buildPublishedModelConfig({backendModelConfig: AppModelConfigResponsecollectionList: Collection[]deletedTools?: DeletedTool[]- mode: AppModeEnum+ mode: ConfigurationAppModenextDataSets: DataSet[]}): ModelConfig {const model = backendModelConfig.model@@ -107,7 +108,7 @@ function buildPublishedModelConfig({external_data_tools: externalDataTools,dataSets: nextDataSets,agentConfig:- mode === AppModeEnum.AGENT_CHAT+ mode === 'agent-chat'? {...backendModelConfig.agent_mode,enabled: true,@@ -170,7 +171,7 @@ export function buildPublishedConfig({collectionList: Collection[]datasetConfigs: DatasetConfigsdeletedTools?: DeletedTool[]- mode: AppModeEnum+ mode: ConfigurationAppModenextDataSets: DataSet[]}): ConfigurationPublishConfig {const modelConfig = buildPublishedModelConfig({diff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/types.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/types.tsindex f20be3b8d87..cb17440282a 100644--- a/web/app/components/app/configuration/hooks/configuration-lifecycle/types.ts+++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/types.ts@@ -1,6 +1,9 @@+import type { AppType } from '@/app/components/apps/app-type'import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { DatasetConfigs, ModelConfig, PromptMode } from '@/models/debug'+export type ConfigurationAppMode = Extract<AppType, 'chat' | 'agent-chat' | 'completion'>+export type ConfigurationPublishConfig = {modelConfig: ModelConfigcompletionParams: FormValuediff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-loader.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-loader.tsindex dfb378badb5..71c2c798b58 100644--- a/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-loader.ts+++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-loader.ts@@ -1,8 +1,8 @@import type { Dispatch, SetStateAction } from 'react'import type { ConfigurationPublishConfig } from './types'+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { Collection } from '@/app/components/tools/types'import type { AnnotationReplyConfig } from '@/models/debug'-import type { AppModeEnum } from '@/types/app'import { useEffect, useRef, useState } from 'react'import { basePath } from '@/utils/var'import { loadConfigurationState } from './load'@@ -13,7 +13,7 @@ type ConfigurationLoaderOperations = {setAnnotationConfig: (config: AnnotationReplyConfig, notSetFormatChanged?: boolean) => voidsetCollectionList: Dispatch<SetStateAction<Collection[]>>setHasFetchedDetail: Dispatch<SetStateAction<boolean>>- setMode: Dispatch<SetStateAction<AppModeEnum>>+ setMode: Dispatch<SetStateAction<ConfigurationAppMode>>setPublishedConfig: Dispatch<SetStateAction<ConfigurationPublishConfig | null>>syncToPublishedConfig: (config: ConfigurationPublishConfig) => void}diff --git a/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-publish.ts b/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-publish.tsindex c9e304bb384..354f70b22e6 100644--- a/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-publish.ts+++ b/web/app/components/app/configuration/hooks/configuration-lifecycle/use-configuration-publish.ts@@ -2,12 +2,13 @@ import type { TFunction } from 'i18next'import type { Dispatch, SetStateAction } from 'react'import type { ConfigurationPublishConfig } from './types'import type { AppPublisherPublishParams } from '@/app/components/app/app-publisher/types'+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { Features as FeaturesData } from '@/app/components/base/features/types'import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { DataSet } from '@/models/datasets'import type { DatasetConfigs, ModelConfig, PromptMode } from '@/models/debug'import type { ConsoleClient } from '@/service/console'-import type { AppModeEnum, ModelModeType } from '@/types/app'+import type { ModelModeType } from '@/types/app'import { useCallback } from 'react'import { createPublishHandler } from './publish'@@ -25,7 +26,7 @@ type UseConfigurationPublishParams = {hasSetBlockStatus: { history: boolean; query: boolean }isAdvancedMode: booleanisFunctionCall: boolean- mode: AppModeEnum+ mode: ConfigurationAppModemodelConfig: ModelConfigpromptEmpty: booleanpromptMode: PromptModediff --git a/web/app/components/app/configuration/hooks/use-advanced-prompt-config.ts b/web/app/components/app/configuration/hooks/use-advanced-prompt-config.tsindex 177347b386a..7f820369fa2 100644--- a/web/app/components/app/configuration/hooks/use-advanced-prompt-config.ts+++ b/web/app/components/app/configuration/hooks/use-advanced-prompt-config.ts@@ -1,3 +1,4 @@+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'import type {ChatPromptConfig,@@ -17,10 +18,10 @@ import {import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'import { PromptMode } from '@/models/debug'import { fetchPromptTemplate } from '@/service/debug'-import { AppModeEnum, ModelModeType } from '@/types/app'+import { ModelModeType } from '@/types/app'type Param = {- appMode?: AppModeEnum+ appMode?: ConfigurationAppModemodelModeType: ModelModeTypemodelName: stringpromptMode: PromptMode@@ -175,9 +176,7 @@ const useAdvancedPromptConfig = ({)if (- [AppModeEnum.ADVANCED_CHAT, AppModeEnum.AGENT_CHAT, AppModeEnum.CHAT].includes(- appMode,- ) &&+ (appMode === 'agent-chat' || appMode === 'chat') &&completionPromptConfig.conversation_histories_role.assistant_prefix &&completionPromptConfig.conversation_histories_role.user_prefix)diff --git a/web/app/components/app/configuration/hooks/use-configuration.ts b/web/app/components/app/configuration/hooks/use-configuration.tsindex ba65d4a62b8..840993dedf4 100644--- a/web/app/components/app/configuration/hooks/use-configuration.ts+++ b/web/app/components/app/configuration/hooks/use-configuration.ts@@ -1,6 +1,8 @@'use client'+import type { ConfigurationPublishConfig } from './configuration-lifecycle/types'import type { ConfigurationViewModel } from './configuration-view-model'+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { OnFeaturesChange } from '@/app/components/base/features/types'import type { Collection } from '@/app/components/tools/types'import type { Inputs, ModelConfig, PromptConfig, PromptVariable } from '@/models/debug'@@ -25,7 +27,7 @@ import {import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { PromptMode } from '@/models/debug'import { useFileUploadConfig } from '@/service/use-common'-import { AppModeEnum, ModelModeType } from '@/types/app'+import { ModelModeType } from '@/types/app'import { supportFunctionCall } from '@/utils/tool-call'import { buildConfigurationFeaturesData, getConfigurationPublishingState } from '../utils'import { buildConfigurationContextValue } from './build-configuration-context'@@ -61,7 +63,7 @@ export const useConfiguration = (): ConfigurationViewModel => {const [hasFetchedDetail, setHasFetchedDetail] = useState(false)// oxlint-disable-next-line eslint-react/use-state -- This custom hook returns a state object.const featureConfiguration = useFeatureConfigurationState()- const [mode, setMode] = useState<AppModeEnum>(AppModeEnum.CHAT)+ const [mode, setMode] = useState<ConfigurationAppMode>('chat')const [publishedConfig, setPublishedConfig] = useState<ConfigurationPublishConfig | null>(null)const [conversationId, setConversationId] = useState<string | null>('')@@ -106,7 +108,7 @@ export const useConfiguration = (): ConfigurationViewModel => {visionConfig,} = modelConfigurationconst modelModeType = modelConfig.mode- const isAgent = mode === AppModeEnum.AGENT_CHAT+ const isAgent = mode === 'agent-chat'const [collectionList, setCollectionList] = useState<Collection[]>([])// oxlint-disable-next-line eslint-react/use-state -- This custom hook returns a state object.diff --git a/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx b/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsxindex d1ad96783d0..86b3794fac5 100644--- a/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx+++ b/web/app/components/app/configuration/prompt-value-panel/__tests__/index.spec.tsx@@ -4,7 +4,7 @@ import userEvent from '@testing-library/user-event'import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import ConfigContext from '@/context/debug-configuration'-import { AppModeEnum, ModelModeType, Resolution } from '@/types/app'+import { ModelModeType, Resolution } from '@/types/app'import PromptValuePanel from '../index'const mockOnOpenFeatures = vi.fn()@@ -78,7 +78,7 @@ const baseContextValue: any = {},setInputs: mockSetInputs,canTestAndRun: true,- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,isAdvancedMode: false,completionPromptConfig: {prompt: { text: 'completion' },@@ -88,7 +88,7 @@ const baseContextValue: any = {} as anyconst defaultProps: IPromptValuePanelProps = {- appType: AppModeEnum.COMPLETION,+ appType: 'completion',onSend: mockOnSend,inputs: { textVar: 'initial', boolVar: false },visionConfig: { enabled: false, number_limits: 0, detail: Resolution.low, transfer_methods: [] },@@ -142,10 +142,10 @@ describe('PromptValuePanel', () => {it('disables run when mode is not completion', () => {renderPanel({context: {- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,},props: {- appType: AppModeEnum.CHAT,+ appType: 'chat',},})diff --git a/web/app/components/app/configuration/prompt-value-panel/index.tsx b/web/app/components/app/configuration/prompt-value-panel/index.tsxindex f8c9710c5f3..8de91ac5bc8 100644--- a/web/app/components/app/configuration/prompt-value-panel/index.tsx+++ b/web/app/components/app/configuration/prompt-value-panel/index.tsx@@ -1,5 +1,7 @@'use client'+import type { FC } from 'react'+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { Inputs } from '@/models/debug'import type { VisionFile, VisionSettings } from '@/types/app'import { Button } from '@langgenius/dify-ui/button'@@ -25,10 +27,10 @@ import FeatureBar from '@/app/components/base/features/new-feature-panel/featureimport TextGenerationImageUploader from '@/app/components/base/image-uploader/text-generation-image-uploader'import BoolInput from '@/app/components/workflow/nodes/_base/components/before-run-form/bool-input'import ConfigContext from '@/context/debug-configuration'-import { AppModeEnum, ModelModeType } from '@/types/app'+import { ModelModeType } from '@/types/app'export type IPromptValuePanelProps = {- appType: AppModeEnum+ appType: ConfigurationAppModeonSend?: () => voidinputs: InputsvisionConfig: VisionSettings@@ -93,7 +95,7 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({}, [promptVariables, inputs, setInputs])const canNotRun = useMemo(() => {- if (mode !== AppModeEnum.COMPLETION) return true+ if (mode !== 'completion') return trueif (isAdvancedMode) {if (modelModeType === ModelModeType.chat)@@ -320,7 +322,7 @@ const PromptValuePanel: FC<IPromptValuePanelProps> = ({<div className="mx-3"><FeatureBarshowFileUpload={false}- isChatMode={appType !== AppModeEnum.COMPLETION}+ isChatMode={appType !== 'completion'}onFeatureBarClick={onOpenFeatures}disabled={readonly}hideEditEntrance={readonly}diff --git a/web/app/components/app/configuration/utils.ts b/web/app/components/app/configuration/utils.tsindex c9a7f6e22ae..453ff4455c8 100644--- a/web/app/components/app/configuration/utils.ts+++ b/web/app/components/app/configuration/utils.ts@@ -1,3 +1,4 @@+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { Features as FeaturesData, FileUpload } from '@/app/components/base/features/types'import type { Collection } from '@/app/components/tools/types'import type {@@ -8,7 +9,7 @@ import type {} from '@/models/debug'import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'import { SupportUploadFileTypes } from '@/app/components/workflow/types'-import { AppModeEnum, ModelModeType, Resolution } from '@/types/app'+import { ModelModeType, Resolution } from '@/types/app'export const withCollectionIconBasePath = (collectionList: Collection[], prefix?: string) => {if (!prefix) return collectionList@@ -84,12 +85,12 @@ export const getConfigurationPublishingState = ({hasSetContextVar: booleanhasSelectedDataSets: booleanisAdvancedMode: boolean- mode: AppModeEnum+ mode: ConfigurationAppModemodelModeType: ModelModeTypepromptTemplate: string}) => {const promptEmpty = (() => {- if (mode !== AppModeEnum.COMPLETION) return false+ if (mode !== 'completion') return falseif (isAdvancedMode) {if (modelModeType === ModelModeType.chat)@@ -102,7 +103,7 @@ export const getConfigurationPublishingState = ({})()const cannotPublish = (() => {- if (mode !== AppModeEnum.COMPLETION) {+ if (mode !== 'completion') {if (!isAdvancedMode) return falseif (modelModeType === ModelModeType.completion) {@@ -118,6 +119,6 @@ export const getConfigurationPublishingState = ({return {promptEmpty,cannotPublish,- contextVarEmpty: mode === AppModeEnum.COMPLETION && hasSelectedDataSets && !hasSetContextVar,+ contextVarEmpty: mode === 'completion' && hasSelectedDataSets && !hasSetContextVar,}}diff --git a/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx b/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsxindex cc50aefb762..139d83a3730 100644--- a/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx+++ b/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx@@ -4,7 +4,6 @@ import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { trackEvent } from '@/app/components/base/amplitude'import { renderWithConsoleQuery } from '@/test/console/query-data'-import { AppModeEnum } from '@/types/app'import AppCard from '../index'vi.mock('@/app/components/base/amplitude', () => ({ trackEvent: vi.fn() }))@@ -16,7 +15,7 @@ const app = {can_trial: true,app: {id: 'app-1',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,icon_type: 'emoji',icon: '🤖',icon_background: '#FFEAD5',diff --git a/web/app/components/app/create-app-dialog/app-list/index.tsx b/web/app/components/app/create-app-dialog/app-list/index.tsxindex e62ac830f48..7b750bce2d3 100644--- a/web/app/components/app/create-app-dialog/app-list/index.tsx+++ b/web/app/components/app/create-app-dialog/app-list/index.tsx@@ -1,6 +1,7 @@'use client'import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'+import type { AppType } from '@/app/components/apps/app-type'import type { CreateAppModalProps } from '@/app/components/explore/create-app-modal'import { IconButton } from '@langgenius/dify-ui/icon-button'import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'@@ -23,7 +24,6 @@ import { workspacePermissionKeysAtom } from '@/context/permission-state'import { useCanImportAgents } from '@/features/agent-v2/permissions'import { useImportDSL } from '@/hooks/use-import-dsl'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { trackCreateApp } from '@/utils/create-app-tracking'import { hasPermission } from '@/utils/permission'import AppCard from '../app-card'@@ -62,7 +62,7 @@ const Apps = ({ onClose, onCreateFromBlank, templateMode }: AppsProps) => {searchInputRef.current?.focus()}- const [currentType, setCurrentType] = useState<AppModeEnum[]>([])+ const [currentType, setCurrentType] = useState<AppType[]>([])const [currCategory, setCurrCategory] = useState<AppCategories | string>(allCategoriesEn)const { data, isLoading } = useQuery(@@ -74,7 +74,7 @@ const Apps = ({ onClose, onCreateFromBlank, templateMode }: AppsProps) => {() =>[...(data?.recommended_apps ?? [])].filter((item) =>- templateMode ? item.app?.mode === templateMode : item.app?.mode !== AppModeEnum.AGENT,+ templateMode ? item.app?.mode === templateMode : item.app?.mode !== 'agent',).sort((a, b) => (a.position ?? 0) - (b.position ?? 0)),[data?.recommended_apps, templateMode],@@ -101,18 +101,11 @@ const Apps = ({ onClose, onCreateFromBlank, templateMode }: AppsProps) => {})if (currentType.length === 0) return filteredByCategoryreturn filteredByCategory.filter((item) => {- if (currentType.includes(AppModeEnum.CHAT) && item.app?.mode === AppModeEnum.CHAT) return true- if (- currentType.includes(AppModeEnum.ADVANCED_CHAT) &&- item.app?.mode === AppModeEnum.ADVANCED_CHAT- )- return true- if (currentType.includes(AppModeEnum.AGENT_CHAT) && item.app?.mode === AppModeEnum.AGENT_CHAT)- return true- if (currentType.includes(AppModeEnum.COMPLETION) && item.app?.mode === AppModeEnum.COMPLETION)- return true- if (currentType.includes(AppModeEnum.WORKFLOW) && item.app?.mode === AppModeEnum.WORKFLOW)- return true+ if (currentType.includes('chat') && item.app?.mode === 'chat') return true+ if (currentType.includes('advanced-chat') && item.app?.mode === 'advanced-chat') return true+ if (currentType.includes('agent-chat') && item.app?.mode === 'agent-chat') return true+ if (currentType.includes('completion') && item.app?.mode === 'completion') return true+ if (currentType.includes('workflow') && item.app?.mode === 'workflow') return truereturn false})}, [currentType, activeCategory, allCategoriesEn, data, allList])@@ -152,7 +145,7 @@ const Apps = ({ onClose, onCreateFromBlank, templateMode }: AppsProps) => {})if (!canCreateTemplate(detail.mode) ||- (templateMode ? detail.mode !== templateMode : detail.mode === AppModeEnum.AGENT)+ (templateMode ? detail.mode !== templateMode : detail.mode === 'agent'))throw new Error('Template mode does not match this picker')await handleImportDSL(diff --git a/web/app/components/app/create-app-modal/__tests__/index.spec.tsx b/web/app/components/app/create-app-modal/__tests__/index.spec.tsxindex c70fae8cbf5..a68faac6e49 100644--- a/web/app/components/app/create-app-modal/__tests__/index.spec.tsx+++ b/web/app/components/app/create-app-modal/__tests__/index.spec.tsx@@ -8,7 +8,6 @@ import { useRouter } from '@/next/navigation'import { renderWithConsoleQuery } from '@/test/console/query-data'import { mockEmojiData } from '@/test/emoji-picker'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'import { trackCreateApp } from '@/utils/create-app-tracking'import CreateAppModal from '../index'@@ -109,7 +108,7 @@ const renderModal = () => {showonClose={onClose}onCreateFromTemplate={onCreateFromTemplate}- defaultAppMode={AppModeEnum.ADVANCED_CHAT}+ defaultAppMode={'advanced-chat'}/>,)return { onClose, onCreateFromTemplate }@@ -138,7 +137,7 @@ describe('CreateAppModal', () => {it('creates an app and fires callbacks', async () => {const mockApp = createAppDetailFixture({- mode: AppModeEnum.ADVANCED_CHAT,+ mode: 'advanced-chat' as const,maintainer: 'user-1',})mockCreateApp.mockResolvedValue(mockApp)@@ -155,13 +154,13 @@ describe('CreateAppModal', () => {icon_type: 'emoji',icon: '🤖',icon_background: '#FFEAD5',- mode: AppModeEnum.ADVANCED_CHAT,+ mode: 'advanced-chat' as const,}),)expect(mockTrackCreateApp).toHaveBeenCalledWith({source: 'studio_blank',- appMode: AppModeEnum.ADVANCED_CHAT,+ appMode: 'advanced-chat' as const,})expect(onClose).toHaveBeenCalledTimes(1)await waitFor(() =>@@ -176,7 +175,7 @@ describe('CreateAppModal', () => {it('waits for create_app tracking before redirecting after blank app creation', async () => {const mockApp = createAppDetailFixture({- mode: AppModeEnum.ADVANCED_CHAT,+ mode: 'advanced-chat' as const,maintainer: 'user-1',})let resolveTracking: (() => void) | undefined@@ -196,7 +195,7 @@ describe('CreateAppModal', () => {await waitFor(() => {expect(mockTrackCreateApp).toHaveBeenCalledWith({source: 'studio_blank',- appMode: AppModeEnum.ADVANCED_CHAT,+ appMode: 'advanced-chat' as const,})})const createButton = screen.getByRole('button', { name: /app\.newApp\.Create/ })@@ -251,7 +250,7 @@ describe('CreateAppModal', () => {async ({ platform, modifier }) => {vi.spyOn(navigator, 'platform', 'get').mockReturnValue(platform)mockCreateApp.mockResolvedValue(- createAppDetailFixture({ id: 'chat-app', mode: AppModeEnum.CHAT }),+ createAppDetailFixture({ id: 'chat-app', mode: 'chat' as const }),)renderModal()@@ -288,7 +287,7 @@ describe('CreateAppModal', () => {icon_type: 'emoji',icon: '🤖',icon_background: '#F3FEE7',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})})},@@ -302,7 +301,7 @@ describe('CreateAppModal', () => {async ({ platform, modifier }) => {vi.spyOn(navigator, 'platform', 'get').mockReturnValue(platform)mockCreateApp.mockResolvedValue(- createAppDetailFixture({ id: 'reopened-app', mode: AppModeEnum.ADVANCED_CHAT }),+ createAppDetailFixture({ id: 'reopened-app', mode: 'advanced-chat' as const }),)const onClose = vi.fn()const modal = (show: boolean) => (@@ -310,7 +309,7 @@ describe('CreateAppModal', () => {show={show}onClose={onClose}onCreateFromTemplate={vi.fn()}- defaultAppMode={AppModeEnum.ADVANCED_CHAT}+ defaultAppMode={'advanced-chat'}/>)const { rerender } = render(modal(true))@@ -366,7 +365,7 @@ describe('CreateAppModal', () => {it('should switch between app types before creating a completion app', async () => {mockCreateApp.mockResolvedValue(- createAppDetailFixture({ id: 'completion-app', mode: AppModeEnum.COMPLETION }),+ createAppDetailFixture({ id: 'completion-app', mode: 'completion' as const }),)renderModal()@@ -385,7 +384,7 @@ describe('CreateAppModal', () => {expect(mockCreateApp).toHaveBeenCalledWith(expect.objectContaining({name: 'Completion App',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,}),)})@@ -416,7 +415,7 @@ describe('CreateAppModal', () => {expect(mockCreateApp).toHaveBeenCalledTimes(1)- resolveCreate?.(createAppDetailFixture({ id: 'slow-app', mode: AppModeEnum.ADVANCED_CHAT }))+ resolveCreate?.(createAppDetailFixture({ id: 'slow-app', mode: 'advanced-chat' as const }))await waitFor(() => {expect(mockGetRedirection).toHaveBeenCalledTimes(1)})diff --git a/web/app/components/app/create-app-modal/index.tsx b/web/app/components/app/create-app-modal/index.tsxindex 51178597c5e..b3843b7009d 100644--- a/web/app/components/app/create-app-modal/index.tsx+++ b/web/app/components/app/create-app-modal/index.tsx@@ -1,6 +1,7 @@'use client'import type { Hotkey } from '@tanstack/react-hotkeys'+import type { AppType } from '@/app/components/apps/app-type'import type { IconPickerValue } from '@/app/components/base/icon-picker'import { zPostAppsBody } from '@dify/contracts/api/console/apps/zod.gen'import { Button } from '@langgenius/dify-ui/button'@@ -29,7 +30,6 @@ import { systemFeaturesQueryOptions } from '@/features/system-features/client'import useTheme from '@/hooks/use-theme'import { useRouter } from '@/next/navigation'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'import { trackCreateApp } from '@/utils/create-app-tracking'import { hasPermission } from '@/utils/permission'@@ -39,17 +39,13 @@ import { CreateAppDialogShell } from '../create-app-dialog-shell'type CreateAppProps = {onClose: () => voidonCreateFromTemplate?: () => void- defaultAppMode?: AppModeEnum+ defaultAppMode?: AppType}const CREATE_APP_HOTKEY = 'Mod+Enter' satisfies Hotkey-const shouldExpandBeginnerAppTypes = (appMode?: AppModeEnum) => {- return (- appMode === AppModeEnum.CHAT ||- appMode === AppModeEnum.AGENT_CHAT ||- appMode === AppModeEnum.COMPLETION- )+const shouldExpandBeginnerAppTypes = (appMode?: AppType) => {+ return appMode === 'chat' || appMode === 'agent-chat' || appMode === 'completion'}function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppProps) {@@ -58,7 +54,7 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppPconst nameInputId = useId()const contentRef = useRef<HTMLDivElement>(null)- const [appMode, setAppMode] = useState<AppModeEnum>(defaultAppMode || AppModeEnum.ADVANCED_CHAT)+ const [appMode, setAppMode] = useState<AppType>(defaultAppMode || 'advanced-chat')const [appIcon, setAppIcon] = useState<IconPickerValue>({type: 'emoji',icon: '🤖',@@ -209,7 +205,7 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP<div><div className="flex flex-row gap-2"><AppTypeCard- active={appMode === AppModeEnum.WORKFLOW}+ active={appMode === 'workflow'}title={t(($) => $['types.workflow'], { ns: 'app' })}description={t(($) => $['newApp.workflowShortDescription'], { ns: 'app' })}icon={@@ -221,11 +217,11 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP</div>}onClick={() => {- setAppMode(AppModeEnum.WORKFLOW)+ setAppMode('workflow')}}/><AppTypeCard- active={appMode === AppModeEnum.ADVANCED_CHAT}+ active={appMode === 'advanced-chat'}title={t(($) => $['types.advanced'], { ns: 'app' })}description={t(($) => $['newApp.advancedShortDescription'], { ns: 'app' })}icon={@@ -237,7 +233,7 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP</div>}onClick={() => {- setAppMode(AppModeEnum.ADVANCED_CHAT)+ setAppMode('advanced-chat')}}/></div>@@ -261,7 +257,7 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP{isAppTypeExpanded && (<div className="flex flex-row gap-2"><AppTypeCard- active={appMode === AppModeEnum.CHAT}+ active={appMode === 'chat'}title={t(($) => $['types.chatbot'], { ns: 'app' })}description={t(($) => $['newApp.chatbotShortDescription'], { ns: 'app' })}icon={@@ -273,11 +269,11 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP</div>}onClick={() => {- setAppMode(AppModeEnum.CHAT)+ setAppMode('chat')}}/><AppTypeCard- active={appMode === AppModeEnum.AGENT_CHAT}+ active={appMode === 'agent-chat'}title={t(($) => $['types.agent'], { ns: 'app' })}description={t(($) => $['newApp.agentShortDescription'], { ns: 'app' })}icon={@@ -289,11 +285,11 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP</div>}onClick={() => {- setAppMode(AppModeEnum.AGENT_CHAT)+ setAppMode('agent-chat')}}/><AppTypeCard- active={appMode === AppModeEnum.COMPLETION}+ active={appMode === 'completion'}title={t(($) => $['newApp.completeApp'], { ns: 'app' })}description={t(($) => $['newApp.completionShortDescription'], { ns: 'app' })}icon={@@ -305,7 +301,7 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP</div>}onClick={() => {- setAppMode(AppModeEnum.COMPLETION)+ setAppMode('completion')}}/></div>@@ -400,20 +396,11 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP'repeating-linear-gradient(135deg, transparent, transparent 2px, rgba(16,24,40,0.04) 4px,transparent 3px, transparent 6px)',}}>- <AppScreenShot show={appMode === AppModeEnum.CHAT} mode={AppModeEnum.CHAT} />- <AppScreenShot- show={appMode === AppModeEnum.ADVANCED_CHAT}- mode={AppModeEnum.ADVANCED_CHAT}- />- <AppScreenShot- show={appMode === AppModeEnum.AGENT_CHAT}- mode={AppModeEnum.AGENT_CHAT}- />- <AppScreenShot- show={appMode === AppModeEnum.COMPLETION}- mode={AppModeEnum.COMPLETION}- />- <AppScreenShot show={appMode === AppModeEnum.WORKFLOW} mode={AppModeEnum.WORKFLOW} />+ <AppScreenShot show={appMode === 'chat'} mode={'chat'} />+ <AppScreenShot show={appMode === 'advanced-chat'} mode={'advanced-chat'} />+ <AppScreenShot show={appMode === 'agent-chat'} mode={'agent-chat'} />+ <AppScreenShot show={appMode === 'completion'} mode={'completion'} />+ <AppScreenShot show={appMode === 'workflow'} mode={'workflow'} /></div><div className="absolute inset-x-0 border-b border-b-divider-subtle"></div></div>@@ -479,31 +466,31 @@ function AppTypeCard({ icon, title, description, active, onClick }: AppTypeCardP)}-function AppPreview({ mode }: { mode: AppModeEnum }) {+function AppPreview({ mode }: { mode: AppType }) {const { t } = useTranslation(['app'])const previewInfo = (() => {switch (mode) {- case AppModeEnum.CHAT:+ case 'chat':return {title: t(($) => $['types.chatbot'], { ns: 'app' }),description: t(($) => $['newApp.chatbotUserDescription'], { ns: 'app' }),}- case AppModeEnum.ADVANCED_CHAT:+ case 'advanced-chat':return {title: t(($) => $['types.advanced'], { ns: 'app' }),description: t(($) => $['newApp.advancedUserDescription'], { ns: 'app' }),}- case AppModeEnum.AGENT_CHAT:+ case 'agent-chat':return {title: t(($) => $['types.agent'], { ns: 'app' }),description: t(($) => $['newApp.agentUserDescription'], { ns: 'app' }),}- case AppModeEnum.COMPLETION:+ case 'completion':return {title: t(($) => $['newApp.completeApp'], { ns: 'app' }),description: t(($) => $['newApp.completionUserDescription'], { ns: 'app' }),}- case AppModeEnum.WORKFLOW:+ case 'workflow':return {title: t(($) => $['types.workflow'], { ns: 'app' }),description: t(($) => $['newApp.workflowUserDescription'], { ns: 'app' }),@@ -525,14 +512,14 @@ function AppPreview({ mode }: { mode: AppModeEnum }) {)}-function AppScreenShot({ mode, show }: { mode: AppModeEnum; show: boolean }) {+function AppScreenShot({ mode, show }: { mode: AppType; show: boolean }) {const { theme } = useTheme()const modeToImageMap = {- [AppModeEnum.CHAT]: 'Chatbot',- [AppModeEnum.ADVANCED_CHAT]: 'Chatflow',- [AppModeEnum.AGENT_CHAT]: 'Agent',- [AppModeEnum.COMPLETION]: 'TextGenerator',- [AppModeEnum.WORKFLOW]: 'Workflow',+ chat: 'Chatbot',+ 'advanced-chat': 'Chatflow',+ 'agent-chat': 'Agent',+ completion: 'TextGenerator',+ workflow: 'Workflow',}return (<picture>diff --git a/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx b/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsxindex f8b0513da20..0a394b0b6fd 100644--- a/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx+++ b/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx@@ -4,7 +4,6 @@ import userEvent from '@testing-library/user-event'import { DSLImportMode, DSLImportStatus } from '@/models/app'import { httpErrorFromResponse } from '@/service/http-error'import { renderWithConsoleQuery } from '@/test/console/query-data'-import { AppModeEnum } from '@/types/app'import CreateFromDSLModal from '../index'import { CreateFromDSLModalTab } from '../types'@@ -163,7 +162,7 @@ describe('CreateFromDSLModal', () => {id: 'package-import',status: 'completed-with-warnings',app_id: 'agent-app',- app_mode: AppModeEnum.AGENT,+ app_mode: 'agent',warnings: [{ code: 'agent_skill_missing', path: 'skills.s_000001', message: 'Missing Skill' },],@@ -180,7 +179,7 @@ describe('CreateFromDSLModal', () => {})expect(mockResolveImportedAppRedirectionTarget).toHaveBeenCalledWith({id: 'agent-app',- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,permission_keys: undefined,})},@@ -193,7 +192,7 @@ describe('CreateFromDSLModal', () => {mockImportDSL.mockResolvedValue({id: 'import',status: 'completed',- app_mode: AppModeEnum.AGENT,+ app_mode: 'agent',})render(<CreateFromDSLModal show onClose={vi.fn()} />)const input = document.querySelector<HTMLInputElement>('input[type="file"]')@@ -309,7 +308,7 @@ describe('CreateFromDSLModal', () => {id: 'import-1',status: DSLImportStatus.COMPLETED,app_id: 'app-1',- app_mode: AppModeEnum.CHAT,+ app_mode: 'chat',permission_keys: ['app.acl.view_layout'],})@@ -336,7 +335,7 @@ describe('CreateFromDSLModal', () => {})expect(mockTrackCreateApp).toHaveBeenCalledWith({source: 'studio_upload',- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,})expect(handleSuccess).toHaveBeenCalledTimes(1)expect(handleClose).toHaveBeenCalledTimes(1)@@ -358,7 +357,7 @@ describe('CreateFromDSLModal', () => {id: 'import-no-permissions',status: DSLImportStatus.COMPLETED,app_id: 'app-no-permissions',- app_mode: AppModeEnum.WORKFLOW,+ app_mode: 'workflow',})render(@@ -375,7 +374,7 @@ describe('CreateFromDSLModal', () => {})expect(mockGetRedirection).toHaveBeenCalledWith(- { id: 'app-no-permissions', mode: AppModeEnum.WORKFLOW, permission_keys: undefined },+ { id: 'app-no-permissions', mode: 'workflow' as const, permission_keys: undefined },mockPush,{currentUserId: 'user-1',@@ -391,7 +390,7 @@ describe('CreateFromDSLModal', () => {id: 'import-2',status: DSLImportStatus.COMPLETED_WITH_WARNINGS,app_id: 'app-2',- app_mode: AppModeEnum.AGENT,+ app_mode: 'agent',permission_keys: ['app.acl.view_layout'],warnings: [{@@ -446,7 +445,7 @@ describe('CreateFromDSLModal', () => {id: 'import-file-in-flight',status: DSLImportStatus.COMPLETED,app_id: 'app-1',- app_mode: AppModeEnum.CHAT,+ app_mode: 'chat',permission_keys: ['app.acl.view_layout'],})@@ -517,7 +516,7 @@ describe('CreateFromDSLModal', () => {mockImportDSLConfirm.mockResolvedValue({status: DSLImportStatus.COMPLETED,app_id: 'app-3',- app_mode: AppModeEnum.WORKFLOW,+ app_mode: 'workflow',permission_keys: ['app.acl.view_layout'],})@@ -548,10 +547,10 @@ describe('CreateFromDSLModal', () => {})expect(mockTrackCreateApp).toHaveBeenCalledWith({source: 'studio_upload',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,})expect(mockGetRedirection).toHaveBeenCalledWith(- { id: 'app-3', mode: AppModeEnum.WORKFLOW, permission_keys: ['app.acl.view_layout'] },+ { id: 'app-3', mode: 'workflow' as const, permission_keys: ['app.acl.view_layout'] },mockPush,{currentUserId: 'user-1',@@ -569,7 +568,7 @@ describe('CreateFromDSLModal', () => {const completed = {status: DSLImportStatus.COMPLETED,app_id: 'created-app',- app_mode: AppModeEnum.WORKFLOW,+ app_mode: 'workflow',}mockImportDSL.mockResolvedValue(confirmed ? { id: 'pending-import', status: DSLImportStatus.PENDING } : completed,@@ -606,7 +605,7 @@ describe('CreateFromDSLModal', () => {mockImportDSLConfirm.mockResolvedValue({status: DSLImportStatus.COMPLETED_WITH_WARNINGS,app_id: 'agent-app-1',- app_mode: AppModeEnum.AGENT,+ app_mode: 'agent',warnings: [{code: 'agent_tool_authorization_required',@@ -618,7 +617,7 @@ describe('CreateFromDSLModal', () => {})mockResolveImportedAppRedirectionTarget.mockResolvedValueOnce({id: 'agent-app-1',- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,permission_keys: undefined,bound_agent_id: 'agent-1',})@@ -645,13 +644,13 @@ describe('CreateFromDSLModal', () => {})expect(mockResolveImportedAppRedirectionTarget).toHaveBeenCalledWith({id: 'agent-app-1',- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,permission_keys: undefined,})expect(mockGetRedirection).toHaveBeenCalledWith(expect.objectContaining({id: 'agent-app-1',- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,bound_agent_id: 'agent-1',}),mockPush,@@ -771,7 +770,7 @@ describe('CreateFromDSLModal', () => {id: 'import-in-flight',status: DSLImportStatus.COMPLETED,app_id: 'app-1',- app_mode: AppModeEnum.CHAT,+ app_mode: 'chat',permission_keys: ['app.acl.view_layout'],})})@@ -834,7 +833,7 @@ describe('CreateFromDSLModal', () => {id: 'import-confirming',status: DSLImportStatus.COMPLETED,app_id: 'app-confirming',- app_mode: AppModeEnum.WORKFLOW,+ app_mode: 'workflow',})})})@@ -882,7 +881,7 @@ describe('CreateFromDSLModal', () => {mockImportDSL.mockResolvedValue({id: 'package-import',status: 'completed',- app_mode: AppModeEnum.AGENT,+ app_mode: 'agent',})render(<CreateFromDSLModal show onClose={vi.fn()} />)expect(screen.getByText('apps-full')).toBeInTheDocument()@@ -918,7 +917,7 @@ describe('CreateFromDSLModal', () => {mockImportDSL.mockResolvedValue({id: 'package-import',status: 'completed',- app_mode: AppModeEnum.AGENT,+ app_mode: 'agent',})render(<CreateFromDSLModal show onClose={vi.fn()} />)expect(diff --git a/web/app/components/app/create-from-dsl-modal/index.tsx b/web/app/components/app/create-from-dsl-modal/index.tsxindex 5ba6a84a6ae..84a9c3f3cda 100644--- a/web/app/components/app/create-from-dsl-modal/index.tsx+++ b/web/app/components/app/create-from-dsl-modal/index.tsx@@ -1,8 +1,7 @@'use client'-import type { AppImportPayload, Import } from '@dify/contracts/api/console/apps/types.gen'+import type { AppImportPayload, AppMode, Import } from '@dify/contracts/api/console/apps/types.gen'import type { Hotkey } from '@tanstack/react-hotkeys'-import type { AppModeEnum } from '@/types/app'import { Button } from '@langgenius/dify-ui/button'import {Dialog,@@ -30,7 +29,6 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { useRouter } from '@/next/navigation'import { consoleQuery } from '@/service/console'-import { AppModeEnum as AppMode } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'import { trackCreateApp } from '@/utils/create-app-tracking'import { getErrorMessage } from '@/utils/error-message'@@ -65,20 +63,20 @@ type ImportSource =const CREATE_FROM_DSL_HOTKEY = 'Mod+Enter' satisfies Hotkey-function getImportedAppMode(mode?: string | null): AppModeEnum | undefined {+function getImportedAppMode(mode?: string | null): AppMode | undefined {switch (mode) {- case AppMode.COMPLETION:- return AppMode.COMPLETION- case AppMode.WORKFLOW:- return AppMode.WORKFLOW- case AppMode.CHAT:- return AppMode.CHAT- case AppMode.ADVANCED_CHAT:- return AppMode.ADVANCED_CHAT- case AppMode.AGENT_CHAT:- return AppMode.AGENT_CHAT- case AppMode.AGENT:- return AppMode.AGENT+ case 'completion':+ return 'completion'+ case 'workflow':+ return 'workflow'+ case 'chat':+ return 'chat'+ case 'advanced-chat':+ return 'advanced-chat'+ case 'agent-chat':+ return 'agent-chat'+ case 'agent':+ return 'agent'default:return undefined}diff --git a/web/app/components/app/deploy/__tests__/index.spec.tsx b/web/app/components/app/deploy/__tests__/index.spec.tsxindex 37b925cfc41..df8515bc0cd 100644--- a/web/app/components/app/deploy/__tests__/index.spec.tsx+++ b/web/app/components/app/deploy/__tests__/index.spec.tsx@@ -33,7 +33,6 @@ import {seedAppDetail,} from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import AppDeploy from '..'import { EnvironmentTable } from '../environment-table'@@ -745,7 +744,7 @@ function render(queryClient,createAppDetailFixture({...mockBuiltInEnvironment.appDetail,- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow',permission_keys: appPermissionKeys,}),)diff --git a/web/app/components/app/deploy/index.tsx b/web/app/components/app/deploy/index.tsxindex 705ed19863e..e16ef1488bb 100644--- a/web/app/components/app/deploy/index.tsx+++ b/web/app/components/app/deploy/index.tsx@@ -18,7 +18,6 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'import { getDocLanguage } from '@/i18n/language'import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { getAppACLCapabilities } from '@/utils/permission'import { BuiltInEnvironmentCard } from './built-in-environment-card'import { EnvironmentTable } from './environment-table'@@ -170,10 +169,7 @@ export default function AppDeploy() {workspacePermissionKeys,})- if (- (appDetail.mode !== AppModeEnum.WORKFLOW && appDetail.mode !== AppModeEnum.ADVANCED_CHAT) ||- !canDeploy- )+ if ((appDetail.mode !== 'workflow' && appDetail.mode !== 'advanced-chat') || !canDeploy)return nullreturn (diff --git a/web/app/components/app/log-annotation/__tests__/index.spec.tsx b/web/app/components/app/log-annotation/__tests__/index.spec.tsxindex 939c69e9086..49fac6e718c 100644--- a/web/app/components/app/log-annotation/__tests__/index.spec.tsx+++ b/web/app/components/app/log-annotation/__tests__/index.spec.tsx@@ -6,7 +6,6 @@ import { PageType } from '@/app/components/base/features/new-feature-panel/annotimport { consoleQuery } from '@/service/console'import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'import { createAppDetailFixture, createAppSiteFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import LogAnnotation from '../index'vi.mock('@/app/components/app/annotation', () => ({@@ -75,7 +74,7 @@ describe('LogAnnotation', () => {it('should render log content without the old page tabs', () => {// Arrange- appDetail = createMockApp({ mode: AppModeEnum.CHAT })+ appDetail = createMockApp({ mode: 'chat' })// Actrender(<LogAnnotation appId="app-123" pageType={PageType.log} />)@@ -88,7 +87,7 @@ describe('LogAnnotation', () => {it('should render completion logs without the old page tabs', () => {// Arrange- appDetail = createMockApp({ mode: AppModeEnum.COMPLETION })+ appDetail = createMockApp({ mode: 'completion' as const })// Actrender(<LogAnnotation appId="app-123" pageType={PageType.log} />)@@ -101,7 +100,7 @@ describe('LogAnnotation', () => {it('should hide tabs and render workflow log in workflow mode', () => {// Arrange- appDetail = createMockApp({ mode: AppModeEnum.WORKFLOW })+ appDetail = createMockApp({ mode: 'workflow' as const })// Actrender(<LogAnnotation appId="app-123" pageType={PageType.log} />)@@ -116,7 +115,7 @@ describe('LogAnnotation', () => {describe('Props', () => {it('should render log content when page type is log', () => {// Arrange- appDetail = createMockApp({ mode: AppModeEnum.CHAT })+ appDetail = createMockApp({ mode: 'chat' })// Actrender(<LogAnnotation appId="app-123" pageType={PageType.log} />)@@ -128,7 +127,7 @@ describe('LogAnnotation', () => {it('should render annotation content when page type is annotation', () => {// Arrange- appDetail = createMockApp({ mode: AppModeEnum.CHAT })+ appDetail = createMockApp({ mode: 'chat' })// Actrender(<LogAnnotation appId="app-123" pageType={PageType.annotation} />)diff --git a/web/app/components/app/log-annotation/index.tsx b/web/app/components/app/log-annotation/index.tsxindex 325d8f36b6e..fc2272d2fe1 100644--- a/web/app/components/app/log-annotation/index.tsx+++ b/web/app/components/app/log-annotation/index.tsx@@ -1,4 +1,5 @@'use client'+import type { FC } from 'react'import { useSuspenseQuery } from '@tanstack/react-query'import * as React from 'react'@@ -7,7 +8,6 @@ import Log from '@/app/components/app/log'import WorkflowLog from '@/app/components/app/workflow-log'import { PageType } from '@/app/components/base/features/new-feature-panel/annotation-reply/type'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'type Props = Readonly<{appId: string@@ -24,11 +24,11 @@ const LogAnnotation: FC<Props> = ({ appId, pageType }) => {return (<div className="flex h-full flex-col px-6 pt-3"><div className="h-0 grow">- {pageType === PageType.log && appDetail.mode !== AppModeEnum.WORKFLOW && (+ {pageType === PageType.log && appDetail.mode !== 'workflow' && (<Log appDetail={appDetail} />)}{pageType === PageType.annotation && <Annotation appDetail={appDetail} />}- {pageType === PageType.log && appDetail.mode === AppModeEnum.WORKFLOW && (+ {pageType === PageType.log && appDetail.mode === 'workflow' && (<WorkflowLog appDetail={appDetail} />)}</div>diff --git a/web/app/components/app/log/__tests__/empty-element.spec.tsx b/web/app/components/app/log/__tests__/empty-element.spec.tsxindex 6f48de616c5..ddff1dd6759 100644--- a/web/app/components/app/log/__tests__/empty-element.spec.tsx+++ b/web/app/components/app/log/__tests__/empty-element.spec.tsx@@ -1,8 +1,7 @@-import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'+import type { AppDetailWithSite, AppMode } from '@dify/contracts/api/console/apps/types.gen'import { screen } from '@testing-library/react'import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { createAppDetailFixture, createAppSiteFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import EmptyElement from '../empty-element'vi.mock('react-i18next', async () => {@@ -39,7 +38,7 @@ vi.mock('@/utils/var', () => ({}))describe('EmptyElement', () => {- const createMockAppDetail = (mode: AppModeEnum) =>+ const createMockAppDetail = (mode: AppMode) =>createAppDetailFixture({id: 'test-app-id',name: 'Test App',@@ -59,14 +58,14 @@ describe('EmptyElement', () => {describe('Rendering', () => {it('should render empty element with title', () => {- const appDetail = createMockAppDetail(AppModeEnum.CHAT)+ const appDetail = createMockAppDetail('chat')render(<EmptyElement appDetail={appDetail} />)expect(screen.getByText('table.empty.element.title')).toBeInTheDocument()})it('should render Trans component with i18n key', () => {- const appDetail = createMockAppDetail(AppModeEnum.CHAT)+ const appDetail = createMockAppDetail('chat')render(<EmptyElement appDetail={appDetail} />)expect(screen.getByText('table.empty.element.content', { exact: false })).toBeInTheDocument()@@ -75,7 +74,7 @@ describe('EmptyElement', () => {describe('App Mode Handling', () => {it('should use CHAT mode for chat apps', () => {- const appDetail = createMockAppDetail(AppModeEnum.CHAT)+ const appDetail = createMockAppDetail('chat')render(<EmptyElement appDetail={appDetail} />)const link = screen.getAllByRole('link')[0]@@ -83,7 +82,7 @@ describe('EmptyElement', () => {})it('should use COMPLETION mode for completion apps', () => {- const appDetail = createMockAppDetail(AppModeEnum.COMPLETION)+ const appDetail = createMockAppDetail('completion')render(<EmptyElement appDetail={appDetail} />)const link = screen.getAllByRole('link')[0]@@ -91,7 +90,7 @@ describe('EmptyElement', () => {})it('should use WORKFLOW mode for workflow apps', () => {- const appDetail = createMockAppDetail(AppModeEnum.WORKFLOW)+ const appDetail = createMockAppDetail('workflow')render(<EmptyElement appDetail={appDetail} />)const link = screen.getAllByRole('link')[0]@@ -99,7 +98,7 @@ describe('EmptyElement', () => {})it('should use CHAT mode for advanced-chat apps', () => {- const appDetail = createMockAppDetail(AppModeEnum.ADVANCED_CHAT)+ const appDetail = createMockAppDetail('advanced-chat')render(<EmptyElement appDetail={appDetail} />)const link = screen.getAllByRole('link')[0]@@ -107,7 +106,7 @@ describe('EmptyElement', () => {})it('should use CHAT mode for agent-chat apps', () => {- const appDetail = createMockAppDetail(AppModeEnum.AGENT_CHAT)+ const appDetail = createMockAppDetail('agent-chat')render(<EmptyElement appDetail={appDetail} />)const link = screen.getAllByRole('link')[0]@@ -128,7 +127,7 @@ describe('EmptyElement', () => {describe('Links', () => {it('should render share link with correct attributes', () => {- const appDetail = createMockAppDetail(AppModeEnum.CHAT)+ const appDetail = createMockAppDetail('chat')render(<EmptyElement appDetail={appDetail} />)const links = screen.getAllByRole('link')@@ -139,7 +138,7 @@ describe('EmptyElement', () => {})it('should render test link with redirection path', () => {- const appDetail = createMockAppDetail(AppModeEnum.CHAT)+ const appDetail = createMockAppDetail('chat')render(<EmptyElement appDetail={appDetail} />)const links = screen.getAllByRole('link')diff --git a/web/app/components/app/log/__tests__/index.spec.tsx b/web/app/components/app/log/__tests__/index.spec.tsxindex 99f9894307c..035b692d01f 100644--- a/web/app/components/app/log/__tests__/index.spec.tsx+++ b/web/app/components/app/log/__tests__/index.spec.tsx@@ -3,7 +3,6 @@ import { fireEvent, render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import dayjs from 'dayjs'import { APP_PAGE_LIMIT } from '@/config'-import { AppModeEnum } from '@/types/app'import Logs from '../index'vi.mock('@/context/i18n', () => ({@@ -94,7 +93,7 @@ describe('Logs', () => {appDetail={{id: 'app-1',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,} as any}/>,@@ -125,7 +124,7 @@ describe('Logs', () => {appDetail={{id: 'app-2',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,} as any}/>,@@ -150,7 +149,7 @@ describe('Logs', () => {appDetail={{id: 'app-3',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,} as any}/>,@@ -174,7 +173,7 @@ describe('Logs', () => {appDetail={{id: 'app-sandbox-last-30-days',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,} as any}/>,@@ -200,7 +199,7 @@ describe('Logs', () => {const user = userEvent.setup()const appDetail = {id: 'app-period-transition',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,} as anymockUseChatConversations.mockReturnValue({data: { total: 0 },diff --git a/web/app/components/app/log/__tests__/list.spec.tsx b/web/app/components/app/log/__tests__/list.spec.tsxindex 58fa91eb8ef..25d55db8ed0 100644--- a/web/app/components/app/log/__tests__/list.spec.tsx+++ b/web/app/components/app/log/__tests__/list.spec.tsx@@ -8,7 +8,6 @@ import { QueryClientTestProvider } from '@/test/console/query-provider'import { render } from '@/test/console/render'import { createAppDetailFixture } from '@/test/fixtures/app'import { renderWithNuqs } from '@/test/nuqs-testing'-import { AppModeEnum } from '@/types/app'import ConversationList from '../list'const mockFetchChatMessages = vi.fn()@@ -304,7 +303,7 @@ const createChatMessage = (id: string, overrides: Record<string, unknown> = {})})const renderConversationList = ({- appDetail = { id: 'app-1', mode: AppModeEnum.CHAT } as any,+ appDetail = { id: 'app-1', mode: 'chat' as const } as any,logs = createLogs() as any,searchParams = '?page=2',}: {@@ -518,36 +517,39 @@ describe('ConversationList', () => {)it.each([- ['chatbot', AppModeEnum.CHAT, 'false'],- ['agent', AppModeEnum.AGENT_CHAT, 'false'],- ['chatflow', AppModeEnum.ADVANCED_CHAT, 'true'],- ])('should expose run details only for %s conversation answers', async (_, mode, expected) => {- mockChatConversationDetail = {- id: 'conversation-1',- created_at: 1710000000,- model_config: {- model: 'gpt-4o',- configs: {- introduction: 'Hello there',+ ['chatbot', 'chat', 'false'],+ ['agent', 'agent-chat', 'false'],+ ['chatflow', 'advanced-chat', 'true'],+ ] as const)(+ 'should expose run details only for %s conversation answers',+ async (_, mode, expected) => {+ mockChatConversationDetail = {+ id: 'conversation-1',+ created_at: 1710000000,+ model_config: {+ model: 'gpt-4o',+ configs: {+ introduction: 'Hello there',+ },+ user_input_form: [],},- user_input_form: [],- },- message: {- inputs: {},- },- }- mockFetchChatMessages.mockResolvedValue({- data: [createChatMessage('message-1')],- has_more: false,- })+ message: {+ inputs: {},+ },+ }+ mockFetchChatMessages.mockResolvedValue({+ data: [createChatMessage('message-1')],+ has_more: false,+ })- renderConversationList({- appDetail: { id: 'app-1', mode } as any,- searchParams: '?conversation_id=conversation-1',- })+ renderConversationList({+ appDetail: { id: 'app-1', mode } as any,+ searchParams: '?conversation_id=conversation-1',+ })- expect(await screen.findByTestId('chat-panel')).toHaveAttribute('data-log-enabled', expected)- })+ expect(await screen.findByTestId('chat-panel')).toHaveAttribute('data-log-enabled', expected)+ },+ )it('should render completion details and refetch after feedback updates', async () => {mockCompletionConversationDetail = {@@ -575,7 +577,7 @@ describe('ConversationList', () => {}renderConversationList({- appDetail: { id: 'app-1', mode: AppModeEnum.COMPLETION } as any,+ appDetail: { id: 'app-1', mode: 'completion' as const } as any,logs: createCompletionLogs() as any,searchParams: '?page=2&conversation_id=conversation-1',})@@ -605,7 +607,7 @@ describe('ConversationList', () => {it('should render chatflow status cells and feedback counters for advanced chat logs', () => {renderConversationList({- appDetail: { id: 'app-1', mode: AppModeEnum.ADVANCED_CHAT } as any,+ appDetail: { id: 'app-1', mode: 'advanced-chat' as const } as any,logs: {data: [{@@ -744,7 +746,7 @@ describe('ConversationList', () => {})})- it.each(['workflow', 'agent', 'prompt'])(+ it.each(['workflow', 'agent', 'prompt'] as const)('should open and close the selected %s log within the conversation',async (kind) => {mockChatConversationDetail = {@@ -753,7 +755,7 @@ describe('ConversationList', () => {message: { inputs: {} },}renderConversationList({- appDetail: { id: 'app-1', mode: AppModeEnum.ADVANCED_CHAT },+ appDetail: { id: 'app-1', mode: 'advanced-chat' as const },searchParams: '?conversation_id=conversation-1',})const user = userEvent.setup()@@ -776,7 +778,7 @@ describe('ConversationList', () => {message: { inputs: {} },}renderConversationList({- appDetail: { id: 'app-1', mode: AppModeEnum.ADVANCED_CHAT },+ appDetail: { id: 'app-1', mode: 'advanced-chat' as const },searchParams: '?conversation_id=conversation-1',})const user = userEvent.setup()@@ -791,7 +793,7 @@ describe('ConversationList', () => {it('should clear a selected log when URL navigation changes or closes the conversation', async () => {const user = userEvent.setup()const queryClient = createAccountProfileQueryClient({ timezone: 'Asia/Shanghai' })- const appDetail = createAppDetailFixture({ mode: AppModeEnum.ADVANCED_CHAT })+ const appDetail = createAppDetailFixture({ mode: 'advanced-chat' as const })const view = (searchParams: string) => (<NuqsTestingAdapter searchParams={searchParams} hasMemory><QueryClientTestProvider queryClient={queryClient}>diff --git a/web/app/components/app/log/empty-element.tsx b/web/app/components/app/log/empty-element.tsxindex 3a692b63430..15bbab6ae5e 100644--- a/web/app/components/app/log/empty-element.tsx+++ b/web/app/components/app/log/empty-element.tsx@@ -10,7 +10,6 @@ import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import Link from '@/next/link'-import { AppModeEnum } from '@/types/app'import { getRedirectionPath } from '@/utils/app-redirection'import { basePath } from '@/utils/var'@@ -46,8 +45,7 @@ const EmptyElement: FC<{ appDetail: AppDetailWithSite }> = ({ appDetail }) => {const isRbacEnabled = systemFeatures.rbac_enabledconst getWebAppType = (appType: AppDetailWithSite['mode']) => {- if (appType !== AppModeEnum.COMPLETION && appType !== AppModeEnum.WORKFLOW)- return AppModeEnum.CHAT+ if (appType !== 'completion' && appType !== 'workflow') return 'chat'return appType}diff --git a/web/app/components/app/log/index.tsx b/web/app/components/app/log/index.tsxindex 6584fe1acb2..714253fe498 100644--- a/web/app/components/app/log/index.tsx+++ b/web/app/components/app/log/index.tsx@@ -14,7 +14,6 @@ import { APP_PAGE_LIMIT } from '@/config'import { useDocLink } from '@/context/i18n'import { usePathname, useRouter, useSearchParams } from '@/next/navigation'import { useChatConversations, useCompletionConversations } from '@/service/use-log'-import { AppModeEnum } from '@/types/app'import PageTitle from '../log-annotation/page-title'import {resolveLogTimePeriod,@@ -96,7 +95,7 @@ const Logs: FC<ILogsProps> = ({ appDetail }) => {}, [appDetail.id, currPage, limit, queryParams])// Get the app type first- const isChatMode = appDetail.mode !== AppModeEnum.COMPLETION+ const isChatMode = appDetail.mode !== 'completion'const query = {page: currPage + 1,diff --git a/web/app/components/app/log/list.tsx b/web/app/components/app/log/list.tsxindex 6265ceced0d..9d27fa5b043 100644--- a/web/app/components/app/log/list.tsx+++ b/web/app/components/app/log/list.tsx@@ -61,7 +61,6 @@ import {} from '@/service/log'import { AppSourceType } from '@/service/share'import { useChatConversationDetail, useCompletionConversationDetail } from '@/service/use-log'-import { AppModeEnum } from '@/types/app'import PromptLogModal from '../../base/prompt-log-modal'import {applyAnnotationAdded,@@ -301,12 +300,7 @@ function DetailPanel({ appDetail, detail, onClose, onFeedback }: IDetailPanel) {// Only load initial messages, don't auto-load moreuseEffect(() => {- if (- appDetail.id &&- detail.id &&- appDetail.mode !== AppModeEnum.COMPLETION &&- !fetchInitiated.current- ) {+ if (appDetail.id && detail.id && appDetail.mode !== 'completion' && !fetchInitiated.current) {// Mark as initialized, but don't auto-load more messagesfetchInitiated.current = true// Still call fetchData to get initial messages@@ -400,8 +394,8 @@ function DetailPanel({ appDetail, detail, onClose, onFeedback }: IDetailPanel) {}}, [hasMore, isLoading, loadMoreMessages])- const isChatMode = appDetail.mode !== AppModeEnum.COMPLETION- const isAdvanced = appDetail.mode === AppModeEnum.ADVANCED_CHAT+ const isChatMode = appDetail.mode !== 'completion'+ const isAdvanced = appDetail.mode === 'advanced-chat'const logKind = selectedLogItem?.workflow_run_id? 'workflow': selectedLogItem?.agent_thoughts?.length@@ -752,8 +746,8 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })const closingConversationIdRef = useRef<string | null>(null)const pendingConversationIdRef = useRef<string | null>(null)const pendingConversationCacheRef = useRef<ConversationSelection | undefined>(undefined)- const isChatMode = appDetail.mode !== AppModeEnum.COMPLETION // Whether the app is a chat app- const isChatflow = appDetail.mode === AppModeEnum.ADVANCED_CHAT // Whether the app is a chatflow app+ const isChatMode = appDetail.mode !== 'completion' // Whether the app is a chat app+ const isChatflow = appDetail.mode === 'advanced-chat' // Whether the app is a chatflow appconst activeConversationId =conversationIdInUrl ?? pendingConversationIdRef.current ?? currentConversation?.iddiff --git a/web/app/components/app/overview/customize/index.tsx b/web/app/components/app/overview/customize/index.tsxindex 7cafdf686ea..cd010679be7 100644--- a/web/app/components/app/overview/customize/index.tsx+++ b/web/app/components/app/overview/customize/index.tsx@@ -1,4 +1,5 @@'use client'+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { ReactNode } from 'react'import { Button, buttonVariants } from '@langgenius/dify-ui/button'@@ -14,7 +15,6 @@ import {import { IconButton } from '@langgenius/dify-ui/icon-button'import { useTranslation } from 'react-i18next'import { useDocLink } from '@/context/i18n'-import { AppModeEnum } from '@/types/app'type CustomizeDialogProps = {disabled?: boolean@@ -62,7 +62,7 @@ export function CustomizeDialog({}: CustomizeDialogProps) {const { t } = useTranslation(['appOverview', 'common'])const docLink = useDocLink()- const isChatApp = mode === AppModeEnum.CHAT || mode === AppModeEnum.ADVANCED_CHAT+ const isChatApp = mode === 'chat' || mode === 'advanced-chat'const repository =sourceCodeRepository ?? (isChatApp ? 'webapp-conversation' : 'webapp-text-generator')const apiDocLink = docLink('/api-reference/guides/get-started')diff --git a/web/app/components/app/overview/settings/__tests__/index.spec.tsx b/web/app/components/app/overview/settings/__tests__/index.spec.tsxindex 7ed09d22b48..3f8e464e248 100644--- a/web/app/components/app/overview/settings/__tests__/index.spec.tsx+++ b/web/app/components/app/overview/settings/__tests__/index.spec.tsx@@ -10,7 +10,6 @@ import {renderWithConsoleQuery as renderWithoutPricing,} from '@/test/console/query-data'import { createAppSiteFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { SettingsDialog } from '../index'const onPricingUrlUpdate = vi.hoisted(() => vi.fn())@@ -68,7 +67,7 @@ const mockAppInfo = {show_workflow_steps: true,use_icon_as_answer_icon: true,},- mode: AppModeEnum.ADVANCED_CHAT,+ mode: 'advanced-chat' as const,} satisfies SettingsAppInfoconst triggerName = 'navigation.settings.settings'diff --git a/web/app/components/app/overview/settings/index.tsx b/web/app/components/app/overview/settings/index.tsxindex b517e4cfe66..cb5661b42d7 100644--- a/web/app/components/app/overview/settings/index.tsx+++ b/web/app/components/app/overview/settings/index.tsx@@ -63,7 +63,6 @@ import { deploymentEditionAtom } from '@/features/system-features/state'import { languages } from '@/i18n/language'import Link from '@/next/link'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'type SettingsDialogProps = {isChat: boolean@@ -110,10 +109,10 @@ export type SettingsAppInfo = {const INPUT_PLACEHOLDER_MAX_LENGTH = 64const INPUT_PLACEHOLDER_SUPPORTED_MODES: ReadonlyArray<AppDetailWithSite['mode']> = [- AppModeEnum.CHAT,- AppModeEnum.AGENT_CHAT,- AppModeEnum.ADVANCED_CHAT,-]+ 'chat',+ 'agent-chat',+ 'advanced-chat',+] as constconst prefixSettings = 'overview.appInfo.settings'type SelectOption = {@@ -484,12 +483,7 @@ function SettingsForm({</FieldLabel><SwitchreadOnly={pending}- disabled={- !(- appInfo.mode === AppModeEnum.WORKFLOW ||- appInfo.mode === AppModeEnum.ADVANCED_CHAT- )- }+ disabled={!(appInfo.mode === 'workflow' || appInfo.mode === 'advanced-chat')}checked={inputInfo.show_workflow_steps}onCheckedChange={(v) =>setInputInfo((item) => ({ ...item, show_workflow_steps: v }))diff --git a/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsxindex ef1220263bb..e0642948ec4 100644--- a/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx+++ b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx@@ -5,7 +5,6 @@ import userEvent from '@testing-library/user-event'import * as React from 'react'import { renderWithConsoleQuery } from '@/test/console/query-data'import { mockEmojiData } from '@/test/emoji-picker'-import { AppModeEnum } from '@/types/app'import SwitchAppModal from '../index'const mockPush = vi.fn()@@ -84,7 +83,7 @@ const createMockApp = (overrides: Partial<AppPartial> = {}): AppPartial => ({icon_background: '#FFEAD5',icon_url: null,use_icon_as_answer_icon: false,- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,created_at: Date.now(),updated_at: Date.now(),tags: [],diff --git a/web/app/components/app/switch-app-modal/index.tsx b/web/app/components/app/switch-app-modal/index.tsxindex 525054bd992..4f9c40ec578 100644--- a/web/app/components/app/switch-app-modal/index.tsx+++ b/web/app/components/app/switch-app-modal/index.tsx@@ -30,7 +30,6 @@ import { toast } from '@/app/notifications'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { useRouter } from '@/next/navigation'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'type SwitchAppModalProps = {@@ -105,10 +104,7 @@ const SwitchAppModal = ({ show, sourceApp, onClose }: SwitchAppModalProps) => {getRedirection({id: newAppID,- mode:- sourceApp.mode === AppModeEnum.COMPLETION- ? AppModeEnum.WORKFLOW- : AppModeEnum.ADVANCED_CHAT,+ mode: sourceApp.mode === 'completion' ? 'workflow' : 'advanced-chat',permission_keys,},removeOriginal ? replace : push,diff --git a/web/app/components/app/type-selector/__tests__/index.spec.tsx b/web/app/components/app/type-selector/__tests__/index.spec.tsxindex 54cfe4b2de3..9681c0115e1 100644--- a/web/app/components/app/type-selector/__tests__/index.spec.tsx+++ b/web/app/components/app/type-selector/__tests__/index.spec.tsx@@ -1,6 +1,6 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'import * as React from 'react'-import { AppModeEnum } from '@/types/app'import AppTypeSelector, { AppTypeLabel } from '../index'describe('AppTypeSelector', () => {@@ -21,16 +21,14 @@ describe('AppTypeSelector', () => {// Covers prop-driven trigger variants (empty, single, multiple).describe('Props', () => {it('should render selected type label and clear button when a single type is selected', () => {- render(<AppTypeSelector value={[AppModeEnum.CHAT]} onChange={vi.fn()} />)+ render(<AppTypeSelector value={['chat'] as const} onChange={vi.fn()} />)expect(screen.getByText('app.typeSelector.chatbot')).toBeInTheDocument()expect(screen.getByRole('button', { name: 'common.operation.clear' })).toBeInTheDocument()})it('should render icon-only trigger when multiple types are selected', () => {- render(- <AppTypeSelector value={[AppModeEnum.CHAT, AppModeEnum.WORKFLOW]} onChange={vi.fn()} />,- )+ render(<AppTypeSelector value={['chat', 'workflow'] as const} onChange={vi.fn()} />)expect(screen.queryByText('app.typeSelector.all')).not.toBeInTheDocument()expect(screen.queryByText('app.typeSelector.chatbot')).not.toBeInTheDocument()@@ -65,12 +63,12 @@ describe('AppTypeSelector', () => {within(screen.getByRole('list')).getByRole('button', { name: 'app.typeSelector.workflow' }),)- expect(onChange).toHaveBeenCalledWith([AppModeEnum.WORKFLOW])+ expect(onChange).toHaveBeenCalledWith(['workflow'] as const)})it('should call onChange with removed type when selecting an already-selected item', () => {const onChange = vi.fn()- render(<AppTypeSelector value={[AppModeEnum.WORKFLOW]} onChange={onChange} />)+ render(<AppTypeSelector value={['workflow'] as const} onChange={onChange} />)fireEvent.click(screen.getByRole('button', { name: 'app.typeSelector.workflow' }))fireEvent.click(@@ -82,19 +80,19 @@ describe('AppTypeSelector', () => {it('should call onChange with appended type when selecting an additional item', () => {const onChange = vi.fn()- render(<AppTypeSelector value={[AppModeEnum.CHAT]} onChange={onChange} />)+ render(<AppTypeSelector value={['chat'] as const} onChange={onChange} />)fireEvent.click(screen.getByRole('button', { name: 'app.typeSelector.chatbot' }))fireEvent.click(within(screen.getByRole('list')).getByRole('button', { name: 'app.typeSelector.agent' }),)- expect(onChange).toHaveBeenCalledWith([AppModeEnum.CHAT, AppModeEnum.AGENT_CHAT])+ expect(onChange).toHaveBeenCalledWith(['chat', 'agent-chat'] as const)})it('should clear selection without opening the dropdown when clicking clear button', () => {const onChange = vi.fn()- render(<AppTypeSelector value={[AppModeEnum.CHAT]} onChange={onChange} />)+ render(<AppTypeSelector value={['chat'] as const} onChange={onChange} />)fireEvent.click(screen.getByRole('button', { name: 'common.operation.clear' }))@@ -111,11 +109,11 @@ describe('AppTypeLabel', () => {// Covers label mapping for each supported app type.it.each([- [AppModeEnum.CHAT, 'app.typeSelector.chatbot'],- [AppModeEnum.AGENT_CHAT, 'app.typeSelector.agent'],- [AppModeEnum.COMPLETION, 'app.typeSelector.completion'],- [AppModeEnum.ADVANCED_CHAT, 'app.typeSelector.advanced'],- [AppModeEnum.WORKFLOW, 'app.typeSelector.workflow'],+ ['chat', 'app.typeSelector.chatbot'],+ ['agent-chat', 'app.typeSelector.agent'],+ ['completion', 'app.typeSelector.completion'],+ ['advanced-chat', 'app.typeSelector.advanced'],+ ['workflow', 'app.typeSelector.workflow'],] as const)('should render label %s for type %s', (_type, expectedLabel) => {render(<AppTypeLabel type={_type} />)expect(screen.getByText(expectedLabel)).toBeInTheDocument()@@ -123,7 +121,7 @@ describe('AppTypeLabel', () => {// Covers fallback behavior for unexpected app mode values.it('should render empty label for unknown type', () => {- const { container } = render(<AppTypeLabel type={'unknown' as AppModeEnum} />)+ const { container } = render(<AppTypeLabel type={'unknown' as AppMode} />)expect(container.textContent).toBe('')})})diff --git a/web/app/components/app/type-selector/index.tsx b/web/app/components/app/type-selector/index.tsxindex 443b0d3db67..e097b141086 100644--- a/web/app/components/app/type-selector/index.tsx+++ b/web/app/components/app/type-selector/index.tsx@@ -1,3 +1,4 @@+import type { AppType } from '@/app/components/apps/app-type'import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import {@@ -8,20 +9,14 @@ import {} from '@remixicon/react'import * as React from 'react'import { useTranslation } from 'react-i18next'-import { AppModeEnum } from '@/types/app'+import { APP_TYPES } from '@/app/components/apps/app-type'type AppSelectorProps = {- value: Array<AppModeEnum>+ value: Array<AppType>onChange: (value: AppSelectorProps['value']) => void}-const allTypes: AppModeEnum[] = [- AppModeEnum.WORKFLOW,- AppModeEnum.ADVANCED_CHAT,- AppModeEnum.CHAT,- AppModeEnum.AGENT_CHAT,- AppModeEnum.COMPLETION,-]+const allTypes = APP_TYPESconst AppTypeSelector = ({ value, onChange }: AppSelectorProps) => {const { t } = useTranslation(['app', 'common'])@@ -92,7 +87,7 @@ export const AppTypeIcon = React.memo(wrapperClassName,)const iconClassNames = cn('size-3.5 text-components-avatar-shape-fill-stop-100', className)- if (type === AppModeEnum.CHAT) {+ if (type === 'chat') {return (<div style={style} className={cn(wrapperClassNames, 'bg-components-icon-bg-blue-solid')}><span@@ -105,7 +100,7 @@ export const AppTypeIcon = React.memo(</div>)}- if (type === AppModeEnum.AGENT_CHAT || type === AppModeEnum.AGENT) {+ if (type === 'agent-chat' || type === 'agent') {return (<div style={style} className={cn(wrapperClassNames, 'bg-components-icon-bg-violet-solid')}><span@@ -115,7 +110,7 @@ export const AppTypeIcon = React.memo(</div>)}- if (type === AppModeEnum.ADVANCED_CHAT) {+ if (type === 'advanced-chat') {return (<divstyle={style}@@ -131,14 +126,14 @@ export const AppTypeIcon = React.memo(</div>)}- if (type === AppModeEnum.WORKFLOW) {+ if (type === 'workflow') {return (<div style={style} className={cn(wrapperClassNames, 'bg-components-icon-bg-indigo-solid')}><RiExchange2Fill className={iconClassNames} /></div>)}- if (type === AppModeEnum.COMPLETION) {+ if (type === 'completion') {return (<div style={style} className={cn(wrapperClassNames, 'bg-components-icon-bg-teal-solid')}><span@@ -197,7 +192,7 @@ function AppTypeSelectTrigger({ values }: { readonly values: AppSelectorProps['vtype AppTypeSelectorItemProps = {checked: boolean- type: AppModeEnum+ type: AppTypeonClick: () => void}function AppTypeSelectorItem({ checked, type, onClick }: AppTypeSelectorItemProps) {@@ -230,12 +225,12 @@ function AppTypeSelectorItem({ checked, type, onClick }: AppTypeSelectorItemProp}function getAppTypeLabel(type: string, t: ReturnType<typeof useTranslation>['t']) {- if (type === AppModeEnum.CHAT) return t(($) => $['typeSelector.chatbot'], { ns: 'app' })- if (type === AppModeEnum.AGENT_CHAT || type === AppModeEnum.AGENT)+ if (type === 'chat') return t(($) => $['typeSelector.chatbot'], { ns: 'app' })+ if (type === 'agent-chat' || type === 'agent')return t(($) => $['typeSelector.agent'], { ns: 'app' })- if (type === AppModeEnum.COMPLETION) return t(($) => $['typeSelector.completion'], { ns: 'app' })- if (type === AppModeEnum.ADVANCED_CHAT) return t(($) => $['typeSelector.advanced'], { ns: 'app' })- if (type === AppModeEnum.WORKFLOW) return t(($) => $['typeSelector.workflow'], { ns: 'app' })+ if (type === 'completion') return t(($) => $['typeSelector.completion'], { ns: 'app' })+ if (type === 'advanced-chat') return t(($) => $['typeSelector.advanced'], { ns: 'app' })+ if (type === 'workflow') return t(($) => $['typeSelector.workflow'], { ns: 'app' })return ''}diff --git a/web/app/components/app/workflow-log/__tests__/index.spec.tsx b/web/app/components/app/workflow-log/__tests__/index.spec.tsxindex fdebf47c65b..6be089cf741 100644--- a/web/app/components/app/workflow-log/__tests__/index.spec.tsx+++ b/web/app/components/app/workflow-log/__tests__/index.spec.tsx@@ -1,4 +1,4 @@-import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'+import type { AppDetailWithSite, AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { UseQueryResult } from '@tanstack/react-query'/*** Logs Container Component Tests@@ -19,7 +19,6 @@ import type { MockedFunction } from 'vite-plus/test'import type { CloudSandboxPlanState } from '../../log/cloud-sandbox-retention'import type { ILogsProps } from '../index'import type { WorkflowAppLogDetail, WorkflowLogsResponse, WorkflowRunDetail } from '@/models/log'-import type { AppModeEnum } from '@/types/app'import { screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import dayjs from 'dayjs'@@ -612,7 +611,7 @@ describe('Logs Container', () => {}),)- const chatApp = createMockApp({ mode: 'advanced-chat' as AppModeEnum })+ const chatApp = createMockApp({ mode: 'advanced-chat' as AppMode })// ActrenderWithQueryClient(<Logs appDetail={chatApp} />)diff --git a/web/app/components/app/workflow-log/__tests__/list.spec.tsx b/web/app/components/app/workflow-log/__tests__/list.spec.tsxindex 3a672ae8e9e..5f872d76da4 100644--- a/web/app/components/app/workflow-log/__tests__/list.spec.tsx+++ b/web/app/components/app/workflow-log/__tests__/list.spec.tsx@@ -1,4 +1,4 @@-import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'+import type { AppDetailWithSite, AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { WorkflowAppLogDetail, WorkflowLogsResponse, WorkflowRunDetail } from '@/models/log'/*** WorkflowAppLogList Component Tests@@ -10,7 +10,6 @@ import type { WorkflowAppLogDetail, WorkflowLogsResponse, WorkflowRunDetail } fr* - Drawer with run details* - Loading states*/-import type { AppModeEnum } from '@/types/app'import { render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { APP_PAGE_LIMIT } from '@/config'@@ -203,7 +202,7 @@ describe('WorkflowAppLogList', () => {it('should render trigger column for workflow apps', () => {const logs = createMockLogsResponse([createMockWorkflowLog()])- const workflowApp = createMockApp({ mode: 'workflow' as AppModeEnum })+ const workflowApp = createMockApp({ mode: 'workflow' as AppMode })render(<WorkflowAppLogList logs={logs} appDetail={workflowApp} onRefresh={defaultOnRefresh} />,@@ -214,7 +213,7 @@ describe('WorkflowAppLogList', () => {it('should not render trigger column for non-workflow apps', () => {const logs = createMockLogsResponse([createMockWorkflowLog()])- const chatApp = createMockApp({ mode: 'advanced-chat' as AppModeEnum })+ const chatApp = createMockApp({ mode: 'advanced-chat' as AppMode })render(<WorkflowAppLogList logs={logs} appDetail={chatApp} onRefresh={defaultOnRefresh} />)@@ -855,7 +854,7 @@ describe('WorkflowAppLogList', () => {}),}),])- const chatApp = createMockApp({ mode: 'advanced-chat' as AppModeEnum })+ const chatApp = createMockApp({ mode: 'advanced-chat' as AppMode })render(<WorkflowAppLogList logs={logs} appDetail={chatApp} onRefresh={defaultOnRefresh} />)diff --git a/web/app/components/app/workflow-log/list.tsx b/web/app/components/app/workflow-log/list.tsxindex cb190f8b711..8ca5eb29d15 100644--- a/web/app/components/app/workflow-log/list.tsx+++ b/web/app/components/app/workflow-log/list.tsx@@ -25,7 +25,6 @@ import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import useTimestamp from '@/hooks/use-timestamp'-import { AppModeEnum } from '@/types/app'import DetailPanel from './detail'import TriggerByDisplay from './trigger-by-display'@@ -67,7 +66,7 @@ const WorkflowAppLogList: FC<ILogs> = ({ logs, appDetail, onRefresh }) => {setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}- const isWorkflow = appDetail?.mode === AppModeEnum.WORKFLOW+ const isWorkflow = appDetail?.mode === 'workflow'const statusTdRender = (status: string) => {if (status === 'succeeded') {diff --git a/web/app/components/apps/__tests__/app-card.spec.tsx b/web/app/components/apps/__tests__/app-card.spec.tsxindex 40e9a3360d9..408810505cc 100644--- a/web/app/components/apps/__tests__/app-card.spec.tsx+++ b/web/app/components/apps/__tests__/app-card.spec.tsx@@ -6,7 +6,6 @@ import * as React from 'react'import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'import { AccessMode } from '@/models/access-control'import { renderWithConsoleQuery } from '@/test/console/query-data'-import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import { AppCard } from '../app-card'import { StarredAppCard } from '../starred-app-card'@@ -414,7 +413,7 @@ const createMockApp = (overrides: Partial<AppPartial> = {}): AppPartial => ({id: 'test-app-id',name: 'Test App',description: 'Test app description',- mode: AppModeEnum.CHAT,+ mode: 'chat',icon: '🤖',icon_type: 'emoji' as const,icon_background: '#FFEAD5',@@ -608,7 +607,7 @@ describe('AppCard', () => {describe('Props', () => {it('should handle different app modes', () => {- const workflowApp = { ...mockApp, mode: AppModeEnum.WORKFLOW }+ const workflowApp = { ...mockApp, mode: 'workflow' as const }render(<AppCard app={workflowApp} />)expect(screen.getByRole('link', { name: 'Test App' })).toBeInTheDocument()})@@ -874,7 +873,7 @@ describe('AppCard', () => {})it('should show switch option for chat mode apps', async () => {- const chatApp = { ...mockApp, mode: AppModeEnum.CHAT }+ const chatApp = { ...mockApp, mode: 'chat' as const }render(<AppCard app={chatApp} />)fireEvent.click(getOperationsTrigger())@@ -889,7 +888,7 @@ describe('AppCard', () => {const editableChatApp = createMockApp({created_by: 'another-user',maintainer: 'another-user',- mode: AppModeEnum.CHAT,+ mode: 'chat',permission_keys: [AppACLPermission.Edit],})render(<AppCard app={editableChatApp} />)@@ -903,7 +902,7 @@ describe('AppCard', () => {})it('should show switch option for completion mode apps', async () => {- const completionApp = { ...mockApp, mode: AppModeEnum.COMPLETION }+ const completionApp = { ...mockApp, mode: 'completion' as const }render(<AppCard app={completionApp} />)fireEvent.click(getOperationsTrigger())@@ -914,7 +913,7 @@ describe('AppCard', () => {})it('should not show switch option for workflow mode apps', async () => {- const workflowApp = { ...mockApp, mode: AppModeEnum.WORKFLOW }+ const workflowApp = { ...mockApp, mode: 'workflow' as const }render(<AppCard app={workflowApp} />)fireEvent.click(getOperationsTrigger())@@ -1236,7 +1235,7 @@ describe('AppCard', () => {describe('Switch Modal', () => {it('should open switch modal when switch button is clicked', async () => {- const chatApp = { ...mockApp, mode: AppModeEnum.CHAT }+ const chatApp = { ...mockApp, mode: 'chat' as const }render(<AppCard app={chatApp} />)fireEvent.click(getOperationsTrigger())@@ -1250,7 +1249,7 @@ describe('AppCard', () => {})it('should close switch modal when close button is clicked', async () => {- const chatApp = { ...mockApp, mode: AppModeEnum.CHAT }+ const chatApp = { ...mockApp, mode: 'chat' as const }render(<AppCard app={chatApp} />)fireEvent.click(getOperationsTrigger())@@ -1270,7 +1269,7 @@ describe('AppCard', () => {})it('should open switch modal for completion mode apps', async () => {- const completionApp = { ...mockApp, mode: AppModeEnum.COMPLETION }+ const completionApp = { ...mockApp, mode: 'completion' as const }render(<AppCard app={completionApp} />)fireEvent.click(getOperationsTrigger())@@ -1313,7 +1312,7 @@ describe('AppCard', () => {describe('Workflow Export with Environment Variables', () => {it('should use the workflow export command for workflow apps', async () => {- const workflowApp = { ...mockApp, mode: AppModeEnum.WORKFLOW }+ const workflowApp = { ...mockApp, mode: 'workflow' as const }render(<AppCard app={workflowApp} />)fireEvent.click(getOperationsTrigger())@@ -1336,7 +1335,7 @@ describe('AppCard', () => {secretEnvList: [{ value_type: 'secret', name: 'API_KEY', value: 'secret' }],})- const workflowApp = { ...mockApp, mode: AppModeEnum.WORKFLOW }+ const workflowApp = { ...mockApp, mode: 'workflow' as const }render(<AppCard app={workflowApp} />)fireEvent.click(getOperationsTrigger())@@ -1350,7 +1349,7 @@ describe('AppCard', () => {})it('should not open a modal when the workflow command downloads directly', async () => {- const workflowApp = { ...mockApp, mode: AppModeEnum.WORKFLOW }+ const workflowApp = { ...mockApp, mode: 'workflow' as const }render(<AppCard app={workflowApp} />)fireEvent.click(getOperationsTrigger())@@ -1369,7 +1368,7 @@ describe('AppCard', () => {})it('should use the workflow export command for advanced chat apps', async () => {- const advancedChatApp = { ...mockApp, mode: AppModeEnum.ADVANCED_CHAT }+ const advancedChatApp = { ...mockApp, mode: 'advanced-chat' as const }render(<AppCard app={advancedChatApp} />)fireEvent.click(getOperationsTrigger())@@ -1391,7 +1390,7 @@ describe('AppCard', () => {secretEnvList: [{ value_type: 'secret', name: 'API_KEY', value: 'secret' }],})- const workflowApp = { ...mockApp, mode: AppModeEnum.WORKFLOW }+ const workflowApp = { ...mockApp, mode: 'workflow' as const }render(<AppCard app={workflowApp} />)fireEvent.click(getOperationsTrigger())@@ -1543,7 +1542,7 @@ describe('AppCard', () => {describe('Open in Explore - No App Found', () => {it('should tell workflow users to publish before opening in explore', async () => {const workflowApp = createMockApp({- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,workflow: undefined,})render(<AppCard app={workflowApp} />)@@ -1698,7 +1697,7 @@ describe('AppCard', () => {mockUserCanAccessApp.result = falsemockUserCanAccessApp.isLoading = trueconst workflowApp = createMockApp({- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,workflow: undefined,})diff --git a/web/app/components/apps/__tests__/list.spec.tsx b/web/app/components/apps/__tests__/list.spec.tsxindex 1b81fd0f6fb..aeaeec51f07 100644--- a/web/app/components/apps/__tests__/list.spec.tsx+++ b/web/app/components/apps/__tests__/list.spec.tsx@@ -14,7 +14,6 @@ import {import { createConsoleQueryWrapper } from '@/test/console/query-data'import { seedRegisteredConsoleStateFixture } from '@/test/console/state-fixture'import { renderWithNuqs } from '@/test/nuqs-testing'-import { AppModeEnum } from '@/types/app'import { List } from '../list'vi.mock('react-i18next', async () => {@@ -185,7 +184,7 @@ const defaultAppData = {id: 'app-1',name: 'Test App 1',description: 'Description 1',- mode: AppModeEnum.CHAT,+ mode: 'chat',icon: '🤖',icon_type: 'emoji',icon_background: '#FFEAD5',@@ -198,7 +197,7 @@ const defaultAppData = {id: 'app-2',name: 'Test App 2',description: 'Description 2',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,icon: '⚙️',icon_type: 'emoji',icon_background: '#E4FBCC',@@ -657,7 +656,7 @@ describe('List', () => {id: 'starred-app-1',name: 'Starred App',description: 'Starred description',- mode: AppModeEnum.CHAT,+ mode: 'chat',icon: '⭐',icon_type: 'emoji',icon_background: '#FFEAD5',@@ -712,7 +711,7 @@ describe('List', () => {id: 'starred-app-1',name: 'Starred App',description: 'Starred description',- mode: AppModeEnum.CHAT,+ mode: 'chat',icon: '⭐',icon_type: 'emoji',icon_background: '#FFEAD5',@@ -766,7 +765,7 @@ describe('List', () => {id: 'starred-app-1',name: 'Starred App',description: 'Starred description',- mode: AppModeEnum.CHAT,+ mode: 'chat',icon: '⭐',icon_type: 'emoji',icon_background: '#FFEAD5',@@ -1054,9 +1053,7 @@ describe('List', () => {await user.click(await screen.findByRole('option', { name: 'app.types.workflow' }))await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled())- expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get('category')).toBe(- AppModeEnum.WORKFLOW,- )+ expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get('category')).toBe('workflow')})it('should update category when all option is selected', async () => {@@ -1123,7 +1120,7 @@ describe('List', () => {sort_by: 'last_modified',tag_ids: ['tag-1'],creator_ids: ['creator-1'],- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,},})expect(options.getNextPageParam({ has_more: true, page: 2 })).toBe(3)@@ -1149,7 +1146,7 @@ describe('List', () => {sort_by: 'last_modified',tag_ids: ['tag-1'],creator_ids: ['creator-1'],- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,},})})@@ -1233,11 +1230,11 @@ describe('List', () => {describe('App Type Select Options', () => {it('should update category for each app type option click', async () => {const appTypeTexts = [- { mode: AppModeEnum.WORKFLOW, text: 'app.types.workflow' },- { mode: AppModeEnum.ADVANCED_CHAT, text: 'app.types.advanced' },- { mode: AppModeEnum.CHAT, text: 'app.types.chatbot' },- { mode: AppModeEnum.AGENT_CHAT, text: 'app.types.agent' },- { mode: AppModeEnum.COMPLETION, text: 'app.newApp.completeApp' },+ { mode: 'workflow' as const, text: 'app.types.workflow' },+ { mode: 'advanced-chat' as const, text: 'app.types.advanced' },+ { mode: 'chat' as const, text: 'app.types.chatbot' },+ { mode: 'agent-chat' as const, text: 'app.types.agent' },+ { mode: 'completion' as const, text: 'app.newApp.completeApp' },]for (const { mode, text } of appTypeTexts) {diff --git a/web/app/components/apps/app-card/index.tsx b/web/app/components/apps/app-card/index.tsxindex 9ab466664b3..56e1248efbc 100644--- a/web/app/components/apps/app-card/index.tsx+++ b/web/app/components/apps/app-card/index.tsx@@ -16,7 +16,6 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { AppCardTags } from '@/features/tag-management/components/app-card-tags'import Link from '@/next/link'-import { AppModeEnum } from '@/types/app'import { getRedirectionPath } from '@/utils/app-redirection'import {getAppACLCapabilities,@@ -86,15 +85,15 @@ export const AppCard = memo(const appModeLabel = useMemo(() => {switch (app.mode) {- case AppModeEnum.CHAT:+ case 'chat':return t(($) => $['types.chatbot'], { ns: 'app' })- case AppModeEnum.ADVANCED_CHAT:+ case 'advanced-chat':return t(($) => $['types.advanced'], { ns: 'app' })- case AppModeEnum.AGENT_CHAT:+ case 'agent-chat':return t(($) => $['types.agent'], { ns: 'app' })- case AppModeEnum.COMPLETION:+ case 'completion':return t(($) => $['types.completion'], { ns: 'app' })- case AppModeEnum.WORKFLOW:+ case 'workflow':return t(($) => $['types.workflow'], { ns: 'app' })default:return app.modediff --git a/web/app/components/apps/app-card/interactions.tsx b/web/app/components/apps/app-card/interactions.tsxindex a95970dc74d..d8169c1a266 100644--- a/web/app/components/apps/app-card/interactions.tsx+++ b/web/app/components/apps/app-card/interactions.tsx@@ -58,7 +58,6 @@ import { AccessMode } from '@/models/access-control'import { useRouter } from '@/next/navigation'import { useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'import { consoleClient, consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'import { getAppACLCapabilities, hasPermission } from '@/utils/permission'import { basePath } from '@/utils/var'@@ -78,9 +77,9 @@ const AppExportConfirmModal = dynamic(() => import('@/app/components/app/export-const OPERATIONS_MENU_POPUP_CLASS_NAME = 'min-w-[216px]'const APP_MODES_REQUIRING_PUBLISHED_WORKFLOW_IN_EXPLORE = new Set<AppPartial['mode']>([- AppModeEnum.ADVANCED_CHAT,- AppModeEnum.WORKFLOW,-])+ 'advanced-chat',+ 'workflow',+] as const)function requiresPublishedWorkflowInExplore(app: AppPartial) {return APP_MODES_REQUIRING_PUBLISHED_WORKFLOW_IN_EXPLORE.has(app.mode)@@ -477,8 +476,7 @@ export function AppCardInteractions({if (isExporting) returnsetIsOperationsMenuOpen(false)- const isWorkflowApp =- app.mode === AppModeEnum.WORKFLOW || app.mode === AppModeEnum.ADVANCED_CHAT+ const isWorkflowApp = app.mode === 'workflow' || app.mode === 'advanced-chat'const result = isWorkflowApp? await exportWorkflowAppDsl({ appId: app.id, appName: app.name }): await exportAppDsl({ appId: app.id, appName: app.name })@@ -515,8 +513,7 @@ export function AppCardInteractions({const shouldShowDuplicateOption = canCreateAppconst shouldShowExportOption = appACLCapabilities.canImportExportDSLconst shouldShowSwitchOption =- appACLCapabilities.canEdit &&- (app.mode === AppModeEnum.COMPLETION || app.mode === AppModeEnum.CHAT)+ appACLCapabilities.canEdit && (app.mode === 'completion' || app.mode === 'chat')const shouldShowAccessConfigOption = appACLCapabilities.canAccessConfigconst shouldShowDeleteOption = appACLCapabilities.canDeleteconst shouldShowOperationsMenu =diff --git a/web/app/components/apps/app-list-catalog.tsx b/web/app/components/apps/app-list-catalog.tsxindex e34a7a8d8e1..f9091753dc5 100644--- a/web/app/components/apps/app-list-catalog.tsx+++ b/web/app/components/apps/app-list-catalog.tsx@@ -17,7 +17,6 @@ import { InfiniteScrollSentinel } from '@/app/components/base/infinite-scroll-seimport { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { AppCard } from './app-card'import { AppCardSkeleton } from './app-card-skeleton'import { APP_LIST_GRID_CLASS_NAME } from './constants'@@ -104,8 +103,7 @@ function AppListCatalogContent({const workflowOnlineUserAppIds = useMemo(() => {const appIds = new Set<string>()apps.forEach((app) => {- if (app.mode === AppModeEnum.WORKFLOW || app.mode === AppModeEnum.ADVANCED_CHAT)- appIds.add(app.id)+ if (app.mode === 'workflow' || app.mode === 'advanced-chat') appIds.add(app.id)})return Array.from(appIds)}, [apps])diff --git a/web/app/components/apps/app-type.ts b/web/app/components/apps/app-type.tsnew file mode 100644index 00000000000..e3c36726636--- /dev/null+++ b/web/app/components/apps/app-type.ts@@ -0,0 +1,16 @@+import type { CreateAppPayload } from '@dify/contracts/api/console/apps/types.gen'++export type AppType = CreateAppPayload['mode']+export type WorkflowAppMode = Extract<AppType, 'workflow' | 'advanced-chat'>++export const APP_TYPES = [+ 'workflow',+ 'advanced-chat',+ 'chat',+ 'agent-chat',+ 'completion',+] as const satisfies readonly AppType[]++export function isWorkflowAppMode(mode: string): mode is WorkflowAppMode {+ return mode === 'workflow' || mode === 'advanced-chat'+}diff --git a/web/app/components/apps/query-params.ts b/web/app/components/apps/query-params.tsindex ab38f4c5fe3..afadfedb428 100644--- a/web/app/components/apps/query-params.ts+++ b/web/app/components/apps/query-params.ts@@ -2,17 +2,14 @@ import type { GetAppsData } from '@dify/contracts/api/console/apps/types.gen'import type { inferParserType } from 'nuqs'import { zGetAppsQuery } from '@dify/contracts/api/console/apps/zod.gen'import { createParser, debounce, parseAsString, parseAsStringLiteral } from 'nuqs'+import { APP_TYPES } from './app-type'import { APP_LIST_SEARCH_DEBOUNCE_MS } from './constants'type AppListMode = NonNullable<NonNullable<GetAppsData['query']>['mode']>export const studioAppListCategories = ['all',- 'workflow',- 'advanced-chat',- 'chat',- 'agent-chat',- 'completion',+ ...APP_TYPES,] as const satisfies readonly AppListMode[]const studioAppListCategorySchema = zGetAppsQuery.shape.modediff --git a/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx b/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsxindex bec6a0864a9..1d5d5101bed 100644--- a/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx+++ b/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx@@ -11,7 +11,7 @@ import { createFeaturesStore } from '@/app/components/base/features/store'import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { createAppModelConfigFixture } from '@/test/fixtures/app'import { withSelectorKey } from '@/test/i18n-mock'-import { AppModeEnum, ModelModeType } from '@/types/app'+import { ModelModeType } from '@/types/app'import ModerationSettingModal from '../moderation-setting-modal'const mockNotify = vi.fn()@@ -1081,7 +1081,7 @@ describe('ModerationSettingModal', () => {backendModelConfig,collectionList: [],datasetConfigs: buildConfigurationDatasetConfigs({ backendModelConfig, nextDataSets: [] }),- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,nextDataSets: [],})const publish = createPublishHandler({@@ -1096,7 +1096,7 @@ describe('ModerationSettingModal', () => {hasSetBlockStatus: { history: true, query: true },isAdvancedMode: false,isFunctionCall: false,- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,modelConfig: config.modelConfig,promptEmpty: false,promptMode: 'simple',diff --git a/web/app/components/base/linked-apps-panel/__tests__/index.spec.tsx b/web/app/components/base/linked-apps-panel/__tests__/index.spec.tsxindex ea92cc5ea66..518a468a010 100644--- a/web/app/components/base/linked-apps-panel/__tests__/index.spec.tsx+++ b/web/app/components/base/linked-apps-panel/__tests__/index.spec.tsx@@ -1,7 +1,6 @@import { render, screen } from '@testing-library/react'import * as React from 'react'import { vi } from 'vite-plus/test'-import { AppModeEnum } from '@/types/app'import LinkedAppsPanel from '../index'vi.mock('@/next/link', () => ({@@ -25,7 +24,7 @@ describe('LinkedAppsPanel Component', () => {{id: 'app-1',name: 'Chatbot App',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,icon_type: 'emoji' as const,icon: '🤖',icon_background: '#FFEAD5',@@ -34,7 +33,7 @@ describe('LinkedAppsPanel Component', () => {{id: 'app-2',name: 'Workflow App',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,icon_type: 'image' as const,icon: 'file-id',icon_background: '#E4FBCC',@@ -43,7 +42,7 @@ describe('LinkedAppsPanel Component', () => {{id: 'app-3',name: '',- mode: AppModeEnum.AGENT_CHAT,+ mode: 'agent-chat' as const,icon_type: 'emoji' as const,icon: '🕵️',icon_background: '#D3F8DF',diff --git a/web/app/components/base/linked-apps-panel/index.stories.tsx b/web/app/components/base/linked-apps-panel/index.stories.tsxindex 0b76b63ac2d..4b2517ec227 100644--- a/web/app/components/base/linked-apps-panel/index.stories.tsx+++ b/web/app/components/base/linked-apps-panel/index.stories.tsx@@ -1,13 +1,12 @@import type { Meta, StoryObj } from '@storybook/nextjs-vite'import type { RelatedApp } from '@/models/datasets'-import { AppModeEnum } from '@/types/app'import LinkedAppsPanel from '.'const mockRelatedApps: RelatedApp[] = [{id: 'app-cx',name: 'Customer Support Assistant',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,icon_type: 'emoji',icon: '\u{1F4AC}',icon_background: '#EEF2FF',@@ -16,7 +15,7 @@ const mockRelatedApps: RelatedApp[] = [{id: 'app-ops',name: 'Ops Workflow Orchestrator',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,icon_type: 'emoji',icon: '\u{1F6E0}\u{FE0F}',icon_background: '#ECFDF3',@@ -25,7 +24,7 @@ const mockRelatedApps: RelatedApp[] = [{id: 'app-research',name: 'Research Synthesizer',- mode: AppModeEnum.ADVANCED_CHAT,+ mode: 'advanced-chat' as const,icon_type: 'emoji',icon: '\u{1F9E0}',icon_background: '#FDF2FA',diff --git a/web/app/components/base/linked-apps-panel/index.tsx b/web/app/components/base/linked-apps-panel/index.tsxindex 37751d9b8ca..1899186c6f3 100644--- a/web/app/components/base/linked-apps-panel/index.tsx+++ b/web/app/components/base/linked-apps-panel/index.tsx@@ -1,4 +1,5 @@'use client'+import type { FC } from 'react'import type { RelatedApp } from '@/models/datasets'import { cn } from '@langgenius/dify-ui/cn'@@ -6,7 +7,6 @@ import { RiArrowRightUpLine } from '@remixicon/react'import * as React from 'react'import AppIcon from '@/app/components/base/app-icon'import Link from '@/next/link'-import { AppModeEnum } from '@/types/app'type ILikedItemProps = Readonly<{appStatus?: boolean@@ -14,12 +14,12 @@ type ILikedItemProps = Readonly<{isMobile: boolean}>-const appTypeMap = {- [AppModeEnum.CHAT]: 'Chatbot',- [AppModeEnum.COMPLETION]: 'Completion',- [AppModeEnum.AGENT_CHAT]: 'Agent',- [AppModeEnum.ADVANCED_CHAT]: 'Chatflow',- [AppModeEnum.WORKFLOW]: 'Workflow',+const appTypeMap: Partial<Record<RelatedApp['mode'], string>> = {+ chat: 'Chatbot',+ completion: 'Completion',+ 'agent-chat': 'Agent',+ 'advanced-chat': 'Chatflow',+ workflow: 'Workflow',}const LikedItem = ({ detail, isMobile }: ILikedItemProps) => {diff --git a/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx b/web/app/components/explore/create-app-modal/__tests__/index.spec.tsxindex 3d237a7df22..a6e521f0197 100644--- a/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx+++ b/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx@@ -6,7 +6,6 @@ import userEvent from '@testing-library/user-event'import * as React from 'react'import { renderWithConsoleQuery } from '@/test/console/query-data'import { mockEmojiData } from '@/test/emoji-picker'-import { AppModeEnum } from '@/types/app'import CreateAppModal from '../index'let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'COMMUNITY'@@ -29,7 +28,7 @@ const setup = async (overrides: Partial<CreateAppModalProps> = {}) => {appIcon: '🤖',appIconBackground: '#FFEAD5',appIconUrl: null,- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,appUseIconAsAnswerIcon: false,max_active_requests: null,onConfirm,@@ -124,7 +123,7 @@ describe('CreateAppModal', () => {})it('should render edit-only fields when editing a chat app', async () => {- await setup({ isEditModal: true, appMode: AppModeEnum.CHAT, max_active_requests: 5 })+ await setup({ isEditModal: true, appMode: 'chat' as const, max_active_requests: 5 })expect(screen.getByText('app.editAppTitle'))!.toBeInTheDocument()expect(screen.getByRole('button', { name: /common\.operation\.save/ }))!.toBeInTheDocument()@@ -132,7 +131,7 @@ describe('CreateAppModal', () => {expect((screen.getByRole('spinbutton') as HTMLInputElement).value).toBe('5')})- it.each([AppModeEnum.ADVANCED_CHAT, AppModeEnum.AGENT_CHAT])(+ it.each(['advanced-chat', 'agent-chat'] as const)('should render answer icon switch when editing %s app',async (mode) => {await setup({ isEditModal: true, appMode: mode })@@ -142,7 +141,7 @@ describe('CreateAppModal', () => {)it('should not render answer icon switch when editing a non-chat app', async () => {- await setup({ isEditModal: true, appMode: AppModeEnum.COMPLETION })+ await setup({ isEditModal: true, appMode: 'completion' as const })expect(screen.queryByRole('switch')).not.toBeInTheDocument()})@@ -587,7 +586,7 @@ describe('CreateAppModal', () => {it('should include max_active_requests and updated answer icon when saving', async () => {const { onConfirm } = await setup({isEditModal: true,- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,appUseIconAsAnswerIcon: false,max_active_requests: 3,})diff --git a/web/app/components/explore/create-app-modal/index.tsx b/web/app/components/explore/create-app-modal/index.tsxindex 47515936794..e1547e62bae 100644--- a/web/app/components/explore/create-app-modal/index.tsx+++ b/web/app/components/explore/create-app-modal/index.tsx@@ -1,4 +1,5 @@'use client'+import type {AppDetailWithSite,UpdateAppPayload,@@ -29,7 +30,6 @@ import AppsFull from '@/app/components/billing/apps-full-in-dialog'import { toast } from '@/app/notifications'import { deploymentEditionAtom } from '@/features/system-features/state'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'export type CreateAppModalProps = {show: boolean@@ -269,9 +269,7 @@ const CreateAppModal = ({</div>{/* answer icon */}{isEditModal &&- (appMode === AppModeEnum.CHAT ||- appMode === AppModeEnum.ADVANCED_CHAT ||- appMode === AppModeEnum.AGENT_CHAT) && (+ (appMode === 'chat' || appMode === 'advanced-chat' || appMode === 'agent-chat') && (<div className="pt-2"><div className="flex items-center justify-between"><div className="py-2 text-sm leading-5 font-medium text-text-primary">diff --git a/web/app/components/explore/installed-app/__tests__/index.spec.tsx b/web/app/components/explore/installed-app/__tests__/index.spec.tsxindex 0e8a46e27f9..f65bab1f716 100644--- a/web/app/components/explore/installed-app/__tests__/index.spec.tsx+++ b/web/app/components/explore/installed-app/__tests__/index.spec.tsx@@ -170,7 +170,7 @@ describe('InstalledApp', () => {})})- it.each<AppMode>(['chat', 'advanced-chat', 'agent-chat'])(+ it.each<AppMode>(['chat', 'advanced-chat', 'agent-chat'] as const)('renders chat for the supported %s mode',async (mode) => {mocks.getInstalledApp.mockResolvedValue(createInstalledApp(mode))diff --git a/web/app/components/explore/learn-dify/__tests__/item.spec.tsx b/web/app/components/explore/learn-dify/__tests__/item.spec.tsxindex f785d5cdcdf..c8f76444baa 100644--- a/web/app/components/explore/learn-dify/__tests__/item.spec.tsx+++ b/web/app/components/explore/learn-dify/__tests__/item.spec.tsx@@ -5,7 +5,6 @@ import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { trackEvent } from '@/app/components/base/amplitude'import { renderWithConsoleQuery } from '@/test/console/query-data'-import { AppModeEnum } from '@/types/app'import LearnDifyItem from '../item'let deploymentEdition: DeploymentEdition = 'CLOUD'@@ -19,7 +18,7 @@ vi.mock('@/app/components/base/amplitude', () => ({const createApp = (overrides: Partial<RecommendedAppResponse> = {}): RecommendedAppResponse => ({app: {id: 'app-basic-id',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,icon_type: 'emoji',icon: '😀',icon_background: '#fff',diff --git a/web/app/components/explore/try-app/app/__tests__/index.spec.tsx b/web/app/components/explore/try-app/app/__tests__/index.spec.tsxindex ce6d29331a6..d0e14e44b44 100644--- a/web/app/components/explore/try-app/app/__tests__/index.spec.tsx+++ b/web/app/components/explore/try-app/app/__tests__/index.spec.tsx@@ -20,7 +20,7 @@ const createApp = (mode: string): TrialAppDetailResponse =>}) as TrialAppDetailResponsedescribe('TryApp', () => {- it.each(['chat', 'advanced-chat', 'agent-chat'])(+ it.each(['chat', 'advanced-chat', 'agent-chat'] as const)('uses the chat experience for %s apps',(mode) => {render(<TryApp appId="app-id" appDetail={createApp(mode)} />)@@ -32,7 +32,7 @@ describe('TryApp', () => {it.each([['completion', 'Completion preview'],['workflow', 'Workflow preview'],- ])('uses the text generation experience for %s apps', (mode, name) => {+ ] as const)('uses the text generation experience for %s apps', (mode, name) => {render(<TryApp appId="app-id" appDetail={createApp(mode)} />)expect(screen.getByRole('region', { name })).toBeInTheDocument()diff --git a/web/app/components/explore/try-app/preview/__tests__/index.spec.tsx b/web/app/components/explore/try-app/preview/__tests__/index.spec.tsxindex bcb0ddfbf5f..9059f569efd 100644--- a/web/app/components/explore/try-app/preview/__tests__/index.spec.tsx+++ b/web/app/components/explore/try-app/preview/__tests__/index.spec.tsx@@ -19,7 +19,7 @@ describe('Preview', () => {expect(screen.getByRole('region', { name: 'Basic app preview' })).toBeInTheDocument()})- it.each(['workflow', 'advanced-chat'])('uses the flow preview for %s apps', (mode) => {+ it.each(['workflow', 'advanced-chat'] as const)('uses the flow preview for %s apps', (mode) => {render(<Preview appId="app-id" appDetail={createApp(mode)} />)expect(screen.getByRole('region', { name: 'Flow app preview' })).toBeInTheDocument()diff --git a/web/app/components/goto-anything/actions/app.tsx b/web/app/components/goto-anything/actions/app.tsxindex 37f3b80735c..3410d19bab5 100644--- a/web/app/components/goto-anything/actions/app.tsx+++ b/web/app/components/goto-anything/actions/app.tsx@@ -1,32 +1,24 @@import type { AppPartial } from '@dify/contracts/api/console/apps/types.gen'import type { ActionItem, AppSearchResult, SearchQueryOptions, SearchResult } from './types'-import type { AppModeEnum as AppMode } from '@/types/app'+import { isWorkflowAppMode } from '@/app/components/apps/app-type'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { getRedirectionPath } from '@/utils/app-redirection'import { AppTypeIcon } from '../../app/type-selector'import AppIcon from '../../base/app-icon'-const WORKFLOW_MODES = new Set([AppModeEnum.WORKFLOW, AppModeEnum.ADVANCED_CHAT])-const APP_MODES = new Set<string>(Object.values(AppModeEnum))-type AppSection = { id: string; label: string; path: string; iconClassName: string }-function getAppMode(app: AppPartial): AppMode {- return APP_MODES.has(app.mode) ? (app.mode as AppMode) : AppModeEnum.CHAT-}-function getAppPath(app: AppPartial) {return getRedirectionPath({id: app.id,- mode: getAppMode(app),+ mode: app.mode,permission_keys: app.permission_keys,})}const getAppSections = (app: AppPartial): AppSection[] => {const base = `/app/${app.id}`- if (WORKFLOW_MODES.has(getAppMode(app))) {+ if (isWorkflowAppMode(app.mode)) {return [{id: 'workflow',@@ -76,7 +68,7 @@ const appIcon = (app: AppPartial) => (<AppTypeIconwrapperClassName="absolute -bottom-0.5 -right-0.5 w-4 h-4 rounded-sm border border-divider-regular outline-solid outline-components-panel-on-panel-item-bg"className="size-3"- type={getAppMode(app)}+ type={app.mode}/></div>)diff --git a/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx b/web/app/components/integrations/__tests__/tool-provider-list.spec.tsxindex 2f1830cd2d2..7af17b95e3d 100644--- a/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx+++ b/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx@@ -357,7 +357,7 @@ describe('getToolType', () => {['workflow', ToolType.Workflow],['mcp', ToolType.MCP],['unknown', ToolType.BuiltIn],- ])('returns correct ToolType for "%s"', (input, expected) => {+ ] as const)('returns correct ToolType for "%s"', (input, expected) => {expect(getToolType(input)).toBe(expected)})})diff --git a/web/app/components/main-nav/__tests__/index.spec.tsx b/web/app/components/main-nav/__tests__/index.spec.tsxindex 1797ee011d1..3a54d1a34dc 100644--- a/web/app/components/main-nav/__tests__/index.spec.tsx+++ b/web/app/components/main-nav/__tests__/index.spec.tsx@@ -37,7 +37,6 @@ import {renderWithConsoleQuery as renderWithoutPricing,} from '@/test/console/query-data'import { seedRegisteredConsoleStateFixture } from '@/test/console/state-fixture'-import { AppModeEnum } from '@/types/app'import { MainNav } from '../index'const onPricingUrlUpdate = vi.hoisted(() => vi.fn())@@ -471,7 +470,7 @@ const createInstalledApp = (is_pinned: overrides.is_pinned ?? false,app: {id: overrides.app?.id ?? 'app-1',- mode: overrides.app?.mode ?? AppModeEnum.CHAT,+ mode: overrides.app?.mode ?? 'chat',icon_type: overrides.app?.icon_type ?? 'emoji',icon: overrides.app?.icon ?? '🤖',icon_background: overrides.app?.icon_background ?? '#fff',diff --git a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-picker.spec.tsx b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-picker.spec.tsxindex 8b79cc49196..cb8b16fc75e 100644--- a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-picker.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-picker.spec.tsx@@ -2,7 +2,6 @@ import type { AppPartial } from '@dify/contracts/api/console/apps/types.gen'import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'-import { AppModeEnum } from '@/types/app'import { AppPicker } from '../app-picker'vi.mock('@/app/components/base/app-icon', () => ({@@ -12,7 +11,7 @@ vi.mock('@/app/components/base/app-icon', () => ({const app = {id: 'app-1',name: 'Workflow App',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,icon_type: 'emoji',icon: 'W',icon_background: '#FFFFFF',diff --git a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/index.spec.tsxindex 8e239b9f955..d44cba5a1fc 100644--- a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/index.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/index.spec.tsx@@ -6,14 +6,13 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'-import { AppModeEnum } from '@/types/app'import { AppSelector } from '../index'const apps = [{id: 'app-1',name: 'Support Bot',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,icon_type: 'emoji',icon: '🤖',icon_background: '#FFEAD5',@@ -22,7 +21,7 @@ const apps = [{id: 'app-2',name: 'Workflow App',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,icon_type: 'emoji',icon: '⚙️',icon_background: '#E0EAFF',@@ -31,7 +30,7 @@ const apps = [{id: 'app-3',name: 'Sales Bot',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,icon_type: 'emoji',icon: '💼',icon_background: '#FEE4E2',diff --git a/web/app/components/plugins/plugin-detail-panel/app-selector/app-picker.tsx b/web/app/components/plugins/plugin-detail-panel/app-selector/app-picker.tsxindex 7889b83631e..0ba830899c1 100644--- a/web/app/components/plugins/plugin-detail-panel/app-selector/app-picker.tsx+++ b/web/app/components/plugins/plugin-detail-panel/app-selector/app-picker.tsx@@ -28,7 +28,6 @@ import {import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import AppIcon from '@/app/components/base/app-icon'-import { AppModeEnum } from '@/types/app'type AppPickerProps = Pick<ComboboxPositionerProps, 'placement'> & {scope?: string@@ -48,15 +47,15 @@ type AppPickerProps = Pick<ComboboxPositionerProps, 'placement'> & {function getAppTypeLabel(app: AppPartial) {switch (app.mode) {- case AppModeEnum.ADVANCED_CHAT:+ case 'advanced-chat':return 'chatflow'- case AppModeEnum.AGENT_CHAT:+ case 'agent-chat':return 'agent'- case AppModeEnum.CHAT:+ case 'chat':return 'chat'- case AppModeEnum.COMPLETION:+ case 'completion':return 'completion'- case AppModeEnum.WORKFLOW:+ case 'workflow':return 'workflow'default:return app.modediff --git a/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/__tests__/use-app-inputs-form-schema.spec.ts b/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/__tests__/use-app-inputs-form-schema.spec.tsindex f8862288758..b709e55deb3 100644--- a/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/__tests__/use-app-inputs-form-schema.spec.ts+++ b/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/__tests__/use-app-inputs-form-schema.spec.ts@@ -1,7 +1,7 @@import { renderHook } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import { BlockEnum, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'-import { AppModeEnum, Resolution } from '@/types/app'+import { Resolution } from '@/types/app'import { useAppInputsFormSchema } from '../use-app-inputs-form-schema'let mockAppDetailData: Record<string, unknown> | null = null@@ -54,7 +54,7 @@ describe('useAppInputsFormSchema', () => {it('should build basic app schemas and append image upload support', () => {mockAppDetailData = {id: 'app-1',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,model_config: {user_input_form: [{@@ -84,7 +84,7 @@ describe('useAppInputsFormSchema', () => {useAppInputsFormSchema({appDetail: {id: 'app-1',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,} as never,}),)@@ -108,7 +108,7 @@ describe('useAppInputsFormSchema', () => {it('should build workflow schemas from start node variables', () => {mockAppDetailData = {id: 'app-2',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,}mockAppWorkflowData = {graph: {@@ -134,7 +134,7 @@ describe('useAppInputsFormSchema', () => {useAppInputsFormSchema({appDetail: {id: 'app-2',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,} as never,}),)@@ -153,7 +153,7 @@ describe('useAppInputsFormSchema', () => {useAppInputsFormSchema({appDetail: {id: 'missing-app',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,} as never,}),)@@ -166,7 +166,7 @@ describe('useAppInputsFormSchema', () => {mockFileUploadConfigIsFetching = truemockAppDetailData = {id: 'app-1',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,model_config: {user_input_form: [{@@ -183,7 +183,7 @@ describe('useAppInputsFormSchema', () => {useAppInputsFormSchema({appDetail: {id: 'app-1',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,} as never,}),)@@ -203,7 +203,7 @@ describe('useAppInputsFormSchema', () => {useAppInputsFormSchema({appDetail: {id: 'app-2',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,} as never,}),)diff --git a/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/use-app-inputs-form-schema.ts b/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/use-app-inputs-form-schema.tsindex 41729e79b21..ca668d30b26 100644--- a/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/use-app-inputs-form-schema.ts+++ b/web/app/components/plugins/plugin-detail-panel/app-selector/hooks/use-app-inputs-form-schema.ts@@ -1,4 +1,5 @@'use client'+import type {AppDetailWithSite,AppPartial,@@ -13,7 +14,7 @@ import { BlockEnum, InputVarType, SupportUploadFileTypes } from '@/app/componentimport { consoleQuery } from '@/service/console'import { useFileUploadConfig } from '@/service/use-common'import { useAppWorkflow } from '@/service/use-workflow'-import { AppModeEnum, Resolution } from '@/types/app'+import { Resolution } from '@/types/app'const BASIC_INPUT_TYPE_MAP: Record<string, string> = {paragraph: 'paragraph',@@ -49,11 +50,11 @@ type WorkflowNodeWithVariables = {}function isBasicAppMode(mode: string): boolean {- return mode !== AppModeEnum.ADVANCED_CHAT && mode !== AppModeEnum.WORKFLOW+ return mode !== 'advanced-chat' && mode !== 'workflow'}function supportsImageUpload(mode: string): boolean {- return mode === AppModeEnum.COMPLETION || mode === AppModeEnum.WORKFLOW+ return mode === 'completion' || mode === 'workflow'}function buildFileConfig(fileConfig: FileUpload | undefined) {diff --git a/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsxindex 52a36c9f801..bb31fd60ce1 100644--- a/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/rag-pipeline-main.spec.tsx@@ -68,16 +68,10 @@ vi.mock('../../hooks/use-pipeline-start-run', () => ({}),}))-vi.mock('../../hooks/use-configs-map', () => ({- useConfigsMap: () => ({- flowId: 'test-flow-id',- flowType: 'ragPipeline',- fileSettings: {},- }),-}))+vi.mock('../../hooks/use-file-settings', () => ({ useFileSettings: () => ({ enabled: true }) }))-vi.mock('../../hooks/use-inspect-vars-crud', () => ({- useInspectVarsCrud: () => ({+vi.mock('@/app/components/workflow/hooks/use-inspect-vars-crud-common', () => ({+ useInspectVarsCrudCommon: () => ({hasNodeInspectVars: vi.fn(),hasSetInspectVar: vi.fn(),fetchInspectVarValue: vi.fn(),diff --git a/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsxindex 361e0d7b324..799e9ec048f 100644--- a/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx+++ b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx@@ -1,5 +1,6 @@-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, fireEvent, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { DSLImportStatus } from '@/models/app'import UpdateDSLModal from '../update-dsl-modal'@@ -133,43 +134,57 @@ describe('UpdateDSLModal', () => {describe('rendering', () => {it('should render title', () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(screen.getByText('workflow.common.importDSL')).toBeInTheDocument()})it('should render warning tip', () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(screen.getByText('workflow.common.importDSLTip')).toBeInTheDocument()})it('should render uploader', () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(screen.getByTestId('uploader')).toBeInTheDocument()})it('should render backup button', () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(screen.getByText('workflow.common.backupCurrentDraft')).toBeInTheDocument()})it('should render cancel button', () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(screen.getByText('app.newApp.Cancel')).toBeInTheDocument()})it('should render import button', () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(screen.getByText('workflow.common.overwriteAndImport')).toBeInTheDocument()})it('should render choose DSL section', () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(screen.getByText('workflow.common.chooseDSL')).toBeInTheDocument()})@@ -177,7 +192,9 @@ describe('UpdateDSLModal', () => {describe('user interactions', () => {it('should call onCancel when cancel button is clicked', () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const cancelButton = screen.getByText('app.newApp.Cancel')fireEvent.click(cancelButton)@@ -186,7 +203,9 @@ describe('UpdateDSLModal', () => {})it('should call onBackup when backup button is clicked', () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const backupButton = screen.getByText('workflow.common.backupCurrentDraft')fireEvent.click(backupButton)@@ -195,7 +214,9 @@ describe('UpdateDSLModal', () => {})it('should handle file upload', async () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -208,7 +229,9 @@ describe('UpdateDSLModal', () => {})it('should clear file when clear button is clicked', () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const clearButton = screen.getByTestId('clear-file')fireEvent.click(clearButton)@@ -219,14 +242,18 @@ describe('UpdateDSLModal', () => {describe('import functionality', () => {it('should show import button disabled when no file is selected', () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const importButton = screen.getByText('workflow.common.overwriteAndImport')expect(importButton).toBeDisabled()})it('should enable import button when file is selected', async () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -240,7 +267,9 @@ describe('UpdateDSLModal', () => {})it('should disable import button after file is cleared', async () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -263,7 +292,9 @@ describe('UpdateDSLModal', () => {describe('import flow', () => {it('should call importDSL when import button is clicked with file content', async () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -289,7 +320,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -319,7 +352,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -345,7 +380,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -377,7 +414,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -407,7 +446,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -437,7 +478,9 @@ describe('UpdateDSLModal', () => {pipeline_id: undefined,})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -463,7 +506,9 @@ describe('UpdateDSLModal', () => {it('should show error notification when import throws exception', async () => {mockImportDSL.mockRejectedValue(new Error('Import failed'))- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -493,7 +538,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -523,7 +570,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -553,7 +602,9 @@ describe('UpdateDSLModal', () => {current_dsl_version: '2.0.0',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -588,7 +639,9 @@ describe('UpdateDSLModal', () => {current_dsl_version: '2.0.0',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -620,7 +673,9 @@ describe('UpdateDSLModal', () => {current_dsl_version: '2.0.0',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -665,7 +720,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -715,7 +772,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -762,7 +821,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -806,7 +867,9 @@ describe('UpdateDSLModal', () => {mockImportDSLConfirm.mockRejectedValue(new Error('Confirm failed'))- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -853,7 +916,9 @@ describe('UpdateDSLModal', () => {pipeline_id: undefined,})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -900,7 +965,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -945,7 +1012,9 @@ describe('UpdateDSLModal', () => {pipeline_id: 'test-pipeline-id',})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -990,7 +1059,9 @@ describe('UpdateDSLModal', () => {current_dsl_version: undefined,})- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })const fileInput = screen.getByTestId('file-input')const file = new File(['test content'], 'test.pipeline', { type: 'text/yaml' })@@ -1013,7 +1084,9 @@ describe('UpdateDSLModal', () => {})it('should not call importDSLConfirm when importId is not set', async () => {- render(<UpdateDSLModal {...defaultProps} />)+ render(<UpdateDSLModal {...defaultProps} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(mockImportDSLConfirm).not.toHaveBeenCalled()})diff --git a/web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsxindex d580ece22e8..178cd3bcdf7 100644--- a/web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsx@@ -1,5 +1,6 @@import type { PanelProps } from '@/app/components/workflow/panel'-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import RagPipelinePanel from '../index'const { dynamicComponent } = vi.hoisted(() => {@@ -54,7 +55,9 @@ vi.mock('@/app/components/workflow/panel', () => ({describe('RagPipelinePanel', () => {it('renders enabled panels and supplies pipeline version endpoints', () => {- render(<RagPipelinePanel />)+ render(<RagPipelinePanel />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(screen.getByText('Record panel')).toBeInTheDocument()expect(screen.getByText('Test run panel')).toBeInTheDocument()@@ -69,8 +72,5 @@ describe('RagPipelinePanel', () => {expect(panelProps?.versionHistoryPanelProps?.deleteVersionUrl?.('version-1')).toBe('/rag/pipelines/pipeline-1/workflows/version-1',)- expect(panelProps?.versionHistoryPanelProps?.restoreVersionUrl?.('version-1')).toBe(- '/rag/pipelines/pipeline-1/workflows/version-1/restore',- )})})diff --git a/web/app/components/rag-pipeline/components/panel/index.tsx b/web/app/components/rag-pipeline/components/panel/index.tsxindex 4fd6f163c1f..cd3432a1b7c 100644--- a/web/app/components/rag-pipeline/components/panel/index.tsx+++ b/web/app/components/rag-pipeline/components/panel/index.tsx@@ -1,6 +1,8 @@import type { PanelProps } from '@/app/components/workflow/panel'+import { useAtomValue } from 'jotai'import dynamic from 'next/dynamic'import { memo, useMemo } from 'react'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import Panel from '@/app/components/workflow/panel'import { useStore } from '@/app/components/workflow/store'@@ -56,14 +58,12 @@ const RagPipelinePanelOnLeft = () => {}const RagPipelinePanel = () => {- const pipelineId = useStore((s) => s.pipelineId)+ const pipelineId = useAtomValue(knowledgePipelineIdentityAtom).pipelineIdconst versionHistoryPanelProps = useMemo(() => {return {getVersionListUrl: `/rag/pipelines/${pipelineId}/workflows`,deleteVersionUrl: (versionId: string) =>`/rag/pipelines/${pipelineId}/workflows/${versionId}`,- restoreVersionUrl: (versionId: string) =>- `/rag/pipelines/${pipelineId}/workflows/${versionId}/restore`,updateVersionUrl: (versionId: string) =>`/rag/pipelines/${pipelineId}/workflows/${versionId}`,latestVersionId: '',diff --git a/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/data-source.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/data-source.spec.tsxindex c838b2acd77..e4ee6f52ec5 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/data-source.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/data-source.spec.tsx@@ -1,5 +1,6 @@import type { Datasource } from '../../../test-run/types'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import DataSource from '../data-source'const { mockOnSelect, mockUseDraftPipelinePreProcessingParams } = vi.hoisted(() => ({@@ -48,7 +49,9 @@ describe('DataSource preview', () => {})it('should render the datasource selection step and forward selected values', () => {- render(<DataSource onSelect={mockOnSelect} dataSourceNodeId="node-1" />)+ render(<DataSource onSelect={mockOnSelect} dataSourceNodeId="node-1" />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })fireEvent.click(screen.getByText('select datasource'))diff --git a/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/index.spec.tsxindex c34c535c3f9..3d3f7d0780c 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/index.spec.tsx@@ -1,8 +1,9 @@import type { Datasource, DataSourceOption } from '../../../test-run/types'import type { RAGPipelineVariable, RAGPipelineVariables } from '@/models/pipeline'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor } from '@testing-library/react'import * as React from 'react'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { PipelineInputVarType } from '@/models/pipeline'import DataSource from '../data-source'import Form from '../form'@@ -210,7 +211,10 @@ const TestWrapper = ({ children }: { children: React.ReactNode }) => {}const renderWithProviders = (ui: React.ReactElement) => {- return render(ui, { wrapper: TestWrapper })+ return render(ui, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ wrapper: TestWrapper,+ })}describe('PreviewPanel', () => {diff --git a/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/process-documents.spec.tsx b/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/process-documents.spec.tsxindex f3fa9c24b78..4a0219b54b8 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/process-documents.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/preview/__tests__/process-documents.spec.tsx@@ -1,4 +1,5 @@-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import ProcessDocuments from '../process-documents'const mockUseDraftPipelineProcessingParams = vi.hoisted(() =>@@ -30,7 +31,9 @@ describe('ProcessDocuments preview', () => {})it('should render the processing step and its variables', () => {- render(<ProcessDocuments dataSourceNodeId="node-2" />)+ render(<ProcessDocuments dataSourceNodeId="node-2" />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(screen.getByText('datasetPipeline.inputFieldPanel.preview.stepTwoTitle'),diff --git a/web/app/components/rag-pipeline/components/panel/input-field/preview/data-source.tsx b/web/app/components/rag-pipeline/components/panel/input-field/preview/data-source.tsxindex 84bbb983782..e1d679a793e 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/preview/data-source.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/preview/data-source.tsx@@ -1,7 +1,8 @@import type { Datasource } from '../../test-run/types'+import { useAtomValue } from 'jotai'import * as React from 'react'import { useTranslation } from 'react-i18next'-import { useStore } from '@/app/components/workflow/store'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useDraftPipelinePreProcessingParams } from '@/service/use-pipeline'import DataSourceOptions from '../../test-run/preparation/data-source-options'import Form from './form'@@ -13,7 +14,7 @@ type DatasourceProps = {const DataSource = ({ onSelect: setDatasource, dataSourceNodeId }: DatasourceProps) => {const { t } = useTranslation(['datasetPipeline'])- const pipelineId = useStore((state) => state.pipelineId)+ const pipelineId = useAtomValue(knowledgePipelineIdentityAtom).pipelineIdconst { data: paramsConfig } = useDraftPipelinePreProcessingParams({pipeline_id: pipelineId!,diff --git a/web/app/components/rag-pipeline/components/panel/input-field/preview/process-documents.tsx b/web/app/components/rag-pipeline/components/panel/input-field/preview/process-documents.tsxindex 8ac1caed240..c346816f838 100644--- a/web/app/components/rag-pipeline/components/panel/input-field/preview/process-documents.tsx+++ b/web/app/components/rag-pipeline/components/panel/input-field/preview/process-documents.tsx@@ -1,6 +1,7 @@+import { useAtomValue } from 'jotai'import * as React from 'react'import { useTranslation } from 'react-i18next'-import { useStore } from '@/app/components/workflow/store'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useDraftPipelineProcessingParams } from '@/service/use-pipeline'import Form from './form'@@ -10,7 +11,7 @@ type ProcessDocumentsProps = {const ProcessDocuments = ({ dataSourceNodeId }: ProcessDocumentsProps) => {const { t } = useTranslation(['datasetPipeline'])- const pipelineId = useStore((state) => state.pipelineId)+ const pipelineId = useAtomValue(knowledgePipelineIdentityAtom).pipelineIdconst { data: paramsConfig } = useDraftPipelineProcessingParams({pipeline_id: pipelineId!,diff --git a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/hooks.spec.ts b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/hooks.spec.tsindex 61e68cd1f90..598ec4fb862 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/hooks.spec.ts+++ b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/hooks.spec.ts@@ -1,4 +1,4 @@-import { renderHook } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { useInputVariables } from '../hooks'const mockUseDraftPipelineProcessingParams = vi.hoisted(() =>@@ -23,7 +23,9 @@ describe('useInputVariables', () => {})it('should query processing params with the current pipeline id and datasource node id', () => {- const { result } = renderHook(() => useInputVariables('datasource-node'))+ const { result } = renderHook(() => useInputVariables('datasource-node'), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(mockUseDraftPipelineProcessingParams).toHaveBeenCalledWith({pipeline_id: 'pipeline-1',diff --git a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsxindex d30eef3e949..70e5d0b0d57 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/__tests__/index.spec.tsx@@ -7,9 +7,10 @@ import type {RAGPipelineVariables,} from '@/models/pipeline'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import * as React from 'react'import { BaseFieldType } from '@/app/components/base/form/form-scenarios/base/types'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { WorkflowRunningStatus } from '@/app/components/workflow/types'import { PipelineInputVarType } from '@/models/pipeline'import { expectLoadingButton } from '@/test/button'@@ -193,7 +194,9 @@ const createQueryClient = () =>const renderWithQueryClient = (component: React.ReactElement) => {const queryClient = createQueryClient()- return render(<QueryClientProvider client={queryClient}>{component}</QueryClientProvider>)+ return render(<QueryClientProvider client={queryClient}>{component}</QueryClientProvider>, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })}describe('DocumentProcessing', () => {@@ -475,7 +478,9 @@ describe('Actions', () => {it('should render back button', () => {const mockFormParams = createMockFormParams()- render(<Actions formParams={mockFormParams} onBack={vi.fn()} />)+ render(<Actions formParams={mockFormParams} onBack={vi.fn()} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(screen.getByText('datasetPipeline.operations.backToDataSource')).toBeInTheDocument()})@@ -483,7 +488,9 @@ describe('Actions', () => {it('should render process button', () => {const mockFormParams = createMockFormParams()- render(<Actions formParams={mockFormParams} onBack={vi.fn()} />)+ render(<Actions formParams={mockFormParams} onBack={vi.fn()} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(screen.getByText('datasetPipeline.operations.process')).toBeInTheDocument()})@@ -493,7 +500,9 @@ describe('Actions', () => {it('should disable process button when runDisabled is true', () => {const mockFormParams = createMockFormParams()- render(<Actions formParams={mockFormParams} runDisabled={true} onBack={vi.fn()} />)+ render(<Actions formParams={mockFormParams} runDisabled={true} onBack={vi.fn()} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).toBeDisabled()@@ -502,7 +511,9 @@ describe('Actions', () => {it('should disable process button when isSubmitting is true', () => {const mockFormParams = createMockFormParams({ isSubmitting: true })- render(<Actions formParams={mockFormParams} onBack={vi.fn()} />)+ render(<Actions formParams={mockFormParams} onBack={vi.fn()} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expectLoadingButton(processButton)@@ -511,7 +522,9 @@ describe('Actions', () => {it('should disable process button when canSubmit is false', () => {const mockFormParams = createMockFormParams({ canSubmit: false })- render(<Actions formParams={mockFormParams} onBack={vi.fn()} />)+ render(<Actions formParams={mockFormParams} onBack={vi.fn()} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).toBeDisabled()@@ -523,7 +536,9 @@ describe('Actions', () => {}const mockFormParams = createMockFormParams()- render(<Actions formParams={mockFormParams} onBack={vi.fn()} />)+ render(<Actions formParams={mockFormParams} onBack={vi.fn()} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expectLoadingButton(processButton)@@ -535,7 +550,9 @@ describe('Actions', () => {}const mockFormParams = createMockFormParams()- render(<Actions formParams={mockFormParams} runDisabled={false} onBack={vi.fn()} />)+ render(<Actions formParams={mockFormParams} runDisabled={false} onBack={vi.fn()} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).not.toBeDisabled()@@ -547,7 +564,9 @@ describe('Actions', () => {const mockOnBack = vi.fn()const mockFormParams = createMockFormParams()- render(<Actions formParams={mockFormParams} onBack={mockOnBack} />)+ render(<Actions formParams={mockFormParams} onBack={mockOnBack} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })fireEvent.click(screen.getByText('datasetPipeline.operations.backToDataSource'))@@ -558,7 +577,9 @@ describe('Actions', () => {const mockSubmit = vi.fn()const mockFormParams = createMockFormParams({ handleSubmit: mockSubmit })- render(<Actions formParams={mockFormParams} onBack={vi.fn()} />)+ render(<Actions formParams={mockFormParams} onBack={vi.fn()} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })fireEvent.click(screen.getByText('datasetPipeline.operations.process'))@@ -570,7 +591,9 @@ describe('Actions', () => {it('should handle undefined runDisabled prop', () => {const mockFormParams = createMockFormParams()- render(<Actions formParams={mockFormParams} onBack={vi.fn()} />)+ render(<Actions formParams={mockFormParams} onBack={vi.fn()} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).not.toBeDisabled()@@ -580,7 +603,9 @@ describe('Actions', () => {mockWorkflowRunningData = undefinedconst mockFormParams = createMockFormParams()- render(<Actions formParams={mockFormParams} onBack={vi.fn()} />)+ render(<Actions formParams={mockFormParams} onBack={vi.fn()} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const processButton = screen.getByText('datasetPipeline.operations.process').closest('button')expect(processButton).not.toBeDisabled()@@ -604,7 +629,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- const { container } = render(<Options {...props} />)+ const { container } = render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(container.querySelector('form')).toBeInTheDocument()})@@ -622,7 +649,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- render(<Options {...props} />)+ render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(screen.getByTestId('field-name')).toBeInTheDocument()expect(screen.getByTestId('field-email')).toBeInTheDocument()@@ -637,7 +666,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- render(<Options {...props} />)+ render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(screen.getByTestId('custom-action')).toBeInTheDocument()})@@ -654,7 +685,9 @@ describe('Options', () => {onSubmit: mockOnSubmit,}- const { container } = render(<Options {...props} />)+ const { container } = render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const form = container.querySelector('form')!const submitEvent = new Event('submit', { bubbles: true, cancelable: true })const preventDefaultSpy = vi.spyOn(submitEvent, 'preventDefault')@@ -674,7 +707,9 @@ describe('Options', () => {onSubmit: mockOnSubmit,}- const { container } = render(<Options {...props} />)+ const { container } = render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const form = container.querySelector('form')!const submitEvent = new Event('submit', { bubbles: true, cancelable: true })const stopPropagationSpy = vi.spyOn(submitEvent, 'stopPropagation')@@ -694,7 +729,9 @@ describe('Options', () => {onSubmit: mockOnSubmit,}- const { container } = render(<Options {...props} />)+ const { container } = render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const form = container.querySelector('form')!fireEvent.submit(form)@@ -719,7 +756,9 @@ describe('Options', () => {onSubmit: mockOnSubmit,}- const { container } = render(<Options {...props} />)+ const { container } = render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const form = container.querySelector('form')!fireEvent.submit(form)@@ -743,7 +782,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- const { container } = render(<Options {...props} />)+ const { container } = render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const form = container.querySelector('form')!fireEvent.submit(form)@@ -770,7 +811,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- const { container } = render(<Options {...props} />)+ const { container } = render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const form = container.querySelector('form')!fireEvent.submit(form)@@ -801,7 +844,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- const { container } = render(<Options {...props} />)+ const { container } = render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const form = container.querySelector('form')!fireEvent.submit(form)@@ -829,7 +874,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- const { container } = render(<Options {...props} />)+ const { container } = render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })const form = container.querySelector('form')!fireEvent.submit(form)@@ -855,7 +902,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- render(<Options {...props} />)+ render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(screen.getByTestId('field-first')).toBeInTheDocument()expect(screen.getByTestId('field-second')).toBeInTheDocument()@@ -883,7 +932,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- render(<Options {...props} />)+ render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(screen.getByTestId('field-label-test')).toHaveTextContent('Test Label')expect(screen.getByTestId('field-type-test')).toHaveTextContent(BaseFieldType.textInput)@@ -901,7 +952,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- const { container } = render(<Options {...props} />)+ const { container } = render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(container.querySelector('form')).toBeInTheDocument()})@@ -915,7 +968,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- render(<Options {...props} />)+ render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(screen.queryByTestId(/^field-/)).not.toBeInTheDocument()})@@ -942,7 +997,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- render(<Options {...props} />)+ render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(screen.getByTestId('field-text')).toBeInTheDocument()expect(screen.getByTestId('field-paragraph')).toBeInTheDocument()@@ -963,7 +1020,9 @@ describe('Options', () => {onSubmit: vi.fn(),}- render(<Options {...props} />)+ render(<Options {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })expect(screen.getAllByTestId(/^field-field_/)).toHaveLength(20)})diff --git a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/hooks.ts b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/hooks.tsindex 529932792c0..cd5809012a1 100644--- a/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/hooks.ts+++ b/web/app/components/rag-pipeline/components/panel/test-run/preparation/document-processing/hooks.ts@@ -1,8 +1,9 @@-import { useStore } from '@/app/components/workflow/store'+import { useAtomValue } from 'jotai'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useDraftPipelineProcessingParams } from '@/service/use-pipeline'export const useInputVariables = (datasourceNodeId: string) => {- const pipelineId = useStore((state) => state.pipelineId)+ const pipelineId = useAtomValue(knowledgePipelineIdentityAtom).pipelineIdconst { data: paramsConfig, isFetching: isFetchingParams } = useDraftPipelineProcessingParams({pipeline_id: pipelineId!,node_id: datasourceNodeId,diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/index.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/index.tsxindex 49b89c63c59..bfef426d4eb 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/index.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/index.tsx@@ -1,13 +1,14 @@import type { HeaderProps } from '@/app/components/workflow/header'+import { useAtomValue } from 'jotai'import { memo, useMemo } from 'react'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import Header from '@/app/components/workflow/header'-import { useStore } from '@/app/components/workflow/store'import InputFieldButton from './input-field-button'import Publisher from './publisher'import { RunMode } from './run-mode'const RagPipelineHeader = () => {- const pipelineId = useStore((s) => s.pipelineId)+ const pipelineId = useAtomValue(knowledgePipelineIdentityAtom).pipelineIdconst viewHistoryProps = useMemo(() => {return {diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsxindex c2bd364bb11..1174ee6a88c 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx@@ -4,9 +4,9 @@ import { fireEvent, screen, waitFor } from '@testing-library/react'import { NuqsTestingAdapter } from 'nuqs/adapters/testing'import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditor as renderWithoutPricing } from '@/app/components/workflow/editor-resource/__tests__/render'import { seedAccountProfileQuery } from '@/test/console/account-profile'import { seedFeatures, seedSystemFeatures } from '@/test/console/query-data'-import { render as renderWithoutPricing } from '@/test/console/render'import Publisher from '../index'import { Popup } from '../popup'@@ -219,7 +219,10 @@ const renderWithQueryClient = (ui: React.ReactElement) => {function render(...args: Parameters<typeof renderWithoutPricing>) {args[0] = <NuqsTestingAdapter onUrlUpdate={onPricingUrlUpdate}>{args[0]}</NuqsTestingAdapter>- return renderWithoutPricing(...args)+ return renderWithoutPricing(args[0], {+ ...args[1],+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })}vi.mock('@/next/navigation', () => ({ useParams: () => ({ datasetId: 'test-dataset-id' }) }))@@ -556,35 +559,6 @@ describe('publisher', () => {})})})-- it('should publish as template with empty pipeline id fallback', async () => {- mockPublishedAt.mockReturnValue(1700000000)- mockPipelineId.mockReturnValue(undefined as unknown as string)- mockPublishAsCustomizedPipeline.mockResolvedValue({})- renderWithQueryClient(<Publisher />)-- fireEvent.click(screen.getByText('workflow.common.publish'))-- const publishAsButton = screen- .getAllByRole('button')- .find((btn) => btn.textContent?.includes('pipeline.common.publishAs'))- fireEvent.click(publishAsButton!)-- await waitFor(() => {- expect(screen.getByTestId('publish-as-knowledge-pipeline-modal')).toBeInTheDocument()- })-- fireEvent.click(screen.getByTestId('modal-confirm'))-- await waitFor(() => {- expect(mockPublishAsCustomizedPipeline).toHaveBeenCalledWith({- pipelineId: '',- name: 'Test Pipeline',- icon_info: { type: 'emoji', emoji: '📚', background: '#fff' },- description: 'Test description',- })- })- })})describe('API Calls and Async Operations', () => {diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsxindex 7642b08b641..e0c0ec74132 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/popup.spec.tsx@@ -1,8 +1,8 @@import { fireEvent, screen, waitFor } from '@testing-library/react'import { NuqsTestingAdapter } from 'nuqs/adapters/testing'import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditor as renderWithConsoleState } from '@/app/components/workflow/editor-resource/__tests__/render'import { createConsoleQueryWrapper } from '@/test/console/query-data'-import { render as renderWithConsoleState } from '@/test/console/render'import { Popup } from '../popup'const onPricingUrlUpdate = vi.hoisted(() => vi.fn())@@ -14,7 +14,10 @@ const renderWithoutPricing = (ui: React.ReactElement) => {systemFeatures: { deployment_edition: 'CLOUD' },features: { knowledge_pipeline: { publish_enabled: mockIsAllowPublishAsCustom } },})- return renderWithConsoleState(ui, { wrapper })+ return renderWithConsoleState(ui, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ wrapper,+ })}const mockPublishWorkflow = vi.fn().mockResolvedValue({ created_at: '2024-01-01T00:00:00Z' })diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsxindex d97c96fbe32..c9958bfc744 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/index.tsx@@ -4,11 +4,12 @@ import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import { RiArrowDownSLine } from '@remixicon/react'import { useBoolean } from 'ahooks'+import { useAtomValue } from 'jotai'import { memo, useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useHooksStore } from '@/app/components/workflow/hooks-store'import { useNodesSyncDraft } from '@/app/components/workflow/hooks/use-nodes-sync-draft'-import { useStore } from '@/app/components/workflow/store'import { toast } from '@/app/notifications'import { useDocLink } from '@/context/i18n'import Link from '@/next/link'@@ -26,7 +27,7 @@ const Publisher = () => {const { handleSyncWorkflowDraft } = useNodesSyncDraft()const canPipelineRelease = useHooksStore((s) => s.accessControl.canReleaseAndVersion)const docLink = useDocLink()- const pipelineId = useStore((s) => s.pipelineId)+ const pipelineId = useAtomValue(knowledgePipelineIdentityAtom).pipelineIdconst { mutateAsync: publishAsCustomizedPipeline } = usePublishAsCustomizedPipeline()const invalidCustomizedTemplateList = useInvalidCustomizedTemplateList()const [showPublishAsKnowledgePipelineModal, setShowPublishAsKnowledgePipelineModal] =diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsxindex 50b7b6527c1..7241f29c233 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx@@ -26,6 +26,7 @@ import {pricingQueryParamName,pricingQueryParser,} from '@/app/components/billing/pricing/query-params'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useChecklistBeforePublish } from '@/app/components/workflow/hooks/use-checklist'import { useStore, useWorkflowStore } from '@/app/components/workflow/store'import { toast } from '@/app/notifications'@@ -74,7 +75,7 @@ export function Popup({const { datasetId } = useParams()const publishedAt = useStore((s) => s.publishedAt)const draftUpdatedAt = useStore((s) => s.draftUpdatedAt)- const pipelineId = useStore((s) => s.pipelineId)+ const pipelineId = useAtomValue(knowledgePipelineIdentityAtom).pipelineIdconst dataset = useDatasetDetailContextWithSelector((s) => s.dataset)const mutateDatasetRes = useDatasetDetailContextWithSelector((s) => s.mutateDatasetRes)const { data: currentUserId } = useSuspenseQuery({diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-main.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-main.tsxindex 7c7294a8bad..55e55278b4d 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-main.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-main.tsx@@ -5,16 +5,16 @@ import { useAtomValue } from 'jotai'import { useCallback, useMemo } from 'react'import { WorkflowWithInnerContext } from '@/app/components/workflow'import { useSetWorkflowVarsWithValue } from '@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars'+import { useInspectVarsCrudCommon as useInspectVarsCrud } from '@/app/components/workflow/hooks/use-inspect-vars-crud-common'import { useWorkflowStore } from '@/app/components/workflow/store'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'import { getDatasetACLCapabilities } from '@/utils/permission'import { useAvailableNodesMetaData } from '../hooks/use-available-nodes-meta-data'-import { useConfigsMap } from '../hooks/use-configs-map'import { useDSLByCanEdit } from '../hooks/use-DSL'+import { useFileSettings } from '../hooks/use-file-settings'import { useGetRunAndTraceUrl } from '../hooks/use-get-run-and-trace-url'-import { useInspectVarsCrud } from '../hooks/use-inspect-vars-crud'import { useNodesSyncDraftByCanEdit } from '../hooks/use-nodes-sync-draft'import { usePipelineRefreshDraft } from '../hooks/use-pipeline-refresh-draft'import { usePipelineRunByCanEdit } from '../hooks/use-pipeline-run'@@ -84,10 +84,8 @@ const RagPipelineMain = ({ nodes, edges, viewport }: RagPipelineMainProps) => {datasetACLCapabilities.canEdit,)- const configsMap = useConfigsMap()- const { fetchInspectVars } = useSetWorkflowVarsWithValue({- ...configsMap,- })+ const fileSettings = useFileSettings()+ const { fetchInspectVars } = useSetWorkflowVarsWithValue()const {hasNodeInspectVars,hasSetInspectVar,@@ -143,7 +141,7 @@ const RagPipelineMain = ({ nodes, edges, viewport }: RagPipelineMainProps) => {canImportExportDSL: datasetACLCapabilities.canImportExportDSL,canReleaseAndVersion: datasetACLCapabilities.canPipelineRelease,},- configsMap,+ fileSettings,}}, [availableNodesMetaData,@@ -177,7 +175,7 @@ const RagPipelineMain = ({ nodes, edges, viewport }: RagPipelineMainProps) => {resetConversationVar,invalidateConversationVarValues,datasetACLCapabilities,- configsMap,+ fileSettings,])return (diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.tsindex 5c47c92a466..6b4b9ef5c1e 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts@@ -1,8 +1,9 @@import type { ReactNode } from 'react'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { act, renderHook, waitFor } from '@testing-library/react'+import { act, waitFor } from '@testing-library/react'import { createElement } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { useDSLByCanEdit } from '../use-DSL'const toastMocks = vi.hoisted(() => ({@@ -47,7 +48,8 @@ vi.mock('@/app/components/workflow/store', () => ({}))const mockExportPipelineConfig = vi.fn()-vi.mock('@/service/console', () => ({+vi.mock('@/service/console', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/service/console')>()),consoleClient: {rag: {pipelines: {@@ -140,7 +142,10 @@ describe('useDSLByCanEdit', () => {callback.onError()return null})- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ wrapper,+ })await act(async () => {expect(await result.current.handleExportDSL()).toBe(false)})@@ -152,7 +157,10 @@ describe('useDSLByCanEdit', () => {it('allows export when draft synchronization is skipped for read-only access', async () => {mockDoSyncWorkflowDraft.mockResolvedValue(null)- const { result } = renderHook(() => useDSLByCanEdit(false), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(false), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ wrapper,+ })await act(async () => {expect(await result.current.handleExportDSL()).toBe(true)})@@ -160,20 +168,11 @@ describe('useDSLByCanEdit', () => {})describe('handleExportDSL', () => {- it('should return early when pipelineId is not set', async () => {- mockGetState.mockReturnValue({ pipelineId: null, knowledgeName: 'test' })-- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })-- await act(async () => {- await result.current.handleExportDSL()- })-- expect(mockDoSyncWorkflowDraft).not.toHaveBeenCalled()- })-it('should create and download file', async () => {- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ wrapper,+ })await act(async () => {await result.current.handleExportDSL()@@ -183,7 +182,10 @@ describe('useDSLByCanEdit', () => {})it('should set correct download filename', async () => {- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ wrapper,+ })await act(async () => {await result.current.handleExportDSL()@@ -197,7 +199,10 @@ describe('useDSLByCanEdit', () => {})it('should pass blob data to downloadBlob', async () => {- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ wrapper,+ })await act(async () => {await result.current.handleExportDSL()@@ -213,7 +218,10 @@ describe('useDSLByCanEdit', () => {it('should handle export error', async () => {mockExportPipelineConfig.mockRejectedValue(new Error('Export failed'))- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ wrapper,+ })await act(async () => {expect(await result.current.handleExportDSL()).toBe(false)@@ -228,7 +236,10 @@ describe('useDSLByCanEdit', () => {})it('should pass include parameter', async () => {- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ wrapper,+ })await act(async () => {await result.current.handleExportDSL(true)@@ -244,22 +255,13 @@ describe('useDSLByCanEdit', () => {})describe('exportCheck', () => {- it('should return early when pipelineId is not set', async () => {- mockGetState.mockReturnValue({ pipelineId: null })-- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })-- await act(async () => {- await result.current.exportCheck()- })-- expect(mockFetchWorkflowDraft).not.toHaveBeenCalled()- })-it('should call handleExportDSL directly when no secret variables', async () => {mockFetchWorkflowDraft.mockResolvedValue({ environment_variables: [] })- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ wrapper,+ })await act(async () => {await result.current.exportCheck()@@ -277,7 +279,10 @@ describe('useDSLByCanEdit', () => {const secretVars = [{ value_type: 'secret', name: 'API_KEY' }]mockFetchWorkflowDraft.mockResolvedValue({ environment_variables: secretVars })- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ wrapper,+ })await act(async () => {await result.current.exportCheck()@@ -296,7 +301,10 @@ describe('useDSLByCanEdit', () => {it('should handle export check error', async () => {mockFetchWorkflowDraft.mockRejectedValue(new Error('Fetch failed'))- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ wrapper,+ })await act(async () => {await result.current.exportCheck()diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-configs-map.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-configs-map.spec.tsdeleted file mode 100644index cb7b7fdaf3c..00000000000--- a/web/app/components/rag-pipeline/hooks/__tests__/use-configs-map.spec.ts+++ /dev/null@@ -1,69 +0,0 @@-import { renderHook } from '@testing-library/react'-import { describe, expect, it, vi } from 'vite-plus/test'-import { useConfigsMap } from '../use-configs-map'--const mockPipelineId = 'pipeline-xyz'-const mockFileUploadConfig = { max_size: 10 }--vi.mock('@/app/components/workflow/store', () => ({- useStore: (selector: (state: Record<string, unknown>) => unknown) => {- const state = {- pipelineId: mockPipelineId,- fileUploadConfig: mockFileUploadConfig,- }- return selector(state)- },-}))--vi.mock('@/types/app', () => ({- Resolution: { high: 'high' },- TransferMethod: { local_file: 'local_file', remote_url: 'remote_url' },-}))--vi.mock('@/types/common', () => ({- FlowType: { ragPipeline: 'rag-pipeline' },-}))--describe('useConfigsMap', () => {- it('should return flowId from pipelineId', () => {- const { result } = renderHook(() => useConfigsMap())-- expect(result.current.flowId).toBe('pipeline-xyz')- })-- it('should return ragPipeline as flowType', () => {- const { result } = renderHook(() => useConfigsMap())-- expect(result.current.flowType).toBe('rag-pipeline')- })-- it('should include file settings with image disabled', () => {- const { result } = renderHook(() => useConfigsMap())-- expect(result.current.fileSettings.image.enabled).toBe(false)- })-- it('should set image detail to high resolution', () => {- const { result } = renderHook(() => useConfigsMap())-- expect(result.current.fileSettings.image.detail).toBe('high')- })-- it('should set image number_limits to 3', () => {- const { result } = renderHook(() => useConfigsMap())-- expect(result.current.fileSettings.image.number_limits).toBe(3)- })-- it('should include both transfer methods for image', () => {- const { result } = renderHook(() => useConfigsMap())-- expect(result.current.fileSettings.image.transfer_methods).toEqual(['local_file', 'remote_url'])- })-- it('should pass through fileUploadConfig from store', () => {- const { result } = renderHook(() => useConfigsMap())-- expect(result.current.fileSettings.fileUploadConfig).toEqual({ max_size: 10 })- })-})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-file-settings.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-file-settings.spec.tsnew file mode 100644index 00000000000..b6afa47f6be--- /dev/null+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-file-settings.spec.ts@@ -0,0 +1,53 @@+import { renderHook } from '@testing-library/react'+import { describe, expect, it, vi } from 'vite-plus/test'+import { useFileSettings } from '../use-file-settings'++const mockPipelineId = 'pipeline-xyz'+const mockFileUploadConfig = { max_size: 10 }++vi.mock('@/app/components/workflow/store', () => ({+ useStore: (selector: (state: Record<string, unknown>) => unknown) => {+ const state = {+ pipelineId: mockPipelineId,+ fileUploadConfig: mockFileUploadConfig,+ }+ return selector(state)+ },+}))++vi.mock('@/types/app', () => ({+ Resolution: { high: 'high' },+ TransferMethod: { local_file: 'local_file', remote_url: 'remote_url' },+}))++describe('useFileSettings', () => {+ it('should include file settings with image disabled', () => {+ const { result } = renderHook(() => useFileSettings())++ expect(result.current.image.enabled).toBe(false)+ })++ it('should set image detail to high resolution', () => {+ const { result } = renderHook(() => useFileSettings())++ expect(result.current.image.detail).toBe('high')+ })++ it('should set image number_limits to 3', () => {+ const { result } = renderHook(() => useFileSettings())++ expect(result.current.image.number_limits).toBe(3)+ })++ it('should include both transfer methods for image', () => {+ const { result } = renderHook(() => useFileSettings())++ expect(result.current.image.transfer_methods).toEqual(['local_file', 'remote_url'])+ })++ it('should pass through fileUploadConfig from store', () => {+ const { result } = renderHook(() => useFileSettings())++ expect(result.current.fileUploadConfig).toEqual({ max_size: 10 })+ })+})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-get-run-and-trace-url.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-get-run-and-trace-url.spec.tsindex c4502b42675..4feab0ddc98 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-get-run-and-trace-url.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-get-run-and-trace-url.spec.ts@@ -1,5 +1,5 @@-import { renderHook } from '@testing-library/react'import { describe, expect, it, vi } from 'vite-plus/test'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { useGetRunAndTraceUrl } from '../use-get-run-and-trace-url'vi.mock('@/app/components/workflow/store', () => ({@@ -12,21 +12,27 @@ vi.mock('@/app/components/workflow/store', () => ({describe('useGetRunAndTraceUrl', () => {it('should generate correct runUrl', () => {- const { result } = renderHook(() => useGetRunAndTraceUrl())+ const { result } = renderHook(() => useGetRunAndTraceUrl(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-test-123' },+ })const { runUrl } = result.current.getWorkflowRunAndTraceUrl('run-abc')expect(runUrl).toBe('/rag/pipelines/pipeline-test-123/workflow-runs/run-abc')})it('should generate correct traceUrl', () => {- const { result } = renderHook(() => useGetRunAndTraceUrl())+ const { result } = renderHook(() => useGetRunAndTraceUrl(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-test-123' },+ })const { traceUrl } = result.current.getWorkflowRunAndTraceUrl('run-abc')expect(traceUrl).toBe('/rag/pipelines/pipeline-test-123/workflow-runs/run-abc/node-executions')})it('should handle different runIds', () => {- const { result } = renderHook(() => useGetRunAndTraceUrl())+ const { result } = renderHook(() => useGetRunAndTraceUrl(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-test-123' },+ })const r1 = result.current.getWorkflowRunAndTraceUrl('id-1')const r2 = result.current.getWorkflowRunAndTraceUrl('id-2')diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-inspect-vars-crud.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-inspect-vars-crud.spec.tsdeleted file mode 100644index 495531a1fe4..00000000000--- a/web/app/components/rag-pipeline/hooks/__tests__/use-inspect-vars-crud.spec.ts+++ /dev/null@@ -1,98 +0,0 @@-import { renderHook } from '@testing-library/react'-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'-import { useInspectVarsCrud } from '../use-inspect-vars-crud'--// Mock return value for useInspectVarsCrudCommon-const mockApis = {- hasNodeInspectVars: vi.fn(),- hasSetInspectVar: vi.fn(),- fetchInspectVarValue: vi.fn(),- editInspectVarValue: vi.fn(),- renameInspectVarName: vi.fn(),- appendNodeInspectVars: vi.fn(),- deleteInspectVar: vi.fn(),- deleteNodeInspectorVars: vi.fn(),- deleteAllInspectorVars: vi.fn(),- isInspectVarEdited: vi.fn(),- resetToLastRunVar: vi.fn(),- invalidateSysVarValues: vi.fn(),- resetConversationVar: vi.fn(),- invalidateConversationVarValues: vi.fn(),-}--const mockUseInspectVarsCrudCommon = vi.fn(() => mockApis)-vi.mock('@/app/components/workflow/hooks/use-inspect-vars-crud-common', () => ({- useInspectVarsCrudCommon: (...args: Parameters<typeof mockUseInspectVarsCrudCommon>) =>- mockUseInspectVarsCrudCommon(...args),-}))--const mockConfigsMap = {- flowId: 'pipeline-123',- flowType: 'rag_pipeline',- fileSettings: {- image: { enabled: false },- fileUploadConfig: {},- },-}--vi.mock('../use-configs-map', () => ({- useConfigsMap: () => mockConfigsMap,-}))--describe('useInspectVarsCrud', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- // Verify the hook composes useConfigsMap with useInspectVarsCrudCommon- describe('Composition', () => {- it('should pass configsMap to useInspectVarsCrudCommon', () => {- renderHook(() => useInspectVarsCrud())-- expect(mockUseInspectVarsCrudCommon).toHaveBeenCalledWith(- expect.objectContaining({- flowId: 'pipeline-123',- flowType: 'rag_pipeline',- }),- )- })-- it('should return all APIs from useInspectVarsCrudCommon', () => {- const { result } = renderHook(() => useInspectVarsCrud())-- expect(result.current.hasNodeInspectVars).toBe(mockApis.hasNodeInspectVars)- expect(result.current.fetchInspectVarValue).toBe(mockApis.fetchInspectVarValue)- expect(result.current.editInspectVarValue).toBe(mockApis.editInspectVarValue)- expect(result.current.deleteInspectVar).toBe(mockApis.deleteInspectVar)- expect(result.current.deleteAllInspectorVars).toBe(mockApis.deleteAllInspectorVars)- expect(result.current.resetToLastRunVar).toBe(mockApis.resetToLastRunVar)- expect(result.current.resetConversationVar).toBe(mockApis.resetConversationVar)- })- })-- // Verify the hook spreads all returned properties- describe('API Surface', () => {- it('should expose all expected API methods', () => {- const { result } = renderHook(() => useInspectVarsCrud())-- const expectedKeys = [- 'hasNodeInspectVars',- 'hasSetInspectVar',- 'fetchInspectVarValue',- 'editInspectVarValue',- 'renameInspectVarName',- 'appendNodeInspectVars',- 'deleteInspectVar',- 'deleteNodeInspectorVars',- 'deleteAllInspectorVars',- 'isInspectVarEdited',- 'resetToLastRunVar',- 'invalidateSysVarValues',- 'resetConversationVar',- 'invalidateConversationVarValues',- ]-- for (const key of expectedKeys) expect(result.current).toHaveProperty(key)- })- })-})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.tsindex 46a4f75b925..029fd026923 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-nodes-sync-draft.spec.ts@@ -1,6 +1,6 @@-import { renderHook } from '@testing-library/react'import { act } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { createHttpError } from '@/service/http-error'import { useNodesSyncDraft } from '../use-nodes-sync-draft'@@ -30,7 +30,7 @@ vi.mock('@/app/components/workflow/hooks/use-workflow', () => ({const mockSyncWorkflowDraft = vi.fn()// Stand in for the draft sync request at the client boundary: record the request it sends// and validate rejections against the contract, as the console link does.-vi.mock('@/service/console', async () => {+vi.mock('@/service/console', async (importOriginal) => {const { rag } = await import('@dify/contracts/api/console/rag/orpc.gen')const { validateDefinedErrors } = await import('@/service/console/defined-errors')const validate = validateDefinedErrors({ rag })@@ -46,6 +46,7 @@ vi.mock('@/service/console', async () => {}),})return {+ ...(await importOriginal<typeof import('@/service/console')>()),consoleClient: { rag: { pipelines: { byPipelineId: { workflows: { draft: { post } } } } } },}})@@ -57,12 +58,14 @@ vi.mock('../use-pipeline-refresh-draft', () => ({}),}))-vi.mock('@/config', () => ({+vi.mock('@/config', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/config')>()),API_PREFIX: '/api',}))const mockPostWithKeepalive = vi.fn()-vi.mock('@/service/fetch', () => ({+vi.mock('@/service/fetch', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/service/fetch')>()),postWithKeepalive: (...args: unknown[]) => mockPostWithKeepalive(...args),}))@@ -103,14 +106,18 @@ describe('useNodesSyncDraft', () => {describe('hook initialization', () => {it('should return doSyncWorkflowDraft function', () => {- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(result.current.doSyncWorkflowDraft).toBeDefined()expect(typeof result.current.doSyncWorkflowDraft).toBe('function')})it('should return syncWorkflowDraftWhenPageClose function', () => {- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(result.current.syncWorkflowDraftWhenPageClose).toBeDefined()expect(typeof result.current.syncWorkflowDraftWhenPageClose).toBe('function')@@ -121,7 +128,9 @@ describe('useNodesSyncDraft', () => {it('should not call postWithKeepalive when nodes are read only', () => {mockGetNodesReadOnly.mockReturnValue(true)- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.syncWorkflowDraftWhenPageClose()@@ -136,7 +145,9 @@ describe('useNodesSyncDraft', () => {{ id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },])- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.syncWorkflowDraftWhenPageClose()@@ -151,27 +162,12 @@ describe('useNodesSyncDraft', () => {)})- it('should not call postWithKeepalive when pipelineId is missing', () => {- mockWorkflowStoreGetState.mockReturnValue({- pipelineId: undefined,- environmentVariables: [],- syncWorkflowDraftHash: 'test-hash',- ragPipelineVariables: [],- })-- const { result } = renderHook(() => useNodesSyncDraft())-- act(() => {- result.current.syncWorkflowDraftWhenPageClose()- })-- expect(mockPostWithKeepalive).not.toHaveBeenCalled()- })-it('should not call postWithKeepalive when nodes array is empty', () => {mockGetNodes.mockReturnValue([])- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.syncWorkflowDraftWhenPageClose()@@ -185,7 +181,9 @@ describe('useNodesSyncDraft', () => {{ id: 'node-1', data: { type: 'start', _isTempNode: true }, position: { x: 0, y: 0 } },])- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.syncWorkflowDraftWhenPageClose()@@ -199,7 +197,9 @@ describe('useNodesSyncDraft', () => {{ id: 'node-1', data: { type: 'start', _privateData: 'secret' }, position: { x: 0, y: 0 } },])- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.syncWorkflowDraftWhenPageClose()@@ -215,7 +215,9 @@ describe('useNodesSyncDraft', () => {it('should not sync when nodes are read only', async () => {mockGetNodesReadOnly.mockReturnValue(true)- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.doSyncWorkflowDraft()@@ -230,7 +232,9 @@ describe('useNodesSyncDraft', () => {{ id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },])- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.doSyncWorkflowDraft()@@ -258,7 +262,9 @@ describe('useNodesSyncDraft', () => {transform: [10, 20, 1.5],})- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>act(() => {@@ -310,7 +316,9 @@ describe('useNodesSyncDraft', () => {.mockResolvedValueOnce({ hash: 'hash-after-first-sync', updated_at: 'first-update' }).mockResolvedValueOnce({ hash: 'hash-after-second-sync', updated_at: 'second-update' })- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })let firstSync!: ReturnType<typeof result.current.doSyncWorkflowDraft>let secondSync!: ReturnType<typeof result.current.doSyncWorkflowDraft>@@ -343,7 +351,9 @@ describe('useNodesSyncDraft', () => {{ id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },])- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.doSyncWorkflowDraft()@@ -365,7 +375,9 @@ describe('useNodesSyncDraft', () => {])const onSuccess = vi.fn()- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.doSyncWorkflowDraft(false, { onSuccess })@@ -381,7 +393,9 @@ describe('useNodesSyncDraft', () => {])const onSettled = vi.fn()- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.doSyncWorkflowDraft(false, { onSettled })@@ -398,7 +412,9 @@ describe('useNodesSyncDraft', () => {mockSyncWorkflowDraft.mockRejectedValue(new Error('Sync failed'))const onError = vi.fn()- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.doSyncWorkflowDraft(false, { onError })@@ -424,7 +440,9 @@ describe('useNodesSyncDraft', () => {setDraftUpdatedAt: mockSetDraftUpdatedAt,})- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.doSyncWorkflowDraft()@@ -447,7 +465,9 @@ describe('useNodesSyncDraft', () => {})mockSyncWorkflowDraft.mockRejectedValue(mockJsonError)- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.doSyncWorkflowDraft(false)@@ -471,7 +491,9 @@ describe('useNodesSyncDraft', () => {})mockSyncWorkflowDraft.mockRejectedValue(mockJsonError)- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.doSyncWorkflowDraft(true)@@ -494,7 +516,9 @@ describe('useNodesSyncDraft', () => {{ id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },])- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.syncWorkflowDraftWhenPageClose()@@ -517,7 +541,9 @@ describe('useNodesSyncDraft', () => {{ id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },])- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.syncWorkflowDraftWhenPageClose()@@ -540,7 +566,9 @@ describe('useNodesSyncDraft', () => {{ id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },])- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.syncWorkflowDraftWhenPageClose()@@ -555,7 +583,9 @@ describe('useNodesSyncDraft', () => {{ id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },])- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.syncWorkflowDraftWhenPageClose()@@ -582,7 +612,9 @@ describe('useNodesSyncDraft', () => {{ id: 'node-1', data: { type: 'start' }, position: { x: 0, y: 0 } },])- const { result } = renderHook(() => useNodesSyncDraft())+ const { result } = renderHook(() => useNodesSyncDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.syncWorkflowDraftWhenPageClose()diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.tsindex fdb26ea5525..c8fe3753d24 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.ts@@ -4,6 +4,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'import { createElement } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'import { WorkflowContext } from '@/app/components/workflow/context'+import { EditorResourceScope } from '@/app/components/workflow/editor-resource/provider'import { createWorkflowStore } from '@/app/components/workflow/store'import { consoleQuery } from '@/service/console'import { createDatasourceProvider } from '../../__tests__/datasource-fixtures'@@ -20,20 +21,24 @@ vi.mock('@/service/use-workflow', () => ({ useWorkflowConfig: mocks.workflowConfconst catalog = consoleQuery.rag.pipelines.datasourcePlugins.getdescribe('usePipelineConfig', () => {+ let pipelineId: stringlet client: QueryClientlet store: ReturnType<typeof createWorkflowStore>const wrapper = ({ children }: PropsWithChildren) =>createElement(QueryClientProvider,{ client },- createElement(WorkflowContext.Provider, { value: store }, children),+ createElement(EditorResourceScope, {+ resource: { kind: 'knowledge-pipeline', pipelineId },+ children: createElement(WorkflowContext.Provider, { value: store }, children),+ }),)beforeEach(() => {vi.clearAllMocks()client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })store = createWorkflowStore({ injectWorkflowStoreSliceFn: createRagPipelineSliceSlice })- store.setState({ pipelineId: 'pipeline-1' })+ pipelineId = 'pipeline-1'mocks.request.mockResolvedValue(Response.json([]))})afterEach(() => client.clear())@@ -74,7 +79,7 @@ describe('usePipelineConfig', () => {})it('does not request or hydrate datasource state before a pipeline is available', () => {- store.setState({ pipelineId: '' })+ pipelineId = ''client.setQueryData(catalog.queryKey(), [createDatasourceProvider()])renderHook(usePipelineConfig, { wrapper })@@ -84,12 +89,13 @@ describe('usePipelineConfig', () => {})it('fetches and synchronizes when the pipeline becomes available', async () => {- store.setState({ pipelineId: '' })+ pipelineId = ''const providers = [createDatasourceProvider()]mocks.request.mockResolvedValue(Response.json(providers))- renderHook(usePipelineConfig, { wrapper })+ const { rerender } = renderHook(usePipelineConfig, { wrapper })- act(() => store.setState({ pipelineId: 'pipeline-2' }))+ pipelineId = 'pipeline-2'+ rerender()await waitFor(() => expect(store.getState().dataSourceList).toEqual(providers))})diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.tsindex 499777d5ec3..7d8e724cc9b 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.ts@@ -1,5 +1,6 @@-import { renderHook, waitFor } from '@testing-library/react'+import { waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { createHttpError } from '@/service/http-error'import { usePipelineInit } from '../use-pipeline-init'@@ -90,17 +91,20 @@ describe('usePipelineInit', () => {describe('hook initialization', () => {it('should return data and isLoading', async () => {- const { result } = renderHook(() => usePipelineInit())+ const { result } = renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(result.current.isLoading).toBe(true)expect(result.current.data).toBeUndefined()})- it('should set pipelineId in workflow store on mount', () => {- renderHook(() => usePipelineInit())+ it('should initialize the knowledge presentation metadata', () => {+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({- pipelineId: 'test-pipeline-id',knowledgeName: 'Test Knowledge',knowledgeIcon: { icon: 'test-icon' },})@@ -109,7 +113,9 @@ describe('usePipelineInit', () => {describe('data fetching', () => {it('should fetch workflow draft on mount', async () => {- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockFetchWorkflowDraft).toHaveBeenCalledWith(@@ -119,7 +125,9 @@ describe('usePipelineInit', () => {})it('should set data after successful fetch', async () => {- const { result } = renderHook(() => usePipelineInit())+ const { result } = renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(result.current.data).toBeDefined()@@ -127,7 +135,9 @@ describe('usePipelineInit', () => {})it('should set isLoading to false after fetch', async () => {- const { result } = renderHook(() => usePipelineInit())+ const { result } = renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(result.current.isLoading).toBe(false)@@ -135,7 +145,9 @@ describe('usePipelineInit', () => {})it('should set draft updated at', async () => {- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockSetDraftUpdatedAt).toHaveBeenCalledWith('2024-01-01T00:00:00Z')@@ -143,7 +155,9 @@ describe('usePipelineInit', () => {})it('should set tool published status', async () => {- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockSetToolPublished).toHaveBeenCalledWith(true)@@ -151,7 +165,9 @@ describe('usePipelineInit', () => {})it('should set sync hash', async () => {- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockSetSyncWorkflowDraftHash).toHaveBeenCalledWith('test-hash')@@ -159,7 +175,9 @@ describe('usePipelineInit', () => {})it('should mark workflow data as loaded after a successful fetch', async () => {- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({ isWorkflowDataLoaded: true })@@ -181,7 +199,9 @@ describe('usePipelineInit', () => {rag_pipeline_variables: [],})- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockSetEnvSecrets).toHaveBeenCalledWith({ 'env-1': 'secret-value' })@@ -201,7 +221,9 @@ describe('usePipelineInit', () => {rag_pipeline_variables: [],})- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockSetEnvironmentVariables).toHaveBeenCalledWith([@@ -221,7 +243,9 @@ describe('usePipelineInit', () => {rag_pipeline_variables: [],})- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockSetEnvSecrets).toHaveBeenCalledWith({})@@ -241,7 +265,9 @@ describe('usePipelineInit', () => {rag_pipeline_variables: [{ variable: 'query', type: 'text-input' }],})- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockSetRagPipelineVariables).toHaveBeenCalledWith([@@ -260,7 +286,9 @@ describe('usePipelineInit', () => {rag_pipeline_variables: undefined,})- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockSetRagPipelineVariables).toHaveBeenCalledWith([])@@ -287,7 +315,9 @@ describe('usePipelineInit', () => {rag_pipeline_variables: [],})- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({@@ -306,7 +336,9 @@ describe('usePipelineInit', () => {mockFetchWorkflowDraft.mockRejectedValueOnce(mockJsonError)mockSyncWorkflowDraft.mockResolvedValue({ updated_at: '2024-01-02T00:00:00Z' })- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockSyncWorkflowDraft).toHaveBeenCalledWith({@@ -332,7 +364,9 @@ describe('usePipelineInit', () => {},)- renderHook(() => usePipelineInit())+ renderHook(() => usePipelineInit(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await waitFor(() => {expect(mockFetchWorkflowDraft).toHaveBeenCalled()diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.tsindex ec44c58ebcb..d1b5278017f 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-refresh-draft.spec.ts@@ -1,6 +1,7 @@-import { renderHook, waitFor } from '@testing-library/react'+import { waitFor } from '@testing-library/react'import { act } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { usePipelineRefreshDraft } from '../use-pipeline-refresh-draft'const mockWorkflowStoreGetState = vi.fn()@@ -66,7 +67,9 @@ describe('usePipelineRefreshDraft', () => {describe('hook initialization', () => {it('should return handleRefreshWorkflowDraft function', () => {- const { result } = renderHook(() => usePipelineRefreshDraft())+ const { result } = renderHook(() => usePipelineRefreshDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(result.current.handleRefreshWorkflowDraft).toBeDefined()expect(typeof result.current.handleRefreshWorkflowDraft).toBe('function')@@ -75,7 +78,9 @@ describe('usePipelineRefreshDraft', () => {describe('handleRefreshWorkflowDraft', () => {it('should set syncing state to true at start', async () => {- const { result } = renderHook(() => usePipelineRefreshDraft())+ const { result } = renderHook(() => usePipelineRefreshDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRefreshWorkflowDraft()@@ -85,7 +90,9 @@ describe('usePipelineRefreshDraft', () => {})it('should fetch workflow draft with correct URL', async () => {- const { result } = renderHook(() => usePipelineRefreshDraft())+ const { result } = renderHook(() => usePipelineRefreshDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRefreshWorkflowDraft()@@ -97,7 +104,9 @@ describe('usePipelineRefreshDraft', () => {})it('should update workflow canvas with response data', async () => {- const { result } = renderHook(() => usePipelineRefreshDraft())+ const { result } = renderHook(() => usePipelineRefreshDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRefreshWorkflowDraft()@@ -109,7 +118,9 @@ describe('usePipelineRefreshDraft', () => {})it('should update sync hash after fetch', async () => {- const { result } = renderHook(() => usePipelineRefreshDraft())+ const { result } = renderHook(() => usePipelineRefreshDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRefreshWorkflowDraft()@@ -132,7 +143,9 @@ describe('usePipelineRefreshDraft', () => {rag_pipeline_variables: [{ variable: 'query', type: 'text-input' }],})- const { result } = renderHook(() => usePipelineRefreshDraft())+ const { result } = renderHook(() => usePipelineRefreshDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRefreshWorkflowDraft()@@ -146,7 +159,9 @@ describe('usePipelineRefreshDraft', () => {})it('should set syncing state to false after completion', async () => {- const { result } = renderHook(() => usePipelineRefreshDraft())+ const { result } = renderHook(() => usePipelineRefreshDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRefreshWorkflowDraft()@@ -171,7 +186,9 @@ describe('usePipelineRefreshDraft', () => {],})- const { result } = renderHook(() => usePipelineRefreshDraft())+ const { result } = renderHook(() => usePipelineRefreshDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRefreshWorkflowDraft()@@ -196,7 +213,9 @@ describe('usePipelineRefreshDraft', () => {],})- const { result } = renderHook(() => usePipelineRefreshDraft())+ const { result } = renderHook(() => usePipelineRefreshDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRefreshWorkflowDraft()@@ -221,7 +240,9 @@ describe('usePipelineRefreshDraft', () => {environment_variables: [],})- const { result } = renderHook(() => usePipelineRefreshDraft())+ const { result } = renderHook(() => usePipelineRefreshDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRefreshWorkflowDraft()@@ -244,7 +265,9 @@ describe('usePipelineRefreshDraft', () => {environment_variables: undefined,})- const { result } = renderHook(() => usePipelineRefreshDraft())+ const { result } = renderHook(() => usePipelineRefreshDraft(), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRefreshWorkflowDraft()diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.tsindex 7853a84f46f..ecf56bd1a29 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts@@ -1,7 +1,7 @@import type { VersionHistory } from '@/types/workflow'-import { renderHook } from '@testing-library/react'import { act } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { WorkflowRunningStatus } from '@/app/components/workflow/types'import { usePipelineRunByCanEdit } from '../use-pipeline-run'@@ -80,16 +80,10 @@ vi.mock('@/service/workflow', () => ({const mockInvalidAllLastRun = vi.fn()const mockInvalidateRunHistory = vi.fn()vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mockInvalidAllLastRun,+ useInvalidateAllLastRun: () => mockInvalidAllLastRun,useInvalidateWorkflowRunHistory: () => mockInvalidateRunHistory,}))-vi.mock('@/types/common', () => ({- FlowType: {- ragPipeline: 'rag-pipeline',- },-}))-describe('usePipelineRunByCanEdit', () => {const mockSetNodes = vi.fn()const mockGetNodes = vi.fn()@@ -149,35 +143,45 @@ describe('usePipelineRunByCanEdit', () => {describe('hook initialization', () => {it('should return handleBackupDraft function', () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(result.current.handleBackupDraft).toBeDefined()expect(typeof result.current.handleBackupDraft).toBe('function')})it('should return handleLoadBackupDraft function', () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(result.current.handleLoadBackupDraft).toBeDefined()expect(typeof result.current.handleLoadBackupDraft).toBe('function')})it('should return handleRun function', () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(result.current.handleRun).toBeDefined()expect(typeof result.current.handleRun).toBe('function')})it('should return handleStopRun function', () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(result.current.handleStopRun).toBeDefined()expect(typeof result.current.handleStopRun).toBe('function')})it('should return handleRestoreFromPublishedWorkflow function', () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })expect(result.current.handleRestoreFromPublishedWorkflow).toBeDefined()expect(typeof result.current.handleRestoreFromPublishedWorkflow).toBe('function')@@ -186,7 +190,9 @@ describe('usePipelineRunByCanEdit', () => {describe('handleBackupDraft', () => {it('should backup draft when no backup exists', () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleBackupDraft()@@ -207,7 +213,9 @@ describe('usePipelineRunByCanEdit', () => {setWorkflowRunningData: mockSetWorkflowRunningData,})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleBackupDraft()@@ -236,7 +244,9 @@ describe('usePipelineRunByCanEdit', () => {setWorkflowRunningData: mockSetWorkflowRunningData,})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleLoadBackupDraft()@@ -262,7 +272,9 @@ describe('usePipelineRunByCanEdit', () => {setWorkflowRunningData: mockSetWorkflowRunningData,})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleLoadBackupDraft()@@ -274,7 +286,9 @@ describe('usePipelineRunByCanEdit', () => {describe('handleStopRun', () => {it('should call stop workflow run service', () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleStopRun('task-123')@@ -298,7 +312,9 @@ describe('usePipelineRunByCanEdit', () => {rag_pipeline_variables: [{ variable: 'input', type: 'text-input' }],}- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRestoreFromPublishedWorkflow(@@ -324,7 +340,9 @@ describe('usePipelineRunByCanEdit', () => {rag_pipeline_variables: [],}- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRestoreFromPublishedWorkflow(@@ -346,7 +364,9 @@ describe('usePipelineRunByCanEdit', () => {rag_pipeline_variables: [{ variable: 'query', type: 'text-input' }],}- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRestoreFromPublishedWorkflow(@@ -370,7 +390,9 @@ describe('usePipelineRunByCanEdit', () => {rag_pipeline_variables: undefined,}- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleRestoreFromPublishedWorkflow(@@ -385,7 +407,9 @@ describe('usePipelineRunByCanEdit', () => {describe('handleRun', () => {it('should sync workflow draft before running', async () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} })@@ -395,7 +419,9 @@ describe('usePipelineRunByCanEdit', () => {})it('should reset node selection and running status', async () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} })@@ -405,7 +431,9 @@ describe('usePipelineRunByCanEdit', () => {})it('should clear history workflow data', async () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} })@@ -415,7 +443,9 @@ describe('usePipelineRunByCanEdit', () => {})it('should set initial running data', async () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} })@@ -434,7 +464,9 @@ describe('usePipelineRunByCanEdit', () => {})it('should call ssePost with correct URL', async () => {- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: { query: 'test' } })@@ -455,7 +487,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onWorkflowStarted })@@ -477,7 +511,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onWorkflowFinished })@@ -499,7 +535,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onError })@@ -521,7 +559,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onNodeStarted })@@ -542,7 +582,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onNodeFinished })@@ -563,7 +605,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onIterationStart })@@ -584,7 +628,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onIterationNext })@@ -605,7 +651,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onIterationFinish })@@ -626,7 +674,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onLoopStart })@@ -647,7 +697,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onLoopNext })@@ -668,7 +720,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onLoopFinish })@@ -689,7 +743,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onNodeRetry })@@ -710,7 +766,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, { onAgentLog })@@ -730,7 +788,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} })@@ -750,7 +810,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} })@@ -771,7 +833,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} }, {@@ -789,7 +853,9 @@ describe('usePipelineRunByCanEdit', () => {capturedCallbacks = callbacks})- const { result } = renderHook(() => usePipelineRunByCanEdit(true))+ const { result } = renderHook(() => usePipelineRunByCanEdit(true), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })await act(async () => {await result.current.handleRun({ inputs: {} })diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.tsindex 847702e82be..72f72cdcf8d 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts@@ -1,5 +1,6 @@-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { DSLImportMode, DSLImportStatus } from '@/models/app'import { httpErrorFromResponse } from '@/service/http-error'import { useUpdateDSLModal } from '../use-update-dsl-modal'@@ -100,11 +101,13 @@ describe('useUpdateDSLModal', () => {const mockOnImport = vi.fn()const renderUpdateDSLModal = (overrides?: { onImport?: () => void }) =>- renderHook(() =>- useUpdateDSLModal({- onCancel: mockOnCancel,- onImport: overrides?.onImport ?? mockOnImport,- }),+ renderHook(+ () =>+ useUpdateDSLModal({+ onCancel: mockOnCancel,+ onImport: overrides?.onImport ?? mockOnImport,+ }),+ { resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' } },)beforeEach(() => {@@ -599,7 +602,9 @@ describe('useUpdateDSLModal', () => {describe('optional onImport', () => {it('should work without onImport callback', async () => {- const { result } = renderHook(() => useUpdateDSLModal({ onCancel: mockOnCancel }))+ const { result } = renderHook(() => useUpdateDSLModal({ onCancel: mockOnCancel }), {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline-id' },+ })act(() => {result.current.handleFile(createFile())diff --git a/web/app/components/rag-pipeline/hooks/use-DSL.ts b/web/app/components/rag-pipeline/hooks/use-DSL.tsindex f27d139ee6a..9236f8c8642 100644--- a/web/app/components/rag-pipeline/hooks/use-DSL.ts+++ b/web/app/components/rag-pipeline/hooks/use-DSL.ts@@ -1,9 +1,11 @@import type { useNodesSyncDraft } from './use-nodes-sync-draft'import type { ExportSecretEnvironmentEvent } from '@/app/components/workflow/export-secret-env-event'import { useMutation } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { DSL_EXPORT_CHECK } from '@/app/components/workflow/constants'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useWorkflowStore } from '@/app/components/workflow/store'import { toast } from '@/app/notifications'import { useEventEmitterContextContext } from '@/context/event-emitter'@@ -17,10 +19,11 @@ type DoSyncWorkflowDraft = ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDconst useDSLBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const { t } = useTranslation(['app'])const { eventEmitter } = useEventEmitterContextContext()+ const { pipelineId } = useAtomValue(knowledgePipelineIdentityAtom)const workflowStore = useWorkflowStore()const { mutateAsync: exportPipeline, isPending: isExporting } = useMutation({mutationFn: async (include: boolean) => {- const { pipelineId, knowledgeName } = workflowStore.getState()+ const { knowledgeName } = workflowStore.getState()if (!pipelineId) return falselet syncFailed = false@@ -57,7 +60,6 @@ const useDSLBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {[t, isExporting, exportPipeline],)const exportCheck = useCallback(async () => {- const { pipelineId } = workflowStore.getState()if (!pipelineId) returntry {const workflowDraft = await fetchWorkflowDraft(`/rag/pipelines/${pipelineId}/workflows/draft`)diff --git a/web/app/components/rag-pipeline/hooks/use-configs-map.ts b/web/app/components/rag-pipeline/hooks/use-configs-map.tsdeleted file mode 100644index 221a87fc79d..00000000000--- a/web/app/components/rag-pipeline/hooks/use-configs-map.ts+++ /dev/null@@ -1,24 +0,0 @@-import { useMemo } from 'react'-import { useStore } from '@/app/components/workflow/store'-import { Resolution, TransferMethod } from '@/types/app'-import { FlowType } from '@/types/common'--export const useConfigsMap = () => {- const pipelineId = useStore((s) => s.pipelineId)- const fileUploadConfig = useStore((s) => s.fileUploadConfig)- return useMemo(() => {- return {- flowId: pipelineId!,- flowType: FlowType.ragPipeline,- fileSettings: {- image: {- enabled: false,- detail: Resolution.high,- number_limits: 3,- transfer_methods: [TransferMethod.local_file, TransferMethod.remote_url],- },- fileUploadConfig,- },- }- }, [fileUploadConfig, pipelineId])-}diff --git a/web/app/components/rag-pipeline/hooks/use-file-settings.ts b/web/app/components/rag-pipeline/hooks/use-file-settings.tsnew file mode 100644index 00000000000..f3e466514aa--- /dev/null+++ b/web/app/components/rag-pipeline/hooks/use-file-settings.ts@@ -0,0 +1,18 @@+import { useMemo } from 'react'+import { useStore } from '@/app/components/workflow/store'+import { Resolution, TransferMethod } from '@/types/app'++export const useFileSettings = () => {+ const fileUploadConfig = useStore((s) => s.fileUploadConfig)+ return useMemo(() => {+ return {+ image: {+ enabled: false,+ detail: Resolution.high,+ number_limits: 3,+ transfer_methods: [TransferMethod.local_file, TransferMethod.remote_url],+ },+ fileUploadConfig,+ }+ }, [fileUploadConfig])+}diff --git a/web/app/components/rag-pipeline/hooks/use-get-run-and-trace-url.ts b/web/app/components/rag-pipeline/hooks/use-get-run-and-trace-url.tsindex 6b19ba6f399..79d2c852d87 100644--- a/web/app/components/rag-pipeline/hooks/use-get-run-and-trace-url.ts+++ b/web/app/components/rag-pipeline/hooks/use-get-run-and-trace-url.ts@@ -1,12 +1,13 @@+import { useAtomValue } from 'jotai'import { useCallback } from 'react'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useWorkflowStore } from '@/app/components/workflow/store'export const useGetRunAndTraceUrl = () => {+ const { pipelineId } = useAtomValue(knowledgePipelineIdentityAtom)const workflowStore = useWorkflowStore()const getWorkflowRunAndTraceUrl = useCallback((runId: string) => {- const { pipelineId } = workflowStore.getState()-return {runUrl: `/rag/pipelines/${pipelineId}/workflow-runs/${runId}`,traceUrl: `/rag/pipelines/${pipelineId}/workflow-runs/${runId}/node-executions`,diff --git a/web/app/components/rag-pipeline/hooks/use-inspect-vars-crud.ts b/web/app/components/rag-pipeline/hooks/use-inspect-vars-crud.tsdeleted file mode 100644index d35d84fa86e..00000000000--- a/web/app/components/rag-pipeline/hooks/use-inspect-vars-crud.ts+++ /dev/null@@ -1,13 +0,0 @@-import { useInspectVarsCrudCommon } from '@/app/components/workflow/hooks/use-inspect-vars-crud-common'-import { useConfigsMap } from './use-configs-map'--export const useInspectVarsCrud = () => {- const configsMap = useConfigsMap()- const apis = useInspectVarsCrudCommon({- ...configsMap,- })-- return {- ...apis,- }-}diff --git a/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts b/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.tsindex c1dbd11c625..decc3529631 100644--- a/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts+++ b/web/app/components/rag-pipeline/hooks/use-nodes-sync-draft.ts@@ -1,8 +1,10 @@import type { SyncDraftCallback } from '@/app/components/workflow/hooks-store'import { safe } from '@orpc/client'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useStoreApi } from 'reactflow'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useSerialAsyncCallback } from '@/app/components/workflow/hooks/use-serial-async-callback'import {useNodesReadOnly,@@ -16,6 +18,7 @@ import { usePipelineRefreshDraft } from './use-pipeline-refresh-draft'const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {const store = useStoreApi()+ const { pipelineId } = useAtomValue(knowledgePipelineIdentityAtom)const workflowStore = useWorkflowStore()const { handleRefreshWorkflowDraft } = usePipelineRefreshDraft()@@ -24,7 +27,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {const nodesOriginal = getNodes()const nodes = nodesOriginal.filter((node) => !node.data._isTempNode)const [x, y, zoom] = transform- const { pipelineId, environmentVariables, syncWorkflowDraftHash, ragPipelineVariables } =+ const { environmentVariables, syncWorkflowDraftHash, ragPipelineVariables } =workflowStore.getState()if (pipelineId && !!nodes.length) {diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-config.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-config.tsindex e15d80b6dcb..ff172f61a3f 100644--- a/web/app/components/rag-pipeline/hooks/use-pipeline-config.ts+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-config.ts@@ -1,13 +1,15 @@import type { FileUploadConfigResponse } from '@/models/common'import type { FetchWorkflowDraftResponse } from '@/types/workflow'import { useQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { useCallback, useEffect } from 'react'-import { useStore, useWorkflowStore } from '@/app/components/workflow/store'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'+import { useWorkflowStore } from '@/app/components/workflow/store'import { consoleQuery } from '@/service/console'import { useWorkflowConfig } from '@/service/use-workflow'export const usePipelineConfig = () => {- const pipelineId = useStore((s) => s.pipelineId)+ const pipelineId = useAtomValue(knowledgePipelineIdentityAtom).pipelineIdconst workflowStore = useWorkflowStore()const handleUpdateNodesDefaultConfigs = useCallback(diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-init.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-init.tsindex 6a1cf658484..f19d928c4d5 100644--- a/web/app/components/rag-pipeline/hooks/use-pipeline-init.ts+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-init.ts@@ -1,6 +1,8 @@import type { FetchWorkflowDraftResponse } from '@/types/workflow'import { ORPCError } from '@orpc/client'+import { useAtomValue } from 'jotai'import { useCallback, useEffect, useState } from 'react'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useWorkflowStore } from '@/app/components/workflow/store'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { fetchWorkflowDraft, syncWorkflowDraft } from '@/service/workflow'@@ -12,13 +14,13 @@ export const usePipelineInit = () => {const { nodes: nodesTemplate, edges: edgesTemplate } = usePipelineTemplate()const [data, setData] = useState<FetchWorkflowDraftResponse>()const [isLoading, setIsLoading] = useState(true)- const datasetId = useDatasetDetailContextWithSelector((s) => s.dataset)?.pipeline_id+ const { pipelineId } = useAtomValue(knowledgePipelineIdentityAtom)const knowledgeName = useDatasetDetailContextWithSelector((s) => s.dataset)?.nameconst knowledgeIcon = useDatasetDetailContextWithSelector((s) => s.dataset)?.icon_infouseEffect(() => {- workflowStore.setState({ pipelineId: datasetId, knowledgeName, knowledgeIcon })- }, [datasetId, workflowStore, knowledgeName, knowledgeIcon])+ workflowStore.setState({ knowledgeName, knowledgeIcon })+ }, [pipelineId, workflowStore, knowledgeName, knowledgeIcon])usePipelineConfig()@@ -32,7 +34,7 @@ export const usePipelineInit = () => {setRagPipelineVariables,} = workflowStore.getState()try {- const res = await fetchWorkflowDraft(`/rag/pipelines/${datasetId}/workflows/draft`)+ const res = await fetchWorkflowDraft(`/rag/pipelines/${pipelineId}/workflows/draft`)setData(res)setDraftUpdatedAt(res.updated_at)setToolPublished(res.tool_published)@@ -57,14 +59,14 @@ export const usePipelineInit = () => {workflowStore.setState({ isWorkflowDataLoaded: true })setIsLoading(false)} catch (error: unknown) {- if (error instanceof ORPCError && datasetId) {+ if (error instanceof ORPCError && pipelineId) {if (error.code === 'draft_workflow_not_exist') {workflowStore.setState({notInitialWorkflow: true,shouldAutoOpenStartNodeSelector: true,})syncWorkflowDraft({- url: `/rag/pipelines/${datasetId}/workflows/draft`,+ url: `/rag/pipelines/${pipelineId}/workflows/draft`,params: {graph: {nodes: nodesTemplate,@@ -80,7 +82,7 @@ export const usePipelineInit = () => {}}}- }, [nodesTemplate, edgesTemplate, workflowStore, datasetId])+ }, [nodesTemplate, edgesTemplate, workflowStore, pipelineId])useEffect(() => {handleGetInitialWorkflowData()diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.tsindex 9f9ba0062bf..58457aeb1f8 100644--- a/web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.ts+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-refresh-draft.ts@@ -1,17 +1,19 @@import type { WorkflowDataUpdater } from '@/app/components/workflow/types'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useWorkflowUpdate } from '@/app/components/workflow/hooks/use-workflow-update'import { useWorkflowStore } from '@/app/components/workflow/store'import { fetchWorkflowDraft } from '@/service/workflow'import { processNodesWithoutDataSource } from '../utils'export const usePipelineRefreshDraft = () => {+ const { pipelineId } = useAtomValue(knowledgePipelineIdentityAtom)const workflowStore = useWorkflowStore()const { handleUpdateWorkflowCanvas } = useWorkflowUpdate()const handleRefreshWorkflowDraft = useCallback(() => {const {- pipelineId,setSyncWorkflowDraftHash,setIsSyncingWorkflowDraft,setEnvironmentVariables,diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-run.tsindex e26a24f2a92..7c9214543f6 100644--- a/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts@@ -2,17 +2,21 @@ import type { useNodesSyncDraft } from './use-nodes-sync-draft'import type { IOtherOptions } from '@/service/base'import type { VersionHistory } from '@/types/workflow'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useRef } from 'react'import { useReactFlow, useStoreApi } from 'reactflow'+import {+ editorResourceAtom,+ knowledgePipelineIdentityAtom,+} from '@/app/components/workflow/editor-resource/state'import { useSetWorkflowVarsWithValue } from '@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars'import { useWorkflowRunEvent } from '@/app/components/workflow/hooks/use-workflow-run-event/use-workflow-run-event'import { useWorkflowUpdate } from '@/app/components/workflow/hooks/use-workflow-update'-import { useStore, useWorkflowStore } from '@/app/components/workflow/store'+import { useWorkflowStore } from '@/app/components/workflow/store'import { WorkflowRunningStatus } from '@/app/components/workflow/types'import { ssePost } from '@/service/base'-import { useInvalidAllLastRun, useInvalidateWorkflowRunHistory } from '@/service/use-workflow'+import { useInvalidateAllLastRun, useInvalidateWorkflowRunHistory } from '@/service/use-workflow'import { stopWorkflowRun } from '@/service/workflow'-import { FlowType } from '@/types/common'import { useNodesSyncDraftByCanEdit } from './use-nodes-sync-draft'type DoSyncWorkflowDraft = ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']@@ -74,13 +78,11 @@ const usePipelineRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {}}, [handleUpdateWorkflowCanvas, workflowStore])- const pipelineId = useStore((s) => s.pipelineId)- const invalidAllLastRun = useInvalidAllLastRun(FlowType.ragPipeline, pipelineId)+ const pipelineId = useAtomValue(knowledgePipelineIdentityAtom).pipelineId+ const resource = useAtomValue(editorResourceAtom)+ const invalidAllLastRun = useInvalidateAllLastRun(resource)const invalidateRunHistory = useInvalidateWorkflowRunHistory()- const { fetchInspectVars } = useSetWorkflowVarsWithValue({- flowType: FlowType.ragPipeline,- flowId: pipelineId!,- })+ const { fetchInspectVars } = useSetWorkflowVarsWithValue()const handleRun = useCallback(async (params: any, callback?: IOtherOptions) => {@@ -110,7 +112,7 @@ const usePipelineRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {onError,...restCallback} = callback || {}- const { pipelineId } = workflowStore.getState()+const runHistoryUrl = `/rag/pipelines/${pipelineId}/workflow-runs`workflowStore.setState({ historyWorkflowData: undefined })const workflowContainer = document.getElementById('workflow-container')@@ -259,8 +261,6 @@ const usePipelineRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const handleStopRun = useCallback((taskId: string) => {- const { pipelineId } = workflowStore.getState()-stopWorkflowRun(`/rag/pipelines/${pipelineId}/workflow-runs/tasks/${taskId}/stop`)if (abortControllerRef.current) abortControllerRef.current.abort()diff --git a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts b/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.tsindex 0815e7d8c7a..22fd574263f 100644--- a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts+++ b/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts@@ -1,7 +1,9 @@import type { MouseEventHandler } from 'react'+import { useAtomValue } from 'jotai'import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { WORKFLOW_DATA_UPDATE } from '@/app/components/workflow/constants'+import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'import { useWorkflowStore } from '@/app/components/workflow/store'import { initialEdges, initialNodes } from '@/app/components/workflow/utils'@@ -23,8 +25,9 @@ type UseUpdateDSLModalParams = {const isCompletedStatus = (status: DSLImportStatus): boolean =>status === DSLImportStatus.COMPLETED || status === DSLImportStatus.COMPLETED_WITH_WARNINGSexport const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParams) => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const { eventEmitter } = useEventEmitterContextContext()+ const { pipelineId } = useAtomValue(knowledgePipelineIdentityAtom)const workflowStore = useWorkflowStore()const { handleCheckPluginDependencies } = usePluginDependencies()const { mutateAsync: importDSL } = useImportPipelineDSL()@@ -115,7 +118,6 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam[],)const handleImport: MouseEventHandler = useCallback(async () => {- const { pipelineId } = workflowStore.getState()if (isCreatingRef.current) returnisCreatingRef.current = trueif (!currentFile) returndiff --git a/web/app/components/rag-pipeline/index.tsx b/web/app/components/rag-pipeline/index.tsxindex 8b9bc47b6be..2f4af2739a1 100644--- a/web/app/components/rag-pipeline/index.tsx+++ b/web/app/components/rag-pipeline/index.tsx@@ -2,6 +2,7 @@ import { useMemo } from 'react'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import WorkflowWithDefaultContext from '@/app/components/workflow'import { WorkflowContextProvider } from '@/app/components/workflow/context'+import { EditorResourceScope } from '@/app/components/workflow/editor-resource/provider'import { initialEdges, initialNodes } from '@/app/components/workflow/utils'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import Conversion from './components/conversion'@@ -48,9 +49,11 @@ const RagPipelineWrapper = () => {if (!pipelineId) return <Conversion />return (- <WorkflowContextProvider injectWorkflowStoreSliceFn={createRagPipelineSliceSlice}>- <RagPipeline />- </WorkflowContextProvider>+ <EditorResourceScope resource={{ kind: 'knowledge-pipeline', pipelineId }}>+ <WorkflowContextProvider injectWorkflowStoreSliceFn={createRagPipelineSliceSlice}>+ <RagPipeline />+ </WorkflowContextProvider>+ </EditorResourceScope>)}diff --git a/web/app/components/rag-pipeline/store/index.ts b/web/app/components/rag-pipeline/store/index.tsindex d24e0a6786d..2dce4fe56ee 100644--- a/web/app/components/rag-pipeline/store/index.ts+++ b/web/app/components/rag-pipeline/store/index.ts@@ -5,7 +5,6 @@ import type { IconInfo } from '@/models/datasets'import type { RAGPipelineVariables } from '@/models/pipeline'export type RagPipelineSliceShape = {- pipelineId: stringknowledgeName: stringknowledgeIcon?: IconInfoshowInputFieldPanel: boolean@@ -30,7 +29,6 @@ export const createRagPipelineSliceSlice: StateCreator<[],RagPipelineSliceShape> = (set) => ({- pipelineId: '',knowledgeName: '',showInputFieldPanel: false,setShowInputFieldPanel: (showInputFieldPanel) => set(() => ({ showInputFieldPanel })),diff --git a/web/app/components/snippets/__tests__/index.spec.tsx b/web/app/components/snippets/__tests__/index.spec.tsxindex a168799ac86..3fa561e563c 100644--- a/web/app/components/snippets/__tests__/index.spec.tsx+++ b/web/app/components/snippets/__tests__/index.spec.tsx@@ -15,13 +15,9 @@ vi.mock('../hooks/use-snippet-init', () => ({}))vi.mock('../components/snippet-main', () => ({- default: ({- hasPublishedWorkflow,- snippetId,- }: {- hasPublishedWorkflow: boolean- snippetId: string- }) => <div data-testid="snippet-main">{`${snippetId}:${String(hasPublishedWorkflow)}`}</div>,+ default: ({ hasPublishedWorkflow }: { hasPublishedWorkflow: boolean }) => (+ <div data-testid="snippet-main">{String(hasPublishedWorkflow)}</div>+ ),}))vi.mock('@/next/navigation', () => ({@@ -163,7 +159,8 @@ describe('SnippetPage', () => {render(<SnippetPage snippetId="snippet-1" />)expect(screen.getByTestId('workflow-default-context')).toBeInTheDocument()- expect(screen.getByTestId('snippet-main')).toHaveTextContent('snippet-1')+ expect(mockUseSnippetInit).toHaveBeenCalledWith('snippet-1')+ expect(screen.getByTestId('snippet-main')).toHaveTextContent('true')expect(screen.queryByRole('main')).not.toBeInTheDocument()})@@ -176,7 +173,7 @@ describe('SnippetPage', () => {expect(capturedWorkflowDefaultContextProps?.edges).toEqual(mockPublishedSnippetDetail.graph.edges,)- expect(screen.getByTestId('snippet-main')).toHaveTextContent('snippet-1:true')+ expect(screen.getByTestId('snippet-main')).toHaveTextContent('true')})it('should initialize workflow context with draft graph data when the published workflow is empty', () => {@@ -198,7 +195,7 @@ describe('SnippetPage', () => {expect(capturedWorkflowDefaultContextProps?.nodes).toEqual(mockDraftSnippetDetail.graph.nodes)expect(capturedWorkflowDefaultContextProps?.edges).toEqual(mockDraftSnippetDetail.graph.edges)- expect(screen.getByTestId('snippet-main')).toHaveTextContent('snippet-1:false')+ expect(screen.getByTestId('snippet-main')).toHaveTextContent('false')})it('should render loading fallback when orchestrate data is unavailable', () => {diff --git a/web/app/components/snippets/components/__tests__/snippet-main.spec.tsx b/web/app/components/snippets/components/__tests__/snippet-main.spec.tsxindex adba9b918d2..3ffad9db548 100644--- a/web/app/components/snippets/components/__tests__/snippet-main.spec.tsx+++ b/web/app/components/snippets/components/__tests__/snippet-main.spec.tsx@@ -83,13 +83,7 @@ vi.mock('@/service/use-snippet-workflows', () => ({}),}))-vi.mock('../../hooks/use-configs-map', () => ({- useConfigsMap: () => ({- flowId: 'snippet-1',- flowType: 'snippet',- fileSettings: {},- }),-}))+vi.mock('../../hooks/use-file-settings', () => ({ useFileSettings: () => ({ enabled: true }) }))vi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () => ({useSetWorkflowVarsWithValue: () => ({@@ -103,12 +97,12 @@ vi.mock('@/app/components/workflow/hooks/use-checklist', () => ({}),}))-vi.mock('@/app/components/workflow-app/hooks/use-available-nodes-meta-data', () => ({- useAvailableNodesMetaData: () => mockUseAvailableNodesMetaData(),+vi.mock('@/app/components/workflow/node-catalog', () => ({+ useWorkflowNodeCatalog: () => mockUseAvailableNodesMetaData(),}))-vi.mock('../../hooks/use-inspect-vars-crud', () => ({- useInspectVarsCrud: () => mockInspectVarsCrud,+vi.mock('@/app/components/workflow/hooks/use-inspect-vars-crud-common', () => ({+ useInspectVarsCrudCommon: () => mockInspectVarsCrud,}))vi.mock('../../hooks/use-nodes-sync-draft', () => ({@@ -234,7 +228,6 @@ const renderSnippetMain = ({draftPayload={payload}hasInitialDraftChanges={hasInitialDraftChanges}hasPublishedWorkflow={hasPublishedWorkflow}- snippetId="snippet-1"nodes={workflowNodes}edges={[] as WorkflowProps['edges']}viewport={{ x: 0, y: 0, zoom: 1 }}@@ -243,6 +236,7 @@ const renderSnippetMain = ({draftViewport={{ x: 0, y: 0, zoom: 1 }}/>,{+ resource: { kind: 'snippet', snippetId: 'snippet-1' },initialStoreState: {nodes: currentNodes,},diff --git a/web/app/components/snippets/components/snippet-main.tsx b/web/app/components/snippets/components/snippet-main.tsxindex 7d3495fde9c..47edfa22ad2 100644--- a/web/app/components/snippets/components/snippet-main.tsx+++ b/web/app/components/snippets/components/snippet-main.tsx@@ -9,17 +9,18 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useState } from 'reacimport { useTranslation } from 'react-i18next'import { useShallow } from 'zustand/react/shallow'import { WorkflowWithInnerContext } from '@/app/components/workflow'-import { useAvailableNodesMetaData } from '@/app/components/workflow-app/hooks/use-available-nodes-meta-data'+import { snippetIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useSetWorkflowVarsWithValue } from '@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars'+import { useInspectVarsCrudCommon as useInspectVarsCrud } from '@/app/components/workflow/hooks/use-inspect-vars-crud-common'+import { useWorkflowNodeCatalog } from '@/app/components/workflow/node-catalog'import { useStore, useWorkflowStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'import { initialEdges, initialNodes } from '@/app/components/workflow/utils'import { toast } from '@/app/notifications'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { useSnippetDraftStore } from '../draft-store'-import { useConfigsMap } from '../hooks/use-configs-map'+import { useFileSettings } from '../hooks/use-file-settings'import { useGetRunAndTraceUrl } from '../hooks/use-get-run-and-trace-url'-import { useInspectVarsCrud } from '../hooks/use-inspect-vars-crud'import { useNodesSyncDraft } from '../hooks/use-nodes-sync-draft'import { useSnippetRefreshDraft } from '../hooks/use-snippet-refresh-draft'import { useSnippetRun } from '../hooks/use-snippet-run'@@ -36,7 +37,6 @@ type SnippetMainProps = {draftPayload: SnippetDetailPayloadhasInitialDraftChanges: booleanhasPublishedWorkflow: boolean- snippetId: stringdraftNodes: WorkflowProps['nodes']draftEdges: WorkflowProps['edges']draftViewport?: WorkflowProps['viewport']@@ -113,19 +113,9 @@ const SnippetMainContent = ({)}-const SnippetMain = ({- draftPayload,- snippetId,- draftNodes,- draftEdges,- draftViewport,-}: SnippetMainProps) => {+const SnippetMain = ({ draftPayload, draftNodes, draftEdges, draftViewport }: SnippetMainProps) => {+ const { snippetId } = useAtomValue(snippetIdentityAtom)const [localDraftState, setLocalDraftState] = useState<LocalDraftState>()- const [localDraftSnippetId, setLocalDraftSnippetId] = useState(snippetId)- if (localDraftSnippetId !== snippetId) {- setLocalDraftState(undefined)- setLocalDraftSnippetId(snippetId)- }const currentCanvasNodeCount = useStore((state) => state.nodes.filter((node) => !node.data?._isTempNode).length,)@@ -147,11 +137,9 @@ const SnippetMain = ({handleRestoreFromPublishedWorkflow,handleRun,handleStopRun,- } = useSnippetRun(snippetId)- const configsMap = useConfigsMap(snippetId)- const { fetchInspectVars } = useSetWorkflowVarsWithValue({- ...configsMap,- })+ } = useSnippetRun()+ const fileSettings = useFileSettings()+ const { fetchInspectVars } = useSetWorkflowVarsWithValue()const {hasNodeInspectVars,hasSetInspectVar,@@ -167,8 +155,8 @@ const SnippetMain = ({invalidateSysVarValues,resetConversationVar,invalidateConversationVarValues,- } = useInspectVarsCrud(snippetId)- const workflowAvailableNodesMetaData = useAvailableNodesMetaData()+ } = useInspectVarsCrud()+ const workflowAvailableNodesMetaData = useWorkflowNodeCatalog()const availableNodesMetaData = useMemo(() => {const nodes = workflowAvailableNodesMetaData.nodes.filter((node) => !unsupportedSnippetBlockTypes.has(node.metaData.type),@@ -346,13 +334,13 @@ const SnippetMain = ({canImportExportDSL: canEditSnippet,canReleaseAndVersion: canEditSnippet,},- configsMap,+ fileSettings,}}, [appendNodeInspectVars,availableNodesMetaData,canEditSnippet,- configsMap,+ fileSettings,deleteAllInspectorVars,deleteInspectVar,deleteNodeInspectorVars,diff --git a/web/app/components/snippets/components/workflow-panel.tsx b/web/app/components/snippets/components/workflow-panel.tsxindex a93ee30889f..7906203a9a9 100644--- a/web/app/components/snippets/components/workflow-panel.tsx+++ b/web/app/components/snippets/components/workflow-panel.tsx@@ -36,8 +36,6 @@ const SnippetWorkflowPanel = ({ snippetId, fields }: SnippetWorkflowPanelProps)return {getVersionListUrl: `/snippets/${snippetId}/workflows`,deleteVersionUrl: (versionId: string) => `/snippets/${snippetId}/workflows/${versionId}`,- restoreVersionUrl: (versionId: string) =>- `/snippets/${snippetId}/workflows/${versionId}/restore`,updateVersionUrl: (versionId: string) => `/snippets/${snippetId}/workflows/${versionId}`,latestVersionId: '',}diff --git a/web/app/components/snippets/hooks/__tests__/use-configs-map.spec.ts b/web/app/components/snippets/hooks/__tests__/use-configs-map.spec.tsdeleted file mode 100644index 571516a4355..00000000000--- a/web/app/components/snippets/hooks/__tests__/use-configs-map.spec.ts+++ /dev/null@@ -1,51 +0,0 @@-import type { FileUploadConfigResponse } from '@/models/common'-import { renderWorkflowHook } from '@/app/components/workflow/__tests__/workflow-test-env'-import { Resolution, TransferMethod } from '@/types/app'-import { FlowType } from '@/types/common'-import { useConfigsMap } from '../use-configs-map'--describe('useConfigsMap', () => {- it('should build snippet workflow configs from the snippet id and workflow file upload config', () => {- const fileUploadConfig = {- batch_count_limit: 5,- image_file_batch_limit: 3,- file_size_limit: 15,- workflow_file_upload_limit: 10,- } as FileUploadConfigResponse-- const { result, rerender } = renderWorkflowHook(- ({ snippetId }: { snippetId: string }) => useConfigsMap(snippetId),- {- initialProps: { snippetId: 'snippet-1' },- initialStoreState: {- fileUploadConfig,- },- },- )-- expect(result.current).toEqual({- flowId: 'snippet-1',- flowType: FlowType.snippet,- fileSettings: {- image: {- enabled: false,- detail: Resolution.high,- number_limits: 3,- transfer_methods: [TransferMethod.local_file, TransferMethod.remote_url],- },- fileUploadConfig,- },- })-- const firstConfigs = result.current-- rerender({ snippetId: 'snippet-1' })-- expect(result.current).toBe(firstConfigs)-- rerender({ snippetId: 'snippet-2' })-- expect(result.current.flowId).toBe('snippet-2')- expect(result.current).not.toBe(firstConfigs)- })-})diff --git a/web/app/components/snippets/hooks/__tests__/use-file-settings.spec.ts b/web/app/components/snippets/hooks/__tests__/use-file-settings.spec.tsnew file mode 100644index 00000000000..5a5a681e058--- /dev/null+++ b/web/app/components/snippets/hooks/__tests__/use-file-settings.spec.ts@@ -0,0 +1,28 @@+import type { FileUploadConfigResponse } from '@/models/common'+import { act } from '@testing-library/react'+import { renderWorkflowHook } from '@/app/components/workflow/__tests__/workflow-test-env'+import { Resolution, TransferMethod } from '@/types/app'+import { useFileSettings } from '../use-file-settings'++describe('useFileSettings', () => {+ it('updates upload limits from the editor while keeping snippet image inputs disabled', () => {+ const fileUploadConfig = { workflow_file_upload_limit: 10 } as FileUploadConfigResponse+ const { result, store } = renderWorkflowHook(useFileSettings, {+ resource: { kind: 'snippet', snippetId: 'snippet-1' },+ initialStoreState: { fileUploadConfig },+ })+ expect(result.current).toEqual({+ image: {+ enabled: false,+ detail: Resolution.high,+ number_limits: 3,+ transfer_methods: [TransferMethod.local_file, TransferMethod.remote_url],+ },+ fileUploadConfig,+ })+ act(() =>+ store.setState({ fileUploadConfig: { ...fileUploadConfig, workflow_file_upload_limit: 20 } }),+ )+ expect(result.current.fileUploadConfig?.workflow_file_upload_limit).toBe(20)+ })+})diff --git a/web/app/components/snippets/hooks/__tests__/use-inspect-vars-crud.spec.ts b/web/app/components/snippets/hooks/__tests__/use-inspect-vars-crud.spec.tsdeleted file mode 100644index 7b19f6c9f0a..00000000000--- a/web/app/components/snippets/hooks/__tests__/use-inspect-vars-crud.spec.ts+++ /dev/null@@ -1,95 +0,0 @@-import { renderHook } from '@testing-library/react'-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'-import { useInspectVarsCrud } from '../use-inspect-vars-crud'--const mockApis = {- hasNodeInspectVars: vi.fn(),- hasSetInspectVar: vi.fn(),- fetchInspectVarValue: vi.fn(),- editInspectVarValue: vi.fn(),- renameInspectVarName: vi.fn(),- appendNodeInspectVars: vi.fn(),- deleteInspectVar: vi.fn(),- deleteNodeInspectorVars: vi.fn(),- deleteAllInspectorVars: vi.fn(),- isInspectVarEdited: vi.fn(),- resetToLastRunVar: vi.fn(),- invalidateSysVarValues: vi.fn(),- resetConversationVar: vi.fn(),- invalidateConversationVarValues: vi.fn(),-}--const mockUseInspectVarsCrudCommon = vi.fn(() => mockApis)-vi.mock('@/app/components/workflow/hooks/use-inspect-vars-crud-common', () => ({- useInspectVarsCrudCommon: (...args: Parameters<typeof mockUseInspectVarsCrudCommon>) =>- mockUseInspectVarsCrudCommon(...args),-}))--const mockConfigsMap = {- flowId: 'snippet-123',- flowType: 'snippet',- fileSettings: {- image: { enabled: false },- fileUploadConfig: {},- },-}--vi.mock('../use-configs-map', () => ({- useConfigsMap: () => mockConfigsMap,-}))--describe('useInspectVarsCrud', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- describe('Composition', () => {- it('should pass configsMap to useInspectVarsCrudCommon', () => {- renderHook(() => useInspectVarsCrud('snippet-123'))-- expect(mockUseInspectVarsCrudCommon).toHaveBeenCalledWith(- expect.objectContaining({- flowId: 'snippet-123',- flowType: 'snippet',- }),- )- })-- it('should return all APIs from useInspectVarsCrudCommon', () => {- const { result } = renderHook(() => useInspectVarsCrud('snippet-123'))-- expect(result.current.hasNodeInspectVars).toBe(mockApis.hasNodeInspectVars)- expect(result.current.fetchInspectVarValue).toBe(mockApis.fetchInspectVarValue)- expect(result.current.editInspectVarValue).toBe(mockApis.editInspectVarValue)- expect(result.current.deleteInspectVar).toBe(mockApis.deleteInspectVar)- expect(result.current.deleteAllInspectorVars).toBe(mockApis.deleteAllInspectorVars)- expect(result.current.resetToLastRunVar).toBe(mockApis.resetToLastRunVar)- expect(result.current.resetConversationVar).toBe(mockApis.resetConversationVar)- })- })-- describe('API Surface', () => {- it('should expose all expected API methods', () => {- const { result } = renderHook(() => useInspectVarsCrud('snippet-123'))-- const expectedKeys = [- 'hasNodeInspectVars',- 'hasSetInspectVar',- 'fetchInspectVarValue',- 'editInspectVarValue',- 'renameInspectVarName',- 'appendNodeInspectVars',- 'deleteInspectVar',- 'deleteNodeInspectorVars',- 'deleteAllInspectorVars',- 'isInspectVarEdited',- 'resetToLastRunVar',- 'invalidateSysVarValues',- 'resetConversationVar',- 'invalidateConversationVarValues',- ]-- for (const key of expectedKeys) expect(result.current).toHaveProperty(key)- })- })-})diff --git a/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.ts b/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.tsindex 6c0edfe37ae..e9904cb641c 100644--- a/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.ts+++ b/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.ts@@ -1,4 +1,5 @@-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { WorkflowRunningStatus } from '@/app/components/workflow/types'import { useSnippetRun } from '../use-snippet-run'@@ -104,7 +105,7 @@ vi.mock('@/service/base', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mocks.mockInvalidateAllLastRun,+ useInvalidateAllLastRun: () => mocks.mockInvalidateAllLastRun,useInvalidateWorkflowRunHistory: () => mocks.mockInvalidateRunHistory,}))@@ -139,7 +140,9 @@ describe('useSnippetRun', () => {it('stops a snippet workflow with the provided task id', () => {mocks.workflowStoreState.workflowRunningData = createRunningData()- const { result } = renderHook(() => useSnippetRun('snippet-1'))+ const { result } = renderHook(() => useSnippetRun(), {+ resource: { kind: 'snippet', snippetId: 'snippet-1' },+ })act(() => {result.current.handleStopRun('task-1')@@ -155,7 +158,9 @@ describe('useSnippetRun', () => {it('does not fall back to the workflow running task id when stop is called without one', () => {mocks.workflowStoreState.workflowRunningData = createRunningData('task-from-store')- const { result } = renderHook(() => useSnippetRun('snippet-1'))+ const { result } = renderHook(() => useSnippetRun(), {+ resource: { kind: 'snippet', snippetId: 'snippet-1' },+ })act(() => {result.current.handleStopRun('')@@ -169,7 +174,9 @@ describe('useSnippetRun', () => {it('does not call the stop endpoint when task id is unavailable', () => {mocks.workflowStoreState.workflowRunningData = createRunningData()- const { result } = renderHook(() => useSnippetRun('snippet-1'))+ const { result } = renderHook(() => useSnippetRun(), {+ resource: { kind: 'snippet', snippetId: 'snippet-1' },+ })act(() => {result.current.handleStopRun('')diff --git a/web/app/components/snippets/hooks/use-configs-map.ts b/web/app/components/snippets/hooks/use-configs-map.tsdeleted file mode 100644index 05d7bc4b589..00000000000--- a/web/app/components/snippets/hooks/use-configs-map.ts+++ /dev/null@@ -1,24 +0,0 @@-import { useMemo } from 'react'-import { useStore } from '@/app/components/workflow/store'-import { Resolution, TransferMethod } from '@/types/app'-import { FlowType } from '@/types/common'--export const useConfigsMap = (snippetId: string) => {- const fileUploadConfig = useStore((s) => s.fileUploadConfig)-- return useMemo(() => {- return {- flowId: snippetId,- flowType: FlowType.snippet,- fileSettings: {- image: {- enabled: false,- detail: Resolution.high,- number_limits: 3,- transfer_methods: [TransferMethod.local_file, TransferMethod.remote_url],- },- fileUploadConfig,- },- }- }, [fileUploadConfig, snippetId])-}diff --git a/web/app/components/snippets/hooks/use-file-settings.ts b/web/app/components/snippets/hooks/use-file-settings.tsnew file mode 100644index 00000000000..728740cb00e--- /dev/null+++ b/web/app/components/snippets/hooks/use-file-settings.ts@@ -0,0 +1,19 @@+import { useMemo } from 'react'+import { useStore } from '@/app/components/workflow/store'+import { Resolution, TransferMethod } from '@/types/app'++export const useFileSettings = () => {+ const fileUploadConfig = useStore((s) => s.fileUploadConfig)++ return useMemo(() => {+ return {+ image: {+ enabled: false,+ detail: Resolution.high,+ number_limits: 3,+ transfer_methods: [TransferMethod.local_file, TransferMethod.remote_url],+ },+ fileUploadConfig,+ }+ }, [fileUploadConfig])+}diff --git a/web/app/components/snippets/hooks/use-inspect-vars-crud.ts b/web/app/components/snippets/hooks/use-inspect-vars-crud.tsdeleted file mode 100644index 290e4761380..00000000000--- a/web/app/components/snippets/hooks/use-inspect-vars-crud.ts+++ /dev/null@@ -1,13 +0,0 @@-import { useInspectVarsCrudCommon } from '@/app/components/workflow/hooks/use-inspect-vars-crud-common'-import { useConfigsMap } from './use-configs-map'--export const useInspectVarsCrud = (snippetId: string) => {- const configsMap = useConfigsMap(snippetId)- const apis = useInspectVarsCrudCommon({- ...configsMap,- })-- return {- ...apis,- }-}diff --git a/web/app/components/snippets/hooks/use-snippet-run.ts b/web/app/components/snippets/hooks/use-snippet-run.tsindex b3fb9c18a47..19a69b7d76e 100644--- a/web/app/components/snippets/hooks/use-snippet-run.ts+++ b/web/app/components/snippets/hooks/use-snippet-run.ts@@ -2,20 +2,23 @@ import type { IOtherOptions } from '@/service/base'import type { SnippetDraftRunPayload } from '@/types/snippet'import type { VersionHistory } from '@/types/workflow'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useRef } from 'react'import { useReactFlow, useStoreApi } from 'reactflow'+import { snippetIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useSetWorkflowVarsWithValue } from '@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars'import { useWorkflowRunEvent } from '@/app/components/workflow/hooks/use-workflow-run-event/use-workflow-run-event'import { useWorkflowUpdate } from '@/app/components/workflow/hooks/use-workflow-update'import { useWorkflowStore } from '@/app/components/workflow/store'import { WorkflowRunningStatus } from '@/app/components/workflow/types'import { ssePost } from '@/service/base'-import { useInvalidAllLastRun, useInvalidateWorkflowRunHistory } from '@/service/use-workflow'+import { useInvalidateAllLastRun, useInvalidateWorkflowRunHistory } from '@/service/use-workflow'import { stopWorkflowRun } from '@/service/workflow'-import { FlowType } from '@/types/common'import { useNodesSyncDraft } from './use-nodes-sync-draft'-export const useSnippetRun = (snippetId: string) => {+export const useSnippetRun = () => {+ const resource = useAtomValue(snippetIdentityAtom)+ const { snippetId } = resourceconst store = useStoreApi()const workflowStore = useWorkflowStore()const reactflow = useReactFlow()@@ -73,12 +76,9 @@ export const useSnippetRun = (snippetId: string) => {}}, [handleUpdateWorkflowCanvas, workflowStore])- const invalidAllLastRun = useInvalidAllLastRun(FlowType.snippet, snippetId)+ const invalidAllLastRun = useInvalidateAllLastRun(resource)const invalidateRunHistory = useInvalidateWorkflowRunHistory()- const { fetchInspectVars } = useSetWorkflowVarsWithValue({- flowType: FlowType.snippet,- flowId: snippetId,- })+ const { fetchInspectVars } = useSetWorkflowVarsWithValue()const handleRun = useCallback(async (params: SnippetDraftRunPayload, callback?: IOtherOptions) => {diff --git a/web/app/components/snippets/index.tsx b/web/app/components/snippets/index.tsxindex fb4d0833b59..a9a31282e87 100644--- a/web/app/components/snippets/index.tsx+++ b/web/app/components/snippets/index.tsx@@ -1,9 +1,12 @@'use client'+import { useAtomValue } from 'jotai'import { useMemo } from 'react'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import WorkflowWithDefaultContext from '@/app/components/workflow'import { WorkflowContextProvider } from '@/app/components/workflow/context'+import { EditorResourceScope } from '@/app/components/workflow/editor-resource/provider'+import { snippetIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { initialEdges, initialNodes } from '@/app/components/workflow/utils'import SnippetLayout from './components/snippet-layout'import SnippetMain from './components/snippet-main'@@ -23,7 +26,8 @@ const SnippetPageLoading = ({ snippetId }: SnippetPageProps) => {)}-const SnippetPage = ({ snippetId }: SnippetPageProps) => {+const SnippetPage = () => {+ const { snippetId } = useAtomValue(snippetIdentityAtom)const { data, isLoading } = useSnippetInit(snippetId)const publishedNodesData = useMemo(() => {if (!data) return []@@ -58,8 +62,6 @@ const SnippetPage = ({ snippetId }: SnippetPageProps) => {<SnippetLayout snippetId={snippetId} snippet={data.snippet} section="orchestrate"><WorkflowWithDefaultContext edges={initialWorkflowEdgesData} nodes={initialWorkflowNodesData}><SnippetMain- key={snippetId}- snippetId={snippetId}payload={data.published}draftPayload={data.draft}hasInitialDraftChanges={data.hasDraftChanges}@@ -78,9 +80,11 @@ const SnippetPage = ({ snippetId }: SnippetPageProps) => {const SnippetPageWrapper = ({ snippetId }: SnippetPageProps) => {return (- <WorkflowContextProvider key={snippetId}>- <SnippetPage snippetId={snippetId} />- </WorkflowContextProvider>+ <EditorResourceScope resource={{ kind: 'snippet', snippetId }}>+ <WorkflowContextProvider>+ <SnippetPage />+ </WorkflowContextProvider>+ </EditorResourceScope>)}diff --git a/web/app/components/workflow-app/__tests__/index.spec.tsx b/web/app/components/workflow-app/__tests__/index.spec.tsxindex 7aa1cf62a96..16a851138be 100644--- a/web/app/components/workflow-app/__tests__/index.spec.tsx+++ b/web/app/components/workflow-app/__tests__/index.spec.tsx@@ -7,7 +7,6 @@ import { createQueryClientWrapper } from '@/test/console/query-client'import { seedAppDetail } from '@/test/console/query-data'import { render as renderWithConsoleState } from '@/test/console/render'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import WorkflowApp from '../index'@@ -229,7 +228,7 @@ describe('WorkflowApp', () => {mockIsWorkflowDataLoaded = trueappDetail = createAppDetailFixture({id: 'app-1',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.TestAndRun],})workflowInitState = {@@ -359,7 +358,7 @@ describe('WorkflowApp', () => {searchParamsValue = 'run-1'appDetail = createAppDetailFixture({id: 'app-1',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.ViewLayout],})diff --git a/web/app/components/workflow-app/__tests__/provider-contract.spec.tsx b/web/app/components/workflow-app/__tests__/provider-contract.spec.tsxindex 41b4e233c08..71b3be6ec12 100644--- a/web/app/components/workflow-app/__tests__/provider-contract.spec.tsx+++ b/web/app/components/workflow-app/__tests__/provider-contract.spec.tsx@@ -6,7 +6,6 @@ import { createQueryClientWrapper } from '@/test/console/query-client'import { seedAppDetail } from '@/test/console/query-data'import { render as renderWithConsoleState } from '@/test/console/render'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import WorkflowApp from '../index'const render = (ui: ReactElement) => {@@ -16,7 +15,7 @@ const render = (ui: ReactElement) => {createAppDetailFixture({id: 'app-1',name: 'Workflow App',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [],}),)@@ -66,11 +65,11 @@ vi.mock('../hooks/use-workflow-init', async () => {return {useWorkflowInit: () => {- useStore((state) => state.appId)+ useStore((state) => state.syncWorkflowDraftHash)const workflowStore = useWorkflowStore()React.useEffect(() => {- workflowStore.setState({ appId: 'initialized-app' })+ workflowStore.setState({ syncWorkflowDraftHash: 'initialized-draft' })}, [workflowStore])return {@@ -115,7 +114,7 @@ vi.mock('../components/workflow-main', async () => {await import('@/app/components/workflow/workflow-history-store')const WorkflowMainProbe = () => {- const appId = useStore((state) => state.appId)+ const appId = useStore((state) => state.syncWorkflowDraftHash)const hasWorkflowSlice = useStore((state) => typeof state.setNotInitialWorkflow === 'function')const { store } = useWorkflowHistoryStore()@@ -139,6 +138,8 @@ describe('WorkflowApp provider contract', () => {</StrictMode>,)- expect(await screen.findByText('app:initialized-app history:1 slice:true')).toBeInTheDocument()+ expect(+ await screen.findByText('app:initialized-draft history:1 slice:true'),+ ).toBeInTheDocument()})})diff --git a/web/app/components/workflow-app/components/__tests__/workflow-children.spec.tsx b/web/app/components/workflow-app/components/__tests__/workflow-children.spec.tsxindex 64003955eae..4e81561637d 100644--- a/web/app/components/workflow-app/components/__tests__/workflow-children.spec.tsx+++ b/web/app/components/workflow-app/components/__tests__/workflow-children.spec.tsx@@ -1,7 +1,8 @@-import { act, render, screen } from '@testing-library/react'+import { act, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'import { DSL_EXPORT_CHECK } from '@/app/components/workflow/constants'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum } from '@/app/components/workflow/types'import WorkflowChildren from '../workflow-children'@@ -135,8 +136,8 @@ vi.mock('@/app/components/workflow/utils', async (importOriginal) => {}})-vi.mock('../../hooks/use-available-nodes-meta-data', () => ({- useAvailableNodesMetaData: () => ({+vi.mock('@/app/components/workflow/node-catalog', () => ({+ useWorkflowNodeCatalog: () => ({nodesMap: {[BlockEnum.Start]: {defaultValue: {@@ -160,9 +161,12 @@ vi.mock('../../hooks/use-available-nodes-meta-data', () => ({}),}))-vi.mock('../../hooks/use-is-chat-mode', () => ({- useIsChatMode: () => false,-}))+vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})vi.mock('../../hooks/use-auto-onboarding', () => ({useAutoOnboarding: () => ({@@ -366,7 +370,7 @@ describe('WorkflowChildren', () => {showImportDSLModal: true,}- render(<WorkflowChildren />)+ render(<WorkflowChildren />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })expect(screen.getByTestId('plugin-dependency')).toBeInTheDocument()expect(screen.getByTestId('workflow-header')).toBeInTheDocument()@@ -386,7 +390,7 @@ describe('WorkflowChildren', () => {it('should react to DSL export check events by showing the confirm modal and closing it', async () => {const user = userEvent.setup()- render(<WorkflowChildren />)+ render(<WorkflowChildren />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })await act(async () => {eventSubscription?.({@@ -410,7 +414,7 @@ describe('WorkflowChildren', () => {})it('should ignore unrelated workflow events when listening for DSL export checks', async () => {- render(<WorkflowChildren />)+ render(<WorkflowChildren />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })await act(async () => {eventSubscription?.({@@ -431,7 +435,7 @@ describe('WorkflowChildren', () => {showOnboarding: true,}- render(<WorkflowChildren />)+ render(<WorkflowChildren />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })expect(await screen.findByTestId('workflow-onboarding-modal')).toBeInTheDocument()@@ -447,7 +451,7 @@ describe('WorkflowChildren', () => {showOnboarding: true,}- render(<WorkflowChildren />)+ render(<WorkflowChildren />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })expect(screen.queryByTestId('workflow-onboarding-modal')).not.toBeInTheDocument()expect(mockSetNodes).not.toHaveBeenCalled()@@ -461,7 +465,7 @@ describe('WorkflowChildren', () => {showOnboarding: true,}- render(<WorkflowChildren />)+ render(<WorkflowChildren />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })await user.click(await screen.findByRole('button', { name: /^select-start-node$/i }))@@ -490,7 +494,7 @@ describe('WorkflowChildren', () => {showOnboarding: true,}- render(<WorkflowChildren />)+ render(<WorkflowChildren />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })await user.click(await screen.findByRole('button', { name: /select-start-node-with-config/i }))@@ -514,7 +518,7 @@ describe('WorkflowChildren', () => {showOnboarding: true,}- render(<WorkflowChildren />)+ render(<WorkflowChildren />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })await user.click(await screen.findByRole('button', { name: /^select-trigger-plugin$/i }))@@ -550,7 +554,7 @@ describe('WorkflowChildren', () => {showOnboarding: true,}- render(<WorkflowChildren />)+ render(<WorkflowChildren />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })await user.click(await screen.findByRole('button', { name: /select-trigger-plugin-fallback/i }))diff --git a/web/app/components/workflow-app/components/__tests__/workflow-main.spec.tsx b/web/app/components/workflow-app/components/__tests__/workflow-main.spec.tsxindex 66bec7abc3f..74d8af69306 100644--- a/web/app/components/workflow-app/components/__tests__/workflow-main.spec.tsx+++ b/web/app/components/workflow-app/components/__tests__/workflow-main.spec.tsx@@ -1,20 +1,14 @@import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'import type { ReactElement, ReactNode } from 'react'import type { WorkflowProps } from '@/app/components/workflow'-import {- act,- fireEvent,- render as renderWithQueryClient,- screen,- waitFor,-} from '@testing-library/react'+import { act, fireEvent, screen, waitFor } from '@testing-library/react'+import { renderEditor as renderWithQueryClient } from '@/app/components/workflow/editor-resource/__tests__/render'import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'import { BlockEnum } from '@/app/components/workflow/types'import { createAccountProfileQueryClient } from '@/test/console/account-profile'import { createQueryClientWrapper } from '@/test/console/query-client'import { seedAppDetail } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import WorkflowMain from '../workflow-main'@@ -23,7 +17,10 @@ let appDetail: AppDetailWithSiteconst render = (ui: ReactElement) => {const queryClient = createAccountProfileQueryClient()seedAppDetail(queryClient, appDetail)- return renderWithQueryClient(ui, { wrapper: createQueryClientWrapper(queryClient) })+ return renderWithQueryClient(ui, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper: createQueryClientWrapper(queryClient),+ })}vi.mock('@/next/navigation', async (importOriginal) => ({@@ -129,6 +126,8 @@ vi.mock('@/context/workspace-state', async () => {})vi.mock('@/app/components/base/features/hooks', () => ({+ useFeatures: (selector: (state: { features: { file: { enabled: boolean } } }) => unknown) =>+ selector({ features: { file: { enabled: true } } }),useFeaturesStore: () => ({getState: () => ({setFeatures: mockSetFeatures,@@ -302,17 +301,13 @@ vi.mock('@/app/components/workflow', () => ({},}))-vi.mock('../../hooks/use-available-nodes-meta-data', () => ({- useAvailableNodesMetaData: () => ({+vi.mock('@/app/components/workflow/node-catalog', () => ({+ useWorkflowNodeCatalog: () => ({nodes: [{ id: 'start' }],nodesMap: { start: { id: 'start' } },}),}))-vi.mock('../../hooks/use-configs-map', () => ({- useConfigsMap: () => ({ flowId: 'app-1', flowType: 'app-flow', fileSettings: { enabled: true } }),-}))-vi.mock('../../hooks/use-DSL', () => ({useDSL: () => ({ exportCheck: hookFns.exportCheck, handleExportDSL: hookFns.handleExportDSL }),useDSLByCanEdit: () => ({@@ -325,8 +320,8 @@ vi.mock('../../hooks/use-get-run-and-trace-url', () => ({useGetRunAndTraceUrl: () => ({ getWorkflowRunAndTraceUrl: hookFns.getWorkflowRunAndTraceUrl }),}))-vi.mock('../../hooks/use-inspect-vars-crud', () => ({- useInspectVarsCrud: () => ({+vi.mock('@/app/components/workflow/hooks/use-inspect-vars-crud-common', () => ({+ useInspectVarsCrudCommon: () => ({hasNodeInspectVars: hookFns.hasNodeInspectVars,hasSetInspectVar: hookFns.hasSetInspectVar,fetchInspectVarValue: hookFns.fetchInspectVarValue,@@ -472,7 +467,7 @@ describe('WorkflowMain', () => {mockReplaceGraphFromReactFlow.mockReturnValue(true)hookFns.doSyncWorkflowDraft.mockResolvedValue({ hash: 'saved-hash', updatedAt: 2 })hookFns.handleRefreshWorkflowDraft.mockResolvedValue(true)- appDetail = createAppDetailFixture({ id: 'app-1', mode: AppModeEnum.WORKFLOW })+ appDetail = createAppDetailFixture({ id: 'app-1', mode: 'workflow' as const })})it('should render the inner workflow context with children and forwarded graph props', () => {@@ -567,7 +562,7 @@ describe('WorkflowMain', () => {exportCheck: hookFns.exportCheck,handleExportDSL: hookFns.handleExportDSL,fetchInspectVars: hookFns.fetchInspectVars,- configsMap: { flowId: 'app-1', flowType: 'app-flow', fileSettings: { enabled: true } },+ fileSettings: { enabled: true },})})@@ -616,7 +611,7 @@ describe('WorkflowMain', () => {it('disables collaboration for view-only apps', () => {appDetail = createAppDetailFixture({id: 'app-1',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.ViewLayout],})diff --git a/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx b/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsxindex aafaa97550c..565f9c08be3 100644--- a/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx+++ b/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx@@ -6,7 +6,6 @@ import * as React from 'react'import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'import { createConsoleQueryWrapper, seedAppDetail } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import WorkflowPanel from '../workflow-panel'type WorkflowStoreState = Partial<Shape>@@ -26,11 +25,15 @@ const renderPanel = (initialStoreState: WorkflowStoreState) => {queryClient,createAppDetailFixture({id: 'app-123',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,workflow: { id: 'workflow-version-id' },}),)- return renderWorkflowComponent(<WorkflowPanel />, { initialStoreState, queryClient })+ return renderWorkflowComponent(<WorkflowPanel />, {+ initialStoreState,+ queryClient,+ resource: { kind: 'app', appId: 'app-123', mode: 'workflow' },+ })}vi.mock('@/app/components/workflow/panel', () => ({@@ -45,20 +48,16 @@ vi.mock('@/app/components/workflow/panel', () => ({versionHistoryPanelProps?: {getVersionListUrl: stringdeleteVersionUrl: (versionId: string) => string- restoreVersionUrl: (versionId: string) => stringupdateVersionUrl: (versionId: string) => stringlatestVersionId?: string- appMode?: AppModeEnum}}) => (<divdata-testid="panel"data-version-list-url={versionHistoryPanelProps?.getVersionListUrl ?? ''}data-delete-version-url={versionHistoryPanelProps?.deleteVersionUrl('version-1') ?? ''}- data-restore-version-url={versionHistoryPanelProps?.restoreVersionUrl('version-1') ?? ''}data-update-version-url={versionHistoryPanelProps?.updateVersionUrl('version-1') ?? ''}data-latest-version-id={versionHistoryPanelProps?.latestVersionId ?? ''}- data-app-mode={versionHistoryPanelProps?.appMode ?? ''}><div data-testid="panel-left">{components?.left}</div><div data-testid="panel-right">{components?.right}</div>@@ -108,9 +107,12 @@ vi.mock('@/app/components/workflow/panel/global-variable-panel', () => ({default: () => <div data-testid="global-variable-panel">global-variable</div>,}))-vi.mock('../../hooks/use-is-chat-mode', () => ({- useIsChatMode: () => mockUseIsChatMode(),-}))+vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})describe('WorkflowPanel', () => {beforeEach(() => {@@ -130,13 +132,8 @@ describe('WorkflowPanel', () => {const panel = await screen.findByTestId('panel')expect(panel).toHaveAttribute('data-version-list-url', '/apps/app-123/workflows')expect(panel).toHaveAttribute('data-delete-version-url', '/apps/app-123/workflows/version-1')- expect(panel).toHaveAttribute(- 'data-restore-version-url',- '/apps/app-123/workflows/version-1/restore',- )expect(panel).toHaveAttribute('data-update-version-url', '/apps/app-123/workflows/version-1')expect(panel).toHaveAttribute('data-latest-version-id', 'workflow-version-id')- expect(panel).toHaveAttribute('data-app-mode', AppModeEnum.WORKFLOW)})it('should close the selected log and reopen on the default detail tab', async () => {diff --git a/web/app/components/workflow-app/components/workflow-children.tsx b/web/app/components/workflow-app/components/workflow-children.tsxindex cb2bf2786b7..2b5f9b390e4 100644--- a/web/app/components/workflow-app/components/workflow-children.tsx+++ b/web/app/components/workflow-app/components/workflow-children.tsx@@ -3,24 +3,28 @@ import type {TriggerDefaultValue,} from '@/app/components/workflow/block-selector/types'import type { ExportSecretEnvironmentVariable } from '@/app/components/workflow/export-secret-env-event'+import { useAtomValue } from 'jotai'import dynamic from 'next/dynamic'import { memo, useCallback, useState } from 'react'import { useStoreApi } from 'reactflow'import { START_INITIAL_POSITION } from '@/app/components/workflow/constants'+import {+ isChatflowAtom,+ workflowAppIdentityAtom,+} from '@/app/components/workflow/editor-resource/state'import { isExportSecretEnvironmentEvent } from '@/app/components/workflow/export-secret-env-event'import { useHooksStore } from '@/app/components/workflow/hooks-store'import { useAutoGenerateWebhookUrl } from '@/app/components/workflow/hooks/use-auto-generate-webhook-url'import { useDSL } from '@/app/components/workflow/hooks/use-DSL'import { useNodesSyncDraft } from '@/app/components/workflow/hooks/use-nodes-sync-draft'import { usePanelInteractions } from '@/app/components/workflow/hooks/use-panel-interactions'+import { useWorkflowNodeCatalog } from '@/app/components/workflow/node-catalog'import PluginDependency from '@/app/components/workflow/plugin-dependency'import { useStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'import { generateNewNode } from '@/app/components/workflow/utils'import { useEventEmitterContextContext } from '@/context/event-emitter'import { useAutoOnboarding } from '../hooks/use-auto-onboarding'-import { useAvailableNodesMetaData } from '../hooks/use-available-nodes-meta-data'-import { useIsChatMode } from '../hooks/use-is-chat-mode'import WorkflowHeader from './workflow-header'import WorkflowPanel from './workflow-panel'@@ -63,8 +67,8 @@ const getTriggerPluginNodeData = (}const WorkflowChildren = () => {- const appId = useStore((s) => s.appId)- const isChatMode = useIsChatMode()+ const appId = useAtomValue(workflowAppIdentityAtom).appId+ const isChatflow = useAtomValue(isChatflowAtom)const { eventEmitter } = useEventEmitterContextContext()const [secretEnvList, setSecretEnvList] = useState<ExportSecretEnvironmentVariable[]>([])const showFeaturesPanel = useStore((s) => s.showFeaturesPanel)@@ -77,7 +81,7 @@ const WorkflowChildren = () => {const setHasSelectedStartNode = useStore((s) => s.setHasSelectedStartNode)const setShouldAutoOpenStartNodeSelector = useStore((s) => s.setShouldAutoOpenStartNodeSelector)const reactFlowStore = useStoreApi()- const availableNodesMetaData = useAvailableNodesMetaData()+ const availableNodesMetaData = useWorkflowNodeCatalog()const { handleSyncWorkflowDraft } = useNodesSyncDraft()const { handleOnboardingClose } = useAutoOnboarding()const { handlePaneContextmenuCancel } = usePanelInteractions()@@ -176,7 +180,7 @@ const WorkflowChildren = () => {{appId && canImportExportDSL && showImportDSLModal && (<UpdateDSLModalappId={appId}- appMode={isChatMode ? 'advanced-chat' : 'workflow'}+ appMode={isChatflow ? 'advanced-chat' : 'workflow'}onCancel={() => setShowImportDSLModal(false)}onBackup={exportCheck!}onImport={handlePaneContextmenuCancel}diff --git a/web/app/components/workflow-app/components/workflow-header/__tests__/chat-variable-trigger.spec.tsx b/web/app/components/workflow-app/components/workflow-header/__tests__/chat-variable-trigger.spec.tsxindex 343a6d26314..23ea3891639 100644--- a/web/app/components/workflow-app/components/workflow-header/__tests__/chat-variable-trigger.spec.tsx+++ b/web/app/components/workflow-app/components/workflow-header/__tests__/chat-variable-trigger.spec.tsx@@ -1,4 +1,5 @@-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import ChatVariableTrigger from '../chat-variable-trigger'const mockUseNodesReadOnly = vi.fn()@@ -8,9 +9,12 @@ vi.mock('@/app/components/workflow/hooks/use-workflow', () => ({useNodesReadOnly: () => mockUseNodesReadOnly(),}))-vi.mock('../../../hooks/use-is-chat-mode', () => ({- useIsChatMode: () => mockUseIsChatMode(),-}))+vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})vi.mock('@/app/components/workflow/header/chat-variable-button', () => ({default: ({ disabled }: { disabled: boolean }) => (@@ -33,7 +37,9 @@ describe('ChatVariableTrigger', () => {mockUseNodesReadOnly.mockReturnValue({ nodesReadOnly: false })// Act- render(<ChatVariableTrigger />)+ render(<ChatVariableTrigger />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })// Assertexpect(screen.queryByRole('button', { name: 'ChatVariableButton' })).not.toBeInTheDocument()@@ -48,7 +54,9 @@ describe('ChatVariableTrigger', () => {mockUseNodesReadOnly.mockReturnValue({ nodesReadOnly: false })// Act- render(<ChatVariableTrigger />)+ render(<ChatVariableTrigger />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })// Assertexpect(screen.getByRole('button', { name: 'ChatVariableButton' })).toBeEnabled()@@ -60,7 +68,9 @@ describe('ChatVariableTrigger', () => {mockUseNodesReadOnly.mockReturnValue({ nodesReadOnly: true })// Act- render(<ChatVariableTrigger />)+ render(<ChatVariableTrigger />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })// Assertexpect(screen.getByRole('button', { name: 'ChatVariableButton' })).toBeDisabled()diff --git a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsxindex 0879fed0d1e..3e8be595d84 100644--- a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx+++ b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx@@ -2,8 +2,9 @@ import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen'import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'import type { ReactElement } from 'react'import type { AppPublisherProps } from '@/app/components/app/app-publisher/types'-import { render, screen, waitFor } from '@testing-library/react'+import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum, InputVarType } from '@/app/components/workflow/types'import { consoleQuery } from '@/service/console'import { createConsoleQueryWrapper, seedFeatures } from '@/test/console/query-data'@@ -73,7 +74,6 @@ const mockWorkflowStore = {vi.mock('@/app/components/workflow/hooks/use-workflow', () => ({useNodesReadOnly: () => mockUseNodesReadOnly(),- useIsChatMode: () => mockUseIsChatMode(),}))vi.mock('@/app/components/workflow/hooks/use-checklist', () => ({@@ -244,7 +244,17 @@ const renderWithToast = (})seedFeatures(queryClient, { billing: { subscription: { plan } } })vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries)- return { queryClient, ...render(ui, { wrapper }) }+ return {+ ...render(ui, {+ resource: {+ kind: 'app',+ appId: 'app-id',+ mode: mockUseIsChatMode() ? 'advanced-chat' : 'workflow',+ },+ wrapper,+ queryClient,+ }),+ }}describe('FeaturesTrigger', () => {diff --git a/web/app/components/workflow-app/components/workflow-header/chat-variable-trigger.tsx b/web/app/components/workflow-app/components/workflow-header/chat-variable-trigger.tsxindex e2709e2074e..b669705f993 100644--- a/web/app/components/workflow-app/components/workflow-header/chat-variable-trigger.tsx+++ b/web/app/components/workflow-app/components/workflow-header/chat-variable-trigger.tsx@@ -1,13 +1,14 @@+import { useAtomValue } from 'jotai'import { memo } from 'react'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import ChatVariableButton from '@/app/components/workflow/header/chat-variable-button'import { useNodesReadOnly } from '@/app/components/workflow/hooks/use-workflow'-import { useIsChatMode } from '../../hooks/use-is-chat-mode'const ChatVariableTrigger = () => {const { nodesReadOnly } = useNodesReadOnly()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)- if (!isChatMode) return null+ if (!isChatflow) return nullreturn <ChatVariableButton disabled={nodesReadOnly} />}diff --git a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsxindex 5c0c0b9c605..5e768640139 100644--- a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx+++ b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx@@ -9,11 +9,16 @@ import type { CommonEdgeType, Node } from '@/app/components/workflow/types'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { memo, useCallback, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { useEdges } from 'reactflow'import { AppPublisher } from '@/app/components/app/app-publisher'import { useFeatures } from '@/app/components/base/features/hooks'+import {+ isChatflowAtom,+ workflowAppIdentityAtom,+} from '@/app/components/workflow/editor-resource/state'// useWorkflowRunValidation,import { useHooksStore } from '@/app/components/workflow/hooks-store'import {@@ -21,7 +26,7 @@ import {useChecklistBeforePublish,} from '@/app/components/workflow/hooks/use-checklist'import { useNodesSyncDraft } from '@/app/components/workflow/hooks/use-nodes-sync-draft'-import { useIsChatMode, useNodesReadOnly } from '@/app/components/workflow/hooks/use-workflow'+import { useNodesReadOnly } from '@/app/components/workflow/hooks/use-workflow'import { isAgentV2NodeData } from '@/app/components/workflow/nodes/agent-v2/types'import { useStore, useWorkflowStore } from '@/app/components/workflow/store'import useNodes from '@/app/components/workflow/store/workflow/use-nodes'@@ -29,7 +34,6 @@ import { BlockEnum, InputVarType, isTriggerNode } from '@/app/components/workfloimport { toast } from '@/app/notifications'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import useTheme from '@/hooks/use-theme'-import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { useInvalidateAppTriggers } from '@/service/use-tools'import {@@ -41,10 +45,10 @@ import {const FeaturesTrigger = () => {const { t } = useTranslation(['common', 'workflow'])const { theme } = useTheme()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const workflowStore = useWorkflowStore()const queryClient = useQueryClient()- const { appId: appID } = useParams<{ appId: string }>()+ const { appId: appID } = useAtomValue(workflowAppIdentityAtom)const { nodesReadOnly, getNodesReadOnly } = useNodesReadOnly()const canReleaseAndVersion = useHooksStore((s) => s.accessControl.canReleaseAndVersion)const { data: deploymentEdition } = useSuspenseQuery({@@ -253,7 +257,7 @@ const FeaturesTrigger = () => {return (<>{/* Feature button is only visible in chatflow mode (advanced-chat) */}- {isChatMode && (+ {isChatflow && (<ButtonclassName={cn('rounded-lg text-components-button-secondary-text inset-ring-1 inset-ring-transparent',diff --git a/web/app/components/workflow-app/components/workflow-header/index.tsx b/web/app/components/workflow-app/components/workflow-header/index.tsxindex 47d30131847..67989fd776d 100644--- a/web/app/components/workflow-app/components/workflow-header/index.tsx+++ b/web/app/components/workflow-app/components/workflow-header/index.tsx@@ -1,18 +1,21 @@import type { HeaderProps } from '@/app/components/workflow/header'+import { useAtomValue } from 'jotai'import { memo, useCallback, useMemo } from 'react'+import {+ isChatflowAtom,+ workflowAppIdentityAtom,+} from '@/app/components/workflow/editor-resource/state'import Header from '@/app/components/workflow/header'import { useStore } from '@/app/components/workflow/store'-import { useParams } from '@/next/navigation'import { useResetWorkflowVersionHistory } from '@/service/use-workflow'-import { useIsChatMode } from '../../hooks/use-is-chat-mode'import ChatVariableTrigger from './chat-variable-trigger'import FeaturesTrigger from './features-trigger'const WorkflowHeader = () => {- const { appId } = useParams<{ appId: string }>()+ const { appId } = useAtomValue(workflowAppIdentityAtom)const setMessageLogItem = useStore((state) => state.setMessageLogItem)const resetWorkflowVersionHistory = useResetWorkflowVersionHistory()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const handleClearLogAndMessageModal = useCallback(() => {setMessageLogItem(undefined)@@ -21,11 +24,11 @@ const WorkflowHeader = () => {const viewHistoryProps = useMemo(() => {return {onClearLogAndMessageModal: handleClearLogAndMessageModal,- historyUrl: isChatMode+ historyUrl: isChatflow? `/apps/${appId}/advanced-chat/workflow-runs`: `/apps/${appId}/workflow-runs`,}- }, [appId, isChatMode, handleClearLogAndMessageModal])+ }, [appId, isChatflow, handleClearLogAndMessageModal])const headerProps: HeaderProps = useMemo(() => {return {@@ -35,8 +38,8 @@ const WorkflowHeader = () => {chatVariableTrigger: <ChatVariableTrigger />,},runAndHistoryProps: {- showRunButton: !isChatMode,- showPreviewButton: isChatMode,+ showRunButton: !isChatflow,+ showPreviewButton: isChatflow,viewHistoryProps,},},@@ -47,7 +50,7 @@ const WorkflowHeader = () => {onRestoreSettled: resetWorkflowVersionHistory,},}- }, [resetWorkflowVersionHistory, isChatMode, viewHistoryProps])+ }, [resetWorkflowVersionHistory, isChatflow, viewHistoryProps])return <Header {...headerProps} />}diff --git a/web/app/components/workflow-app/components/workflow-main.tsx b/web/app/components/workflow-app/components/workflow-main.tsxindex 50072878210..72c479e7fe7 100644--- a/web/app/components/workflow-app/components/workflow-main.tsx+++ b/web/app/components/workflow-app/components/workflow-main.tsx@@ -9,26 +9,25 @@ import { useAtomValue } from 'jotai'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { useReactFlow } from 'reactflow'-import { useFeaturesStore } from '@/app/components/base/features/hooks'+import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'import { WorkflowWithInnerContext } from '@/app/components/workflow'import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'import { useCollaboration } from '@/app/components/workflow/collaboration/hooks/use-collaboration'+import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useSetWorkflowVarsWithValue } from '@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars'+import { useInspectVarsCrudCommon as useInspectVarsCrud } from '@/app/components/workflow/hooks/use-inspect-vars-crud-common'import { useWorkflowUpdate } from '@/app/components/workflow/hooks/use-workflow-update'-import { useStore, useWorkflowStore } from '@/app/components/workflow/store'+import { useWorkflowNodeCatalog } from '@/app/components/workflow/node-catalog'+import { useWorkflowStore } from '@/app/components/workflow/store'import { SupportUploadFileTypes } from '@/app/components/workflow/types'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'-import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { fetchWorkflowDraft } from '@/service/workflow'import { getAppACLCapabilities } from '@/utils/permission'-import { useAvailableNodesMetaData } from '../hooks/use-available-nodes-meta-data'-import { useConfigsMap } from '../hooks/use-configs-map'import { useDSLByCanEdit } from '../hooks/use-DSL'import { useGetRunAndTraceUrl } from '../hooks/use-get-run-and-trace-url'-import { useInspectVarsCrud } from '../hooks/use-inspect-vars-crud'import { useNodesSyncDraftByCanEdit } from '../hooks/use-nodes-sync-draft'import { useWorkflowDraftGraphForCanvas } from '../hooks/use-workflow-draft-graph-for-canvas'import { useWorkflowRefreshDraft } from '../hooks/use-workflow-refresh-draft'@@ -51,13 +50,12 @@ const GRAPH_RELOAD_RETRY_BASE_DELAY = 1000const GRAPH_RELOAD_RETRY_MAX_DELAY = 30_000const WorkflowMain = ({ nodes, edges, viewport }: WorkflowMainProps) => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const featuresStore = useFeaturesStore()const workflowStore = useWorkflowStore()- const appId = useStore((s) => s.appId)- const { appId: routeAppId } = useParams<{ appId: string }>()+ const { appId } = useAtomValue(workflowAppIdentityAtom)const { data: appDetail } = useSuspenseQuery(- consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: routeAppId } } }),+ consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),)const containerRef = useRef<HTMLDivElement>(null)const [collaborationGraphState, setCollaborationGraphState] = useState({@@ -419,15 +417,13 @@ const WorkflowMain = ({ nodes, edges, viewport }: WorkflowMainProps) => {handleWorkflowTriggerPluginRunInWorkflow,handleWorkflowRunAllTriggersInWorkflow,} = useWorkflowStartRunByCanEdit(appACLCapabilities.canEdit)- const availableNodesMetaData = useAvailableNodesMetaData()+ const availableNodesMetaData = useWorkflowNodeCatalog()const { getWorkflowRunAndTraceUrl } = useGetRunAndTraceUrl()const { exportCheck, handleExportDSL, isExporting } = useDSLByCanEdit(appACLCapabilities.canEdit)- const configsMap = useConfigsMap()+ const fileSettings = useFeatures((state) => state.features.file)- const { fetchInspectVars } = useSetWorkflowVarsWithValue({- ...configsMap,- })+ const { fetchInspectVars } = useSetWorkflowVarsWithValue()const {hasNodeInspectVars,hasSetInspectVar,@@ -488,7 +484,7 @@ const WorkflowMain = ({ nodes, edges, viewport }: WorkflowMainProps) => {canImportExportDSL: appACLCapabilities.canImportExportDSL,canReleaseAndVersion: appACLCapabilities.canReleaseAndVersion,},- configsMap,+ fileSettings,}}, [syncWorkflowDraftWhenPageClose,@@ -527,7 +523,7 @@ const WorkflowMain = ({ nodes, edges, viewport }: WorkflowMainProps) => {resetConversationVar,invalidateConversationVarValues,appACLCapabilities,- configsMap,+ fileSettings,])return (diff --git a/web/app/components/workflow-app/components/workflow-panel.tsx b/web/app/components/workflow-app/components/workflow-panel.tsxindex bd4adefbbc8..590d6a12edb 100644--- a/web/app/components/workflow-app/components/workflow-panel.tsx+++ b/web/app/components/workflow-app/components/workflow-panel.tsx@@ -1,13 +1,16 @@import type { PanelProps } from '@/app/components/workflow/panel'import { useSuspenseQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import dynamic from 'next/dynamic'import { memo, useMemo } from 'react'+import {+ isChatflowAtom,+ workflowAppIdentityAtom,+} from '@/app/components/workflow/editor-resource/state'import Panel from '@/app/components/workflow/panel'import CommentsPanel from '@/app/components/workflow/panel/comments-panel'import { useStore } from '@/app/components/workflow/store'-import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'-import { useIsChatMode } from '../hooks/use-is-chat-mode'const MessageLogModal = dynamic(() => import('@/app/components/base/message-log-modal'), {ssr: false,@@ -55,7 +58,7 @@ const WorkflowPanelOnLeft = ({ appId }: { appId: string }) => {)}const WorkflowPanelOnRight = () => {- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const historyWorkflowData = useStore((s) => s.historyWorkflowData)const showDebugAndPreviewPanel = useStore((s) => s.showDebugAndPreviewPanel)const showChatVariablePanel = useStore((s) => s.showChatVariablePanel)@@ -64,31 +67,29 @@ const WorkflowPanelOnRight = () => {return (<>- {historyWorkflowData && !isChatMode && <Record />}- {historyWorkflowData && isChatMode && <ChatRecord />}- {showDebugAndPreviewPanel && isChatMode && <DebugAndPreview />}- {showDebugAndPreviewPanel && !isChatMode && <WorkflowPreview />}- {showChatVariablePanel && isChatMode && <ChatVariablePanel />}+ {historyWorkflowData && !isChatflow && <Record />}+ {historyWorkflowData && isChatflow && <ChatRecord />}+ {showDebugAndPreviewPanel && isChatflow && <DebugAndPreview />}+ {showDebugAndPreviewPanel && !isChatflow && <WorkflowPreview />}+ {showChatVariablePanel && isChatflow && <ChatVariablePanel />}{showGlobalVariablePanel && <GlobalVariablePanel />}{controlMode === 'comment' && <CommentsPanel />}</>)}const WorkflowPanel = () => {- const { appId } = useParams<{ appId: string }>()+ const { appId } = useAtomValue(workflowAppIdentityAtom)const { data: appDetail } = useSuspenseQuery(consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),)const versionHistoryPanelProps = useMemo(() => {return {- appMode: appDetail.mode,getVersionListUrl: `/apps/${appId}/workflows`,deleteVersionUrl: (versionId: string) => `/apps/${appId}/workflows/${versionId}`,- restoreVersionUrl: (versionId: string) => `/apps/${appId}/workflows/${versionId}/restore`,updateVersionUrl: (versionId: string) => `/apps/${appId}/workflows/${versionId}`,latestVersionId: appDetail.workflow?.id,}- }, [appId, appDetail.mode, appDetail.workflow?.id])+ }, [appId, appDetail.workflow?.id])const panelProps: PanelProps = useMemo(() => {return {diff --git a/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.tsindex 157f1c488c6..2ab099dad65 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-DSL.spec.ts@@ -1,8 +1,9 @@import type { ReactNode } from 'react'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { act, renderHook, waitFor } from '@testing-library/react'+import { act, waitFor } from '@testing-library/react'import { createElement } from 'react'import { DSL_EXPORT_CHECK } from '@/app/components/workflow/constants'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { consoleQuery } from '@/service/console'import { httpErrorFromResponse } from '@/service/http-error'import { createAppDetailFixture } from '@/test/fixtures/app'@@ -129,7 +130,10 @@ describe('useDSLByCanEdit', () => {})it('exports with the latest name from the detail query', async () => {- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper,+ })const beforeRename = result.currentact(() => {queryClient.setQueryData(@@ -152,7 +156,10 @@ describe('useDSLByCanEdit', () => {callback.onError()return null})- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper,+ })await act(async () => {expect(await result.current.handleExportDSL()).toBe(false)})@@ -164,7 +171,10 @@ describe('useDSLByCanEdit', () => {it('allows export when draft synchronization is skipped for read-only access', async () => {mockDoSyncWorkflowDraft.mockResolvedValue(null)- const { result } = renderHook(() => useDSLByCanEdit(false), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(false), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper,+ })await act(async () => {expect(await result.current.handleExportDSL()).toBe(true)})@@ -174,7 +184,10 @@ describe('useDSLByCanEdit', () => {it('downloads the default package bytes and forwards the selected workflow version', async () => {const file = new File([new Uint8Array([0x50, 0x4b, 0xff])], 'workflow.ifpkg')mockExportAppConfig.mockResolvedValue(file)- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper,+ })await act(async () => {expect(await result.current.handleExportDSL(true, 'revision-1')).toBe(true)})@@ -190,7 +203,10 @@ describe('useDSLByCanEdit', () => {})it('should export workflow dsl and download the yaml blob when no secret env is present', async () => {- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper,+ })await act(async () => {await result.current.exportCheck()@@ -232,7 +248,10 @@ workflow:package_ref: agent_1`mockExportAppConfig.mockResolvedValue({ data: agentDSL })- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper,+ })await act(async () => {await result.current.handleExportDSL()@@ -246,7 +265,10 @@ workflow:})it('should forward include and workflow id arguments when exporting dsl directly', async () => {- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper,+ })await act(async () => {await result.current.handleExportDSL(true, 'workflow-1')@@ -265,7 +287,10 @@ workflow:const secretVars = [{ id: 'env-1', value_type: 'secret', value: 'secret-token' }]mockFetchEnvironmentVariables.mockResolvedValue({ items: secretVars })- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper,+ })await act(async () => {await result.current.exportCheck()@@ -280,22 +305,6 @@ workflow:expect(mockExportAppConfig).not.toHaveBeenCalled()})- it('should return early when app detail is unavailable', async () => {- appQueryFixture = {}-- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })-- await act(async () => {- await result.current.exportCheck()- await result.current.handleExportDSL()- })-- expect(mockFetchEnvironmentVariables).not.toHaveBeenCalled()- expect(mockDoSyncWorkflowDraft).not.toHaveBeenCalled()- expect(mockExportAppConfig).not.toHaveBeenCalled()- expect(mockEmit).not.toHaveBeenCalled()- })-it('should notify when export fails', async () => {mockExportAppConfig.mockRejectedValue(await httpErrorFromResponse(@@ -305,7 +314,10 @@ workflow:),)- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper,+ })await act(async () => {expect(await result.current.handleExportDSL()).toBe(false)@@ -323,7 +335,10 @@ workflow:it('should notify when exportCheck cannot load the workflow draft', async () => {mockFetchEnvironmentVariables.mockRejectedValue(new Error('draft fetch failed'))- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper,+ })await act(async () => {await result.current.exportCheck()@@ -345,7 +360,10 @@ workflow:mockDoSyncWorkflowDraft.mockReturnValue(sync.promise)mockExportAppConfig.mockReturnValue(deferred.promise)- const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const { result } = renderHook(() => useDSLByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper,+ })let firstExportPromise!: Promise<boolean>act(() => {diff --git a/web/app/components/workflow-app/hooks/__tests__/use-configs-map.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-configs-map.spec.tsdeleted file mode 100644index 3613475b7b0..00000000000--- a/web/app/components/workflow-app/hooks/__tests__/use-configs-map.spec.ts+++ /dev/null@@ -1,44 +0,0 @@-import { renderHook } from '@testing-library/react'-import { FlowType } from '@/types/common'-import { useConfigsMap } from '../use-configs-map'--const mockUseFeatures = vi.fn()--vi.mock('@/app/components/base/features/hooks', () => ({- useFeatures: (selector: (state: { features: { file: Record<string, unknown> } }) => unknown) =>- mockUseFeatures(selector),-}))--vi.mock('@/app/components/workflow/store', () => ({- useStore: <T>(selector: (state: { appId: string }) => T) => selector({ appId: 'app-1' }),-}))--describe('useConfigsMap', () => {- beforeEach(() => {- vi.clearAllMocks()- mockUseFeatures.mockImplementation(- (selector: (state: { features: { file: Record<string, unknown> } }) => unknown) =>- selector({- features: {- file: {- enabled: true,- number_limits: 3,- },- },- }),- )- })-- it('should map workflow app id and feature file settings into inspect-var configs', () => {- const { result } = renderHook(() => useConfigsMap())-- expect(result.current).toEqual({- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {- enabled: true,- number_limits: 3,- },- })- })-})diff --git a/web/app/components/workflow-app/hooks/__tests__/use-get-run-and-trace-url.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-get-run-and-trace-url.spec.tsindex 196ad8c915b..100b8bd9c4f 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-get-run-and-trace-url.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-get-run-and-trace-url.spec.ts@@ -1,4 +1,4 @@-import { renderHook } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { useGetRunAndTraceUrl } from '../use-get-run-and-trace-url'const mockWorkflowStore = {@@ -18,7 +18,9 @@ describe('useGetRunAndTraceUrl', () => {})it('should build workflow run and trace urls from the current app id', () => {- const { result } = renderHook(() => useGetRunAndTraceUrl())+ const { result } = renderHook(() => useGetRunAndTraceUrl(), {+ resource: { kind: 'app', appId: 'app-123', mode: 'workflow' },+ })expect(result.current.getWorkflowRunAndTraceUrl('run-1')).toEqual({runUrl: '/apps/app-123/workflow-runs/run-1',diff --git a/web/app/components/workflow-app/hooks/__tests__/use-is-chat-mode.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-is-chat-mode.spec.tsdeleted file mode 100644index 1c2abe40ff9..00000000000--- a/web/app/components/workflow-app/hooks/__tests__/use-is-chat-mode.spec.ts+++ /dev/null@@ -1,33 +0,0 @@-import {- createConsoleQueryClient,- renderHookWithConsoleQuery,- seedAppDetail,-} from '@/test/console/query-data'-import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'-import { useIsChatMode } from '../use-is-chat-mode'--vi.mock('@/next/navigation', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/next/navigation')>()),- useParams: () => ({ appId: 'app-1' }),-}))--const renderWithAppMode = (mode: AppModeEnum) => {- const queryClient = createConsoleQueryClient()- seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode }))- return renderHookWithConsoleQuery(() => useIsChatMode(), { queryClient })-}--describe('useIsChatMode', () => {- it('should return true when the app mode is ADVANCED_CHAT', () => {- const { result } = renderWithAppMode(AppModeEnum.ADVANCED_CHAT)-- expect(result.current).toBe(true)- })-- it('should return false when the app mode is WORKFLOW', () => {- const { result } = renderWithAppMode(AppModeEnum.WORKFLOW)-- expect(result.current).toBe(false)- })-})diff --git a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.tsindex 1cd9bd37d6b..bc9606d1124 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts@@ -1,15 +1,16 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { WorkflowSliceShape } from '@/app/components/workflow/store/workflow/workflow-slice'import type { EnvironmentVariablePatch } from '@/service/workflow'import { noop } from '@tanstack/react-query'import { act } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditorHook as renderHookWithConsoleQuery } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum } from '@/app/components/workflow/types'import { markAppDeletionFailed, markAppDeletionStarted } from '@/service/app-deletion'import { consoleQuery } from '@/service/console'import { createHttpError } from '@/service/http-error'-import { createConsoleQueryClient, renderHookWithConsoleQuery } from '@/test/console/query-data'+import { createConsoleQueryClient } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { useNodesSyncDraft } from '../use-nodes-sync-draft'const mockGetNodes = vi.fn()@@ -25,7 +26,7 @@ const mockCollaborationCanFlushGraphOnPageClose = vi.fn()const mockCollaborationCanUseLocalDraftFallback = vi.fn()const mockSetShowConfirm = vi.fn<(confirmation: WorkflowSliceShape['showConfirm']) => void>()let isCollaborationEnabled = false-let appMode: AppModeEnum | undefined+let appMode: AppMode | undefinedlet reactFlowState: {getNodes: typeof mockGetNodes@@ -200,7 +201,7 @@ describe('useNodesSyncDraft', () => {updatedAt: 2,})isCollaborationEnabled = false- appMode = AppModeEnum.WORKFLOW+ appMode = 'workflow'})it.each(['draft sync', 'page close'] as const)(@@ -260,7 +261,7 @@ describe('useNodesSyncDraft', () => {},)- it.each([AppModeEnum.ADVANCED_CHAT, undefined])(+ it.each(['advanced-chat'] as const)('should preserve LLM memory when app mode is %s',async (mode) => {appMode = mode@@ -544,24 +545,6 @@ describe('useNodesSyncDraft', () => {expect(callbacks.onSettled).toHaveBeenCalledOnce()})- it('should not apply empty-canvas consent to another app', async () => {- mockGetNodes.mockReturnValue([])- const { result } = renderUseNodesSyncDraft()- let syncPromise!: ReturnType<typeof result.current.doSyncWorkflowDraft>-- act(() => {- syncPromise = result.current.doSyncWorkflowDraft()- })-- workflowStoreState.appId = 'app-2'- await act(async () => {- workflowStoreState.showConfirm?.onConfirm()- await expect(syncPromise).resolves.toBeNull()- })-- expect(mockSyncWorkflowDraft).not.toHaveBeenCalled()- })-it('should cancel a pending empty save when its owning hook unmounts', async () => {mockGetNodes.mockReturnValue([])const callbacks = { onError: vi.fn(), onSettled: vi.fn() }diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-draft-graph-for-canvas.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-draft-graph-for-canvas.spec.tsindex 3d5c8a4cf97..59db726cbe5 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-draft-graph-for-canvas.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-draft-graph-for-canvas.spec.ts@@ -1,7 +1,6 @@import type { Node } from '@/app/components/workflow/types'import { renderHook } from '@testing-library/react'import { BlockEnum } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import { useWorkflowDraftGraphForCanvas } from '../use-workflow-draft-graph-for-canvas'let generateNewNodeCalls: Array<Record<string, unknown>> = []@@ -34,7 +33,7 @@ describe('useWorkflowDraftGraphForCanvas', () => {})it('should restore a local start placeholder for workflow graphs without an entry node', () => {- const { result } = renderHook(() => useWorkflowDraftGraphForCanvas(AppModeEnum.WORKFLOW))+ const { result } = renderHook(() => useWorkflowDraftGraphForCanvas('workflow'))const graph = result.current.getWorkflowDraftGraphForCanvas({nodes: [],@@ -64,7 +63,7 @@ describe('useWorkflowDraftGraphForCanvas', () => {BlockEnum.StartPlaceholder,])('should preserve existing %s entry nodes', (type) => {const node = { id: 'entry', data: { type } }- const { result } = renderHook(() => useWorkflowDraftGraphForCanvas(AppModeEnum.WORKFLOW))+ const { result } = renderHook(() => useWorkflowDraftGraphForCanvas('workflow'))const graph = result.current.getWorkflowDraftGraphForCanvas({nodes: [node] as never,@@ -76,7 +75,7 @@ describe('useWorkflowDraftGraphForCanvas', () => {})it('should not restore a start placeholder for non-workflow app modes', () => {- const { result } = renderHook(() => useWorkflowDraftGraphForCanvas(AppModeEnum.ADVANCED_CHAT))+ const { result } = renderHook(() => useWorkflowDraftGraphForCanvas('advanced-chat'))const graph = result.current.getWorkflowDraftGraphForCanvas({nodes: [],@@ -93,7 +92,7 @@ describe('useWorkflowDraftGraphForCanvas', () => {data: { type: BlockEnum.StartPlaceholder },}const draftNode = { id: 'llm', data: { type: BlockEnum.LLM } }- const { result } = renderHook(() => useWorkflowDraftGraphForCanvas(AppModeEnum.WORKFLOW))+ const { result } = renderHook(() => useWorkflowDraftGraphForCanvas('workflow'))const graph = result.current.getWorkflowDraftGraphForCanvas({@@ -141,7 +140,7 @@ describe('useWorkflowDraftGraphForCanvas', () => {},]const originalNodes = structuredClone(nodes)- const { result } = renderHook(() => useWorkflowDraftGraphForCanvas(AppModeEnum.WORKFLOW))+ const { result } = renderHook(() => useWorkflowDraftGraphForCanvas('workflow'))const graph = result.current.getWorkflowDraftGraphForCanvas({ nodes, edges: [] })@@ -159,7 +158,7 @@ describe('useWorkflowDraftGraphForCanvas', () => {expect(nodes).toEqual(originalNodes)})- it.each([AppModeEnum.ADVANCED_CHAT, undefined])(+ it.each(['advanced-chat', undefined] as const)('preserves memory when app mode is %s',(appMode) => {const nodes: Node<{ memory: { window: { enabled: boolean; size: number } } }>[] = [diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.tsindex 399e5c4b02e..6d2c21c170e 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts@@ -1,12 +1,12 @@import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'import { waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditorHook as renderHookWithConsoleState } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum } from '@/app/components/workflow/types'import { createHttpError } from '@/service/http-error'import { createAccountProfileQueryClient } from '@/test/console/account-profile'import { createQueryClientWrapper } from '@/test/console/query-client'import { seedAppDetail } from '@/test/console/query-data'-import { renderHook as renderHookWithConsoleState } from '@/test/console/render'import { createAppDetailFixture } from '@/test/fixtures/app'import { AppACLPermission } from '@/utils/permission'import { useWorkflowInit } from '../use-workflow-init'@@ -29,6 +29,7 @@ const renderHook = <Result>(callback: () => Result) => {const queryClient = createAccountProfileQueryClient({ id: 'user-1' })seedAppDetail(queryClient, appDetail)return renderHookWithConsoleState(callback, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },wrapper: createQueryClientWrapper(queryClient),})}@@ -346,7 +347,6 @@ describe('useWorkflowInit', () => {expect(result.current.data?.hash).toBe('server-hash')})- expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({ appId: 'app-1', appName: 'Test' })expect(mockWorkflowStoreSetState).toHaveBeenCalledWith(expect.objectContaining({envSecrets: { 'env-secret': 'top-secret' },diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-refresh-draft.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-refresh-draft.spec.tsindex ff8b4c48ef9..288c4926406 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-refresh-draft.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-refresh-draft.spec.ts@@ -1,13 +1,10 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import { act, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { renderEditorHook as renderHookWithConsoleQuery } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum } from '@/app/components/workflow/types'-import {- createConsoleQueryClient,- renderHookWithConsoleQuery,- seedAppDetail,-} from '@/test/console/query-data'+import { createConsoleQueryClient, seedAppDetail } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { useWorkflowRefreshDraft } from '../use-workflow-refresh-draft'const mockHandleUpdateWorkflowCanvas = vi.fn()@@ -18,7 +15,7 @@ const mockSetEnvSecrets = vi.fn()const mockSetConversationVariables = vi.fn()const mockSetIsWorkflowDataLoaded = vi.fn()const mockCancel = vi.fn()-let appMode: AppModeEnum+let appMode: AppModelet workflowStoreState: {appId: string@@ -79,7 +76,7 @@ describe('useWorkflowRefreshDraft — notUpdateCanvas parameter', () => {setConversationVariables: mockSetConversationVariables,setIsWorkflowDataLoaded: mockSetIsWorkflowDataLoaded,}- appMode = AppModeEnum.ADVANCED_CHAT+ appMode = 'advanced-chat'mockFetchWorkflowDraft.mockResolvedValue(draftResponse)})@@ -236,7 +233,7 @@ describe('useWorkflowRefreshDraft — notUpdateCanvas parameter', () => {})it('should restore a local start placeholder for workflow drafts without an entry node', async () => {- appMode = AppModeEnum.WORKFLOW+ appMode = 'workflow'mockFetchWorkflowDraft.mockResolvedValue({hash: 'server-hash',graph: {diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-run-utils.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-run-utils.spec.tsindex b88fea15858..66d852f7d9b 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-run-utils.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-run-utils.spec.ts@@ -1,7 +1,6 @@import { TriggerType } from '@/app/components/workflow/header/test-run-menu'import { WorkflowRunningStatus } from '@/app/components/workflow/types'import { httpErrorFromResponse } from '@/service/http-error'-import { AppModeEnum } from '@/types/app'import {applyRunningStateForMode,applyStoppedState,@@ -54,36 +53,32 @@ describe('useWorkflowRun utils', () => {})it('should resolve run history urls and run endpoints for workflow modes', () => {- expect(buildRunHistoryUrl({ id: 'app-1', mode: AppModeEnum.WORKFLOW })).toBe(+ expect(buildRunHistoryUrl({ id: 'app-1', mode: 'workflow' as const })).toBe('/apps/app-1/workflow-runs',)- expect(buildRunHistoryUrl({ id: 'app-1', mode: AppModeEnum.ADVANCED_CHAT })).toBe(+ expect(buildRunHistoryUrl({ id: 'app-1', mode: 'advanced-chat' as const })).toBe('/apps/app-1/advanced-chat/workflow-runs',)expect(resolveWorkflowRunUrl(- { id: 'app-1', mode: AppModeEnum.WORKFLOW },+ { id: 'app-1', mode: 'workflow' as const },TriggerType.UserInput,true,),).toBe('/apps/app-1/workflows/draft/run')expect(resolveWorkflowRunUrl(- { id: 'app-1', mode: AppModeEnum.ADVANCED_CHAT },+ { id: 'app-1', mode: 'advanced-chat' as const },TriggerType.UserInput,false,),).toBe('/apps/app-1/advanced-chat/workflows/draft/run')expect(- resolveWorkflowRunUrl(- { id: 'app-1', mode: AppModeEnum.WORKFLOW },- TriggerType.Schedule,- true,- ),+ resolveWorkflowRunUrl({ id: 'app-1', mode: 'workflow' as const }, TriggerType.Schedule, true),).toBe('/apps/app-1/workflows/draft/trigger/run')expect(- resolveWorkflowRunUrl({ id: 'app-1', mode: AppModeEnum.WORKFLOW }, TriggerType.All, true),+ resolveWorkflowRunUrl({ id: 'app-1', mode: 'workflow' as const }, TriggerType.All, true),).toBe('/apps/app-1/workflows/draft/trigger/run-all')})@@ -124,7 +119,7 @@ describe('useWorkflowRun utils', () => {expect(resolveWorkflowRunUrl(undefined, TriggerType.All, true)).toBe('')expect(resolveWorkflowRunUrl(- { id: 'app-1', mode: AppModeEnum.WORKFLOW },+ { id: 'app-1', mode: 'workflow' as const },TriggerType.UserInput,false,),diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.tsindex 3c57c38fc69..82c3adf8f16 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.ts@@ -1,11 +1,8 @@import { act } from '@testing-library/react'+import { renderEditorHook as renderHookWithConsoleQuery } from '@/app/components/workflow/editor-resource/__tests__/render'import { TriggerType } from '@/app/components/workflow/header/test-run-menu'import { WorkflowRunningStatus } from '@/app/components/workflow/types'-import {- createConsoleQueryClient,- renderHookWithConsoleQuery,- seedAppDetail,-} from '@/test/console/query-data'+import { createConsoleQueryClient, seedAppDetail } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'import { useWorkflowRun } from '../use-workflow-run'@@ -173,7 +170,7 @@ vi.mock('@/service/base', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mocks.mockInvalidateAllLastRun,+ useInvalidateAllLastRun: () => mocks.mockInvalidateAllLastRun,useInvalidateWorkflowRunHistory: () => mocks.mockInvalidateRunHistory,useInvalidateConversationVarValues: () => vi.fn(),useInvalidateSysVarValues: () => vi.fn(),@@ -189,13 +186,6 @@ vi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () =>}),}))-vi.mock('../use-configs-map', () => ({- useConfigsMap: () => ({- flowId: 'flow-1',- flowType: 'workflow',- }),-}))-vi.mock('../use-nodes-sync-draft', () => ({useNodesSyncDraft: () => ({doSyncWorkflowDraft: mocks.mockDoSyncWorkflowDraft,@@ -456,7 +446,7 @@ describe('useWorkflowRun', () => {)expect(mocks.mockTrackEvent).toHaveBeenCalledWith('workflow_run_failed', {- workflow_id: 'flow-1',+ workflow_id: 'app-1',reason: 'failed',node_type: 'llm',data: {@@ -470,7 +460,7 @@ describe('useWorkflowRun', () => {baseCallbackFactoryContext.trackWorkflowRunFailed('Server Error', workflowData)expect(mocks.mockTrackEvent).toHaveBeenCalledWith('workflow_run_failed', {- workflow_id: 'flow-1',+ workflow_id: 'app-1',reason: 'Server Error',node_type: undefined,data: {@@ -515,7 +505,7 @@ describe('useWorkflowRun', () => {if (!chunks) throw new Error('Expected workflow data chunks to be tracked')expect(mocks.mockTrackEvent).toHaveBeenCalledWith('workflow_run_failed', {- workflow_id: 'flow-1',+ workflow_id: 'app-1',reason: 'failed',node_type: 'llm',data: {@@ -546,7 +536,7 @@ describe('useWorkflowRun', () => {baseCallbackFactoryContext.trackWorkflowRunFailed(new Error('network down'), undefined)expect(mocks.mockTrackEvent).toHaveBeenCalledWith('workflow_run_failed', {- workflow_id: 'flow-1',+ workflow_id: 'app-1',reason: 'network down',node_type: undefined,data: {@@ -568,7 +558,7 @@ describe('useWorkflowRun', () => {)expect(mocks.mockTrackEvent).toHaveBeenCalledWith('workflow_run_failed', {- workflow_id: 'flow-1',+ workflow_id: 'app-1',reason: undefined,node_type: undefined,data: {diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-start-run.spec.tsx b/web/app/components/workflow-app/hooks/__tests__/use-workflow-start-run.spec.tsxindex 30339007207..49004059bf1 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-start-run.spec.tsx+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-start-run.spec.tsx@@ -1,4 +1,5 @@-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { TriggerType } from '@/app/components/workflow/header/test-run-menu'import { BlockEnum, WorkflowRunningStatus } from '@/app/components/workflow/types'import { useWorkflowStartRunByCanEdit } from '../use-workflow-start-run'@@ -50,7 +51,7 @@ vi.mock('@/app/components/workflow/store', () => ({}))vi.mock('@/app/components/workflow/hooks/use-workflow', () => ({- useIsChatMode: () => mockUseIsChatMode(),+ useIsChatflow: () => mockUseIsChatMode(),}))vi.mock('../use-nodes-sync-draft', () => ({@@ -102,7 +103,9 @@ describe('useWorkflowStartRunByCanEdit', () => {})it('should run the workflow immediately when there are no start variables and no image upload input', async () => {- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleWorkflowStartRunInWorkflow()@@ -121,7 +124,9 @@ describe('useWorkflowStartRunByCanEdit', () => {{ id: 'start-placeholder', data: { type: BlockEnum.StartPlaceholder } },])- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleWorkflowStartRunInWorkflow()@@ -138,7 +143,9 @@ describe('useWorkflowStartRunByCanEdit', () => {{ id: 'inset-s-1', data: { type: BlockEnum.Start, variables: [{ name: 'query' }] } },])- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleWorkflowStartRunInWorkflow()@@ -161,7 +168,9 @@ describe('useWorkflowStartRunByCanEdit', () => {},})- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleWorkflowStartRunInWorkflow()@@ -178,7 +187,9 @@ describe('useWorkflowStartRunByCanEdit', () => {showDebugAndPreviewPanel: true,})- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleWorkflowStartRunInWorkflow()@@ -198,7 +209,9 @@ describe('useWorkflowStartRunByCanEdit', () => {},})- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleWorkflowStartRunInWorkflow()@@ -212,7 +225,9 @@ describe('useWorkflowStartRunByCanEdit', () => {it('should configure schedule trigger runs and execute the workflow with schedule options', async () => {mockGetNodes.mockReturnValue([{ id: 'schedule-1', data: { type: BlockEnum.TriggerSchedule } }])- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleWorkflowTriggerScheduleRunInWorkflow('schedule-1')@@ -239,7 +254,9 @@ describe('useWorkflowStartRunByCanEdit', () => {})mockGetNodes.mockReturnValue([{ id: 'schedule-1', data: { type: BlockEnum.TriggerSchedule } }])- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleWorkflowTriggerScheduleRunInWorkflow('schedule-1')@@ -267,7 +284,9 @@ describe('useWorkflowStartRunByCanEdit', () => {hook.handleWorkflowTriggerPluginRunInWorkflow(''),},])('should ignore $title trigger execution when the node id is empty', async ({ invoke }) => {- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await invoke(result.current)@@ -302,7 +321,9 @@ describe('useWorkflowStartRunByCanEdit', () => {const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})mockGetNodes.mockReturnValue([{ id: 'other-node', data: { type: BlockEnum.Start } }])- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await invoke(result.current)@@ -340,7 +361,9 @@ describe('useWorkflowStartRunByCanEdit', () => {async ({ nodeId, nodeType, invoke, expectedParams, expectedOptions }) => {mockGetNodes.mockReturnValue([{ id: nodeId, data: { type: nodeType } }])- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await invoke(result.current)@@ -360,7 +383,9 @@ describe('useWorkflowStartRunByCanEdit', () => {)it('should run all triggers and mark the listener state as global', async () => {- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleWorkflowRunAllTriggersInWorkflow(['trigger-1', 'trigger-2'])@@ -385,7 +410,9 @@ describe('useWorkflowStartRunByCanEdit', () => {})it('should ignore run-all requests when there are no trigger nodes', async () => {- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleWorkflowRunAllTriggersInWorkflow([])@@ -399,7 +426,9 @@ describe('useWorkflowStartRunByCanEdit', () => {it('should route handleStartWorkflowRun to the chatflow path when chat mode is enabled', async () => {mockUseIsChatMode.mockReturnValue(true)- const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true))+ const { result } = renderHook(() => useWorkflowStartRunByCanEdit(true), {+ resource: { kind: 'app', appId: 'app-1', mode: 'advanced-chat' },+ })await act(async () => {result.current.handleStartWorkflowRun()diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-template.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-template.spec.tsindex 4f1317c8707..1f14a1c1be6 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-template.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-template.spec.ts@@ -1,24 +1,24 @@-import {- createConsoleQueryClient,- renderHookWithConsoleQuery,- seedAppDetail,-} from '@/test/console/query-data'+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'+import { renderEditorHook as renderHookWithConsoleQuery } from '@/app/components/workflow/editor-resource/__tests__/render'+import { createConsoleQueryClient, seedAppDetail } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import { useWorkflowTemplate } from '../use-workflow-template'const mockUseIsChatMode = vi.fn()let generateNewNodeCalls: Array<Record<string, unknown>> = []-const renderTemplateHook = (mode: AppModeEnum) => {+const renderTemplateHook = (mode: AppMode) => {const queryClient = createConsoleQueryClient()seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode }))return renderHookWithConsoleQuery(() => useWorkflowTemplate(), { queryClient })}-vi.mock('../use-is-chat-mode', () => ({- useIsChatMode: () => mockUseIsChatMode(),-}))+vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})vi.mock('@/next/navigation', async (importOriginal) => ({...(await importOriginal<typeof import('@/next/navigation')>()),@@ -55,7 +55,7 @@ describe('useWorkflowTemplate', () => {it('should return only the start placeholder template in workflow mode', () => {mockUseIsChatMode.mockReturnValue(false)- const { result } = renderTemplateHook(AppModeEnum.WORKFLOW)+ const { result } = renderTemplateHook('workflow')expect(result.current.nodes).toHaveLength(1)expect(result.current.edges).toEqual([])@@ -71,7 +71,7 @@ describe('useWorkflowTemplate', () => {it('should return the start node template for non-workflow app modes', () => {mockUseIsChatMode.mockReturnValue(false)- const { result } = renderTemplateHook(AppModeEnum.COMPLETION)+ const { result } = renderTemplateHook('completion')expect(result.current.nodes).toHaveLength(1)expect(result.current.edges).toEqual([])@@ -85,7 +85,7 @@ describe('useWorkflowTemplate', () => {it('should build start, llm, and answer templates with linked edges in chat mode', () => {mockUseIsChatMode.mockReturnValue(true)- const { result } = renderTemplateHook(AppModeEnum.ADVANCED_CHAT)+ const { result } = renderTemplateHook('advanced-chat')expect(result.current.nodes).toHaveLength(3)expect(result.current.nodes.map((node) => node.id)).toEqual(['generated-1', 'llm', 'answer'])diff --git a/web/app/components/workflow-app/hooks/use-DSL.ts b/web/app/components/workflow-app/hooks/use-DSL.tsindex 9f3fe7c2e0e..269e19bf5e9 100644--- a/web/app/components/workflow-app/hooks/use-DSL.ts+++ b/web/app/components/workflow-app/hooks/use-DSL.ts@@ -1,13 +1,14 @@import type { useNodesSyncDraft } from './use-nodes-sync-draft'import type { ExportSecretEnvironmentEvent } from '@/app/components/workflow/export-secret-env-event'import { useMutation, useQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { exportAppDslFile } from '@/app/components/app/use-export-app-dsl'import { DSL_EXPORT_CHECK } from '@/app/components/workflow/constants'+import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { toast } from '@/app/notifications'import { useEventEmitterContextContext } from '@/context/event-emitter'-import { useParams } from '@/next/navigation'import { consoleClient, consoleQuery } from '@/service/console'import { getErrorMessage } from '@/utils/error-message'import { useNodesSyncDraftByCanEdit } from './use-nodes-sync-draft'@@ -18,7 +19,7 @@ const useDSLBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const { t } = useTranslation(['app'])const { eventEmitter } = useEventEmitterContextContext()- const { appId } = useParams<{ appId: string }>()+ const { appId } = useAtomValue(workflowAppIdentityAtom)const { data: appDetail } = useQuery(consoleQuery.apps.byAppId.get.queryOptions({input: { params: { app_id: appId } },diff --git a/web/app/components/workflow-app/hooks/use-configs-map.ts b/web/app/components/workflow-app/hooks/use-configs-map.tsdeleted file mode 100644index cd6c5adfe80..00000000000--- a/web/app/components/workflow-app/hooks/use-configs-map.ts+++ /dev/null@@ -1,16 +0,0 @@-import { useMemo } from 'react'-import { useFeatures } from '@/app/components/base/features/hooks'-import { useStore } from '@/app/components/workflow/store'-import { FlowType } from '@/types/common'--export const useConfigsMap = () => {- const appId = useStore((s) => s.appId)- const fileSettings = useFeatures((s) => s.features.file)- return useMemo(() => {- return {- flowId: appId!,- flowType: FlowType.appFlow,- fileSettings,- }- }, [appId])-}diff --git a/web/app/components/workflow-app/hooks/use-get-run-and-trace-url.ts b/web/app/components/workflow-app/hooks/use-get-run-and-trace-url.tsindex 17e19f6f419..8077c137a17 100644--- a/web/app/components/workflow-app/hooks/use-get-run-and-trace-url.ts+++ b/web/app/components/workflow-app/hooks/use-get-run-and-trace-url.ts@@ -1,18 +1,19 @@+import { useAtomValue } from 'jotai'import { useCallback } from 'react'-import { useWorkflowStore } from '@/app/components/workflow/store'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'export const useGetRunAndTraceUrl = () => {- const workflowStore = useWorkflowStore()+ const resource = useAtomValue(editorResourceAtom)+ if (resource.kind !== 'app') throw new Error('App run URLs require an app editor')+ const { appId } = resourceconst getWorkflowRunAndTraceUrl = useCallback((runId: string) => {- const { appId } = workflowStore.getState()-return {runUrl: `/apps/${appId}/workflow-runs/${runId}`,traceUrl: `/apps/${appId}/workflow-runs/${runId}/node-executions`,}},- [workflowStore],+ [appId],)return {diff --git a/web/app/components/workflow-app/hooks/use-inspect-vars-crud.ts b/web/app/components/workflow-app/hooks/use-inspect-vars-crud.tsdeleted file mode 100644index d35d84fa86e..00000000000--- a/web/app/components/workflow-app/hooks/use-inspect-vars-crud.ts+++ /dev/null@@ -1,13 +0,0 @@-import { useInspectVarsCrudCommon } from '@/app/components/workflow/hooks/use-inspect-vars-crud-common'-import { useConfigsMap } from './use-configs-map'--export const useInspectVarsCrud = () => {- const configsMap = useConfigsMap()- const apis = useInspectVarsCrudCommon({- ...configsMap,- })-- return {- ...apis,- }-}diff --git a/web/app/components/workflow-app/hooks/use-is-chat-mode.ts b/web/app/components/workflow-app/hooks/use-is-chat-mode.tsdeleted file mode 100644index d8283b3da0f..00000000000--- a/web/app/components/workflow-app/hooks/use-is-chat-mode.ts+++ /dev/null@@ -1,16 +0,0 @@-import { skipToken, useQuery } from '@tanstack/react-query'-import { useParams } from '@/next/navigation'-import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'--export const useIsChatMode = () => {- const { appId } = useParams<{ appId?: string }>()- const { data: appMode } = useQuery(- consoleQuery.apps.byAppId.get.queryOptions({- input: appId ? { params: { app_id: appId } } : skipToken,- select: (appDetail) => appDetail.mode,- }),- )-- return appMode === AppModeEnum.ADVANCED_CHAT-}diff --git a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.tsindex 22b902b10e3..0bfbe01a805 100644--- a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts+++ b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts@@ -7,11 +7,13 @@ import type { WorkflowDraftFeaturesPayload } from '@/service/workflow'import { safe } from '@orpc/client'import { skipToken, useQuery, useSuspenseQuery } from '@tanstack/react-query'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useEffect, useRef } from 'react'import { useTranslation } from 'react-i18next'import { useStoreApi } from 'reactflow'import { useFeaturesStore } from '@/app/components/base/features/hooks'import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'+import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useSerialAsyncCallback } from '@/app/components/workflow/hooks/use-serial-async-callback'import {useNodesReadOnly,@@ -21,7 +23,7 @@ import {isAgentV2NodeData,needsInlineAgentBindingCreation,} from '@/app/components/workflow/nodes/agent-v2/types'-import { useStore, useWorkflowStore } from '@/app/components/workflow/store'+import { useWorkflowStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'import { normalizeWorkflowNodes } from '@/app/components/workflow/utils/normalize-workflow-nodes'import { API_PREFIX } from '@/config'@@ -38,11 +40,11 @@ const isEmptyGraph = (graph: { nodes: unknown[]; edges: unknown[] }) =>graph.nodes.length === 0 && graph.edges.length === 0const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const store = useStoreApi()const workflowStore = useWorkflowStore()const featuresStore = useFeaturesStore()- const appId = useStore((state) => state.appId)+ const appId = useAtomValue(workflowAppIdentityAtom).appIdconst { data: appMode } = useQuery(consoleQuery.apps.byAppId.get.queryOptions({input: appId ? { params: { app_id: appId } } : skipToken,@@ -87,7 +89,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {.map((node) => node.id),)const [x, y, zoom] = transform- const { appId, conversationVariables, syncWorkflowDraftHash, isWorkflowDataLoaded } =+ const { conversationVariables, syncWorkflowDraftHash, isWorkflowDataLoaded } =workflowStore.getState()if (!appId || shouldSkipDraftSync(appId, isWorkflowDataLoaded)) return null@@ -174,7 +176,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {force?: boolean,): Promise<SyncDraftResult | null> => {if (getNodesReadOnly()) return null- const { appId, isWorkflowDataLoaded } = workflowStore.getState()+ const { isWorkflowDataLoaded } = workflowStore.getState()if (shouldSkipDraftSync(appId, isWorkflowDataLoaded)) {callback?.onSettled?.()return null@@ -224,7 +226,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {),)if (error) {- const { appId, isWorkflowDataLoaded } = workflowStore.getState()+ const { isWorkflowDataLoaded } = workflowStore.getState()if (shouldSkipDraftSync(appId, isWorkflowDataLoaded)) return nullif (isDefined && error.code === 'draft_workflow_not_sync' && !notRefreshWhenSyncError)@@ -258,7 +260,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {options?: SyncDraftOptions,): Promise<SyncDraftResult | null> => {if (getNodesReadOnly()) return null- const { appId, isWorkflowDataLoaded } = workflowStore.getState()+ const { isWorkflowDataLoaded } = workflowStore.getState()if (shouldSkipDraftSync(appId, isWorkflowDataLoaded)) {callback?.onSettled?.()return null@@ -333,7 +335,7 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {callback?.onSuccess?.()return result} catch {- const { appId, isWorkflowDataLoaded } = workflowStore.getState()+ const { isWorkflowDataLoaded } = workflowStore.getState()if (!shouldSkipDraftSync(appId, isWorkflowDataLoaded)) callback?.onError?.()return null} finally {diff --git a/web/app/components/workflow-app/hooks/use-workflow-draft-graph-for-canvas.ts b/web/app/components/workflow-app/hooks/use-workflow-draft-graph-for-canvas.tsindex 5612ec240d3..65d9f036848 100644--- a/web/app/components/workflow-app/hooks/use-workflow-draft-graph-for-canvas.ts+++ b/web/app/components/workflow-app/hooks/use-workflow-draft-graph-for-canvas.ts@@ -1,3 +1,4 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { Node, WorkflowDataUpdater } from '@/app/components/workflow/types'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'@@ -6,7 +7,6 @@ import startPlaceholderDefault from '@/app/components/workflow/nodes/start-placeimport { BlockEnum } from '@/app/components/workflow/types'import { generateNewNode } from '@/app/components/workflow/utils'import { normalizeWorkflowNodes } from '@/app/components/workflow/utils/normalize-workflow-nodes'-import { AppModeEnum } from '@/types/app'type HydrateWorkflowDraftGraphOptions = {localStartPlaceholderNodes?: Node[]@@ -26,16 +26,12 @@ const hasStartPlaceholderNode = (nodes: Node[] = []): boolean => {return nodes.some((node) => node?.data?.type === BlockEnum.StartPlaceholder)}-export const useWorkflowDraftGraphForCanvas = (appMode?: AppModeEnum | string) => {- const { t } = useTranslation(['workflow'])+export const useWorkflowDraftGraphForCanvas = (appMode?: AppMode) => {+ const { t } = useTranslation(['workflow'] as const)const getNodesWithLocalStartPlaceholder = useCallback((nodes: Node[] = [], localStartPlaceholderNodes?: Node[]) => {- if (- appMode !== AppModeEnum.WORKFLOW ||- hasWorkflowEntryNode(nodes) ||- hasStartPlaceholderNode(nodes)- )+ if (appMode !== 'workflow' || hasWorkflowEntryNode(nodes) || hasStartPlaceholderNode(nodes))return nodesif (localStartPlaceholderNodes?.length) return [...localStartPlaceholderNodes, ...nodes]diff --git a/web/app/components/workflow-app/hooks/use-workflow-init.ts b/web/app/components/workflow-app/hooks/use-workflow-init.tsindex 710be942a7d..bb98542ae9c 100644--- a/web/app/components/workflow-app/hooks/use-workflow-init.ts+++ b/web/app/components/workflow-app/hooks/use-workflow-init.ts@@ -5,16 +5,15 @@ import { ORPCError } from '@orpc/client'import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import { useCallback, useEffect, useMemo, useState } from 'react'+import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useStore, useWorkflowStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'-import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { useWorkflowConfig } from '@/service/use-workflow'import { fetchNodesDefaultConfigs, fetchWorkflowDraft, syncWorkflowDraft } from '@/service/workflow'import { appWorkflowQueryOptions } from '@/service/workflow-queries'-import { AppModeEnum } from '@/types/app'import { getAppACLCapabilities } from '@/utils/permission'import { useWorkflowDraftGraphForCanvas } from './use-workflow-draft-graph-for-canvas'import { useWorkflowTemplate } from './use-workflow-template'@@ -60,7 +59,7 @@ export const useWorkflowInit = () => {const queryClient = useQueryClient()const workflowStore = useWorkflowStore()const { nodes: nodesTemplate, edges: edgesTemplate } = useWorkflowTemplate()- const { appId } = useParams<{ appId: string }>()+ const { appId } = useAtomValue(workflowAppIdentityAtom)const { data: appDetail } = useSuspenseQuery(consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),)@@ -82,9 +81,6 @@ export const useWorkflowInit = () => {const setSyncWorkflowDraftHash = useStore((s) => s.setSyncWorkflowDraftHash)const [data, setData] = useState<FetchWorkflowDraftResponse>()const [isLoading, setIsLoading] = useState(true)- useEffect(() => {- workflowStore.setState({ appId: appDetail.id, appName: appDetail.name })- }, [appDetail.id, workflowStore])const handleUpdateWorkflowFileUploadConfig = useCallback((config: FileUploadConfigResponse) => {@@ -133,7 +129,7 @@ export const useWorkflowInit = () => {} catch (error: unknown) {if (error instanceof ORPCError) {if (error.code === 'draft_workflow_not_exist') {- const isAdvancedChat = appDetail.mode === AppModeEnum.ADVANCED_CHAT+ const isAdvancedChat = appDetail.mode === 'advanced-chat'const initialGraph = {nodes: isAdvancedChat ? nodesTemplate : [],edges: isAdvancedChat ? edgesTemplate : [],diff --git a/web/app/components/workflow-app/hooks/use-workflow-refresh-draft.ts b/web/app/components/workflow-app/hooks/use-workflow-refresh-draft.tsindex edbe513e2c2..060be206a74 100644--- a/web/app/components/workflow-app/hooks/use-workflow-refresh-draft.ts+++ b/web/app/components/workflow-app/hooks/use-workflow-refresh-draft.ts@@ -1,8 +1,9 @@import { useSuspenseQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { useCallback, useRef } from 'react'+import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useWorkflowUpdate } from '@/app/components/workflow/hooks/use-workflow-update'import { useWorkflowStore } from '@/app/components/workflow/store'-import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { fetchWorkflowDraft } from '@/service/workflow'import { useWorkflowDraftGraphForCanvas } from './use-workflow-draft-graph-for-canvas'@@ -12,9 +13,9 @@ type RefreshWorkflowDraftOptions = {}export const useWorkflowRefreshDraft = () => {- const { appId: routeAppId } = useParams<{ appId: string }>()+ const { appId } = useAtomValue(workflowAppIdentityAtom)const { data: appDetail } = useSuspenseQuery(- consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: routeAppId } } }),+ consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),)const workflowStore = useWorkflowStore()const refreshSequenceRef = useRef(0)@@ -26,7 +27,6 @@ export const useWorkflowRefreshDraft = () => {if (options?.shouldApply && !options.shouldApply()) return Promise.resolve(false)const {- appId,setSyncWorkflowDraftHash,setIsSyncingWorkflowDraft,setEnvironmentVariables,diff --git a/web/app/components/workflow-app/hooks/use-workflow-run-utils.ts b/web/app/components/workflow-app/hooks/use-workflow-run-utils.tsindex e30266c0380..b6bf7854e47 100644--- a/web/app/components/workflow-app/hooks/use-workflow-run-utils.ts+++ b/web/app/components/workflow-app/hooks/use-workflow-run-utils.ts@@ -10,7 +10,6 @@ import { WorkflowRunningStatus } from '@/app/components/workflow/types'import { toast } from '@/app/notifications'import { handleStream, post } from '@/service/base'import { ContentType } from '@/service/fetch'-import { AppModeEnum } from '@/types/app'type HandleRunMode = TriggerTypeexport type HandleRunOptions = {@@ -116,7 +115,7 @@ export const createFailedWorkflowState = (error: string) => {}export const buildRunHistoryUrl = (appDetail?: AppDetailLike) => {- return appDetail?.mode === AppModeEnum.ADVANCED_CHAT+ return appDetail?.mode === 'advanced-chat'? `/apps/${appDetail.id}/advanced-chat/workflow-runs`: `/apps/${appDetail?.id}/workflow-runs`}@@ -148,7 +147,7 @@ export const resolveWorkflowRunUrl = (return `/apps/${appDetail.id}/workflows/draft/trigger/run-all`}- if (appDetail?.mode === AppModeEnum.ADVANCED_CHAT)+ if (appDetail?.mode === 'advanced-chat')return `/apps/${appDetail.id}/advanced-chat/workflows/draft/run`if (isInWorkflowDebug && appDetail?.id) return `/apps/${appDetail.id}/workflows/draft/run`diff --git a/web/app/components/workflow-app/hooks/use-workflow-run.ts b/web/app/components/workflow-app/hooks/use-workflow-run.tsindex df6be208fff..3111e94dc62 100644--- a/web/app/components/workflow-app/hooks/use-workflow-run.ts+++ b/web/app/components/workflow-app/hooks/use-workflow-run.ts@@ -6,24 +6,27 @@ import type { VersionHistory } from '@/types/workflow'import { useSuspenseQuery } from '@tanstack/react-query'import { noop } from 'es-toolkit/function'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useRef } from 'react'import { useReactFlow, useStoreApi } from 'reactflow'import { v4 as uuidV4 } from 'uuid'import { trackEvent } from '@/app/components/base/amplitude'import { AudioPlayerManager } from '@/app/components/base/audio-btn/audio.player.manager'import { useFeaturesStore } from '@/app/components/base/features/hooks'+import {+ editorResourceAtom,+ workflowAppIdentityAtom,+} from '@/app/components/workflow/editor-resource/state'import { TriggerType } from '@/app/components/workflow/header/test-run-menu'import { useSetWorkflowVarsWithValue } from '@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars'import { useWorkflowRunEvent } from '@/app/components/workflow/hooks/use-workflow-run-event/use-workflow-run-event'import { useWorkflowUpdate } from '@/app/components/workflow/hooks/use-workflow-update'import { useWorkflowStore } from '@/app/components/workflow/store'-import { useParams, usePathname } from '@/next/navigation'+import { usePathname } from '@/next/navigation'import { ssePost } from '@/service/base'import { consoleQuery } from '@/service/console'-import { useInvalidAllLastRun, useInvalidateWorkflowRunHistory } from '@/service/use-workflow'+import { useInvalidateAllLastRun, useInvalidateWorkflowRunHistory } from '@/service/use-workflow'import { stopWorkflowRun } from '@/service/workflow'-import { AppModeEnum } from '@/types/app'-import { useConfigsMap } from './use-configs-map'import { useNodesSyncDraft, useNodesSyncDraftByCanEdit } from './use-nodes-sync-draft'import {createBaseWorkflowRunCallbacks,@@ -118,18 +121,15 @@ const useWorkflowRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const featuresStore = useFeaturesStore()const { handleUpdateWorkflowCanvas } = useWorkflowUpdate()const pathname = usePathname()- const { appId } = useParams<{ appId: string }>()+ const { appId } = useAtomValue(workflowAppIdentityAtom)const { data: appDetail } = useSuspenseQuery(consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),)- const configsMap = useConfigsMap()- const { flowId, flowType } = configsMap- const invalidAllLastRun = useInvalidAllLastRun(flowType, flowId)+ const resource = useAtomValue(editorResourceAtom)+ const invalidAllLastRun = useInvalidateAllLastRun(resource)const invalidateRunHistory = useInvalidateWorkflowRunHistory()- const { fetchInspectVars } = useSetWorkflowVarsWithValue({- ...configsMap,- })+ const { fetchInspectVars } = useSetWorkflowVarsWithValue()const abortControllerRef = useRef<AbortController | null>(null)@@ -235,7 +235,7 @@ const useWorkflowRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const { clientWidth, clientHeight } = workflowContainer!- const isInWorkflowDebug = appDetail.mode === AppModeEnum.WORKFLOW+ const isInWorkflowDebug = appDetail.mode === 'workflow'const url = resolveWorkflowRunUrl(appDetail, runMode, isInWorkflowDebug)const requestBody = buildWorkflowRunRequestBody(runMode, resolvedParams, options)@@ -371,7 +371,7 @@ const useWorkflowRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const workflowDataTrackingProperties = buildWorkflowDataTrackingProperties(workflowData)trackEvent('workflow_run_failed', {- workflow_id: flowId,+ workflow_id: appId,reason,node_type: nodeType,data: {@@ -454,7 +454,7 @@ const useWorkflowRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {pathname,appDetail,handleWorkflowFailed,- flowId,+ appId,handleWorkflowStarted,handleWorkflowFinished,fetchInspectVars,diff --git a/web/app/components/workflow-app/hooks/use-workflow-start-run.tsx b/web/app/components/workflow-app/hooks/use-workflow-start-run.tsxindex 7f85ef37f5b..edd7c3e11a3 100644--- a/web/app/components/workflow-app/hooks/use-workflow-start-run.tsx+++ b/web/app/components/workflow-app/hooks/use-workflow-start-run.tsx@@ -1,10 +1,11 @@import type { useNodesSyncDraft } from './use-nodes-sync-draft'import type { useWorkflowRun } from './use-workflow-run'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useStoreApi } from 'reactflow'import { useFeaturesStore } from '@/app/components/base/features/hooks'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { TriggerType } from '@/app/components/workflow/header/test-run-menu'-import { useIsChatMode } from '@/app/components/workflow/hooks/use-workflow'import { useWorkflowInteractions } from '@/app/components/workflow/hooks/use-workflow-panel-interactions'import { useWorkflowStore } from '@/app/components/workflow/store'import { BlockEnum, WorkflowRunningStatus } from '@/app/components/workflow/types'@@ -21,7 +22,7 @@ const useWorkflowStartRunBase = (const store = useStoreApi()const workflowStore = useWorkflowStore()const featuresStore = useFeaturesStore()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const { handleCancelDebugAndPreviewPanel } = useWorkflowInteractions()const handleWorkflowStartRunInWorkflow = useCallback(async () => {@@ -279,9 +280,9 @@ const useWorkflowStartRunBase = (}, [workflowStore, handleCancelDebugAndPreviewPanel])const handleStartWorkflowRun = useCallback(() => {- if (!isChatMode) handleWorkflowStartRunInWorkflow()+ if (!isChatflow) handleWorkflowStartRunInWorkflow()else handleWorkflowStartRunInChatflow()- }, [isChatMode, handleWorkflowStartRunInWorkflow, handleWorkflowStartRunInChatflow])+ }, [isChatflow, handleWorkflowStartRunInWorkflow, handleWorkflowStartRunInChatflow])return {handleStartWorkflowRun,diff --git a/web/app/components/workflow-app/hooks/use-workflow-template.ts b/web/app/components/workflow-app/hooks/use-workflow-template.tsindex 8e0fa1b6337..d6509a233f9 100644--- a/web/app/components/workflow-app/hooks/use-workflow-template.ts+++ b/web/app/components/workflow-app/hooks/use-workflow-template.ts@@ -1,24 +1,26 @@import type { StartNodeType } from '@/app/components/workflow/nodes/start/types'import { useSuspenseQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { useTranslation } from 'react-i18next'import { NODE_WIDTH_X_OFFSET, START_INITIAL_POSITION } from '@/app/components/workflow/constants'+import {+ isChatflowAtom,+ workflowAppIdentityAtom,+} from '@/app/components/workflow/editor-resource/state'import answerDefault from '@/app/components/workflow/nodes/answer/default'import llmDefault from '@/app/components/workflow/nodes/llm/default'import startPlaceholderDefault from '@/app/components/workflow/nodes/start-placeholder/default'import startDefault from '@/app/components/workflow/nodes/start/default'import { generateNewNode } from '@/app/components/workflow/utils'-import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'-import { useIsChatMode } from './use-is-chat-mode'export const useWorkflowTemplate = () => {- const isChatMode = useIsChatMode()- const { appId } = useParams<{ appId: string }>()+ const isChatflow = useAtomValue(isChatflowAtom)+ const { appId } = useAtomValue(workflowAppIdentityAtom)const { data: appDetail } = useSuspenseQuery(consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),)- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const createStartNode = () => {const { newNode: startNode } = generateNewNode({@@ -33,7 +35,7 @@ export const useWorkflowTemplate = () => {return startNode}- if (isChatMode) {+ if (isChatflow) {const startNode = createStartNode()const { newNode: llmNode } = generateNewNode({@@ -89,7 +91,7 @@ export const useWorkflowTemplate = () => {edges: [startToLlmEdge, llmToAnswerEdge],}}- if (appDetail.mode === AppModeEnum.WORKFLOW) {+ if (appDetail.mode === 'workflow') {const { newNode: startPlaceholderNode } = generateNewNode({data: {...startPlaceholderDefault.defaultValue,diff --git a/web/app/components/workflow-app/index.tsx b/web/app/components/workflow-app/index.tsxindex 7a47e2c20e5..c180e791381 100644--- a/web/app/components/workflow-app/index.tsx+++ b/web/app/components/workflow-app/index.tsx@@ -5,10 +5,13 @@ import type { InjectWorkflowStoreSliceFn } from '@/app/components/workflow/storeimport { useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import { useEffect, useMemo } from 'react'+import { isWorkflowAppMode } from '@/app/components/apps/app-type'import { FeaturesProvider } from '@/app/components/base/features'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import WorkflowWithDefaultContext from '@/app/components/workflow'import { WorkflowContextProvider } from '@/app/components/workflow/context'+import { EditorResourceScope } from '@/app/components/workflow/editor-resource/provider'+import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { useWorkflowStore } from '@/app/components/workflow/store'import { useTriggerStatusStore } from '@/app/components/workflow/store/trigger-status'import { initialEdges, initialNodes } from '@/app/components/workflow/utils'@@ -19,7 +22,6 @@ import { useParams, useSearchParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { fetchRunDetail } from '@/service/log'import { useAppTriggers } from '@/service/use-tools'-import { AppModeEnum } from '@/types/app'import { getAppACLCapabilities } from '@/utils/permission'import WorkflowAppMain from './components/workflow-main'import { useGetRunAndTraceUrl } from './hooks/use-get-run-and-trace-url'@@ -40,7 +42,7 @@ const WorkflowAppWithAdditionalContext = () => {// Initialize trigger status at application levelconst { setTriggerStatuses } = useTriggerStatusStore()- const { appId } = useParams<{ appId: string }>()+ const { appId } = useAtomValue(workflowAppIdentityAtom)const { data: appDetail } = useSuspenseQuery(consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),)@@ -53,7 +55,7 @@ const WorkflowAppWithAdditionalContext = () => {}),[appDetail.maintainer, appDetail.permission_keys, currentUserId, workspacePermissionKeys],)- const isWorkflowMode = appDetail.mode === AppModeEnum.WORKFLOW+ const isWorkflowMode = appDetail.mode === 'workflow'const { data: triggersResponse } = useAppTriggers(isWorkflowMode ? appId : undefined, {staleTime: 5 * 60 * 1000, // 5 minutes cacherefetchOnWindowFocus: false,@@ -138,12 +140,23 @@ const WorkflowAppWithAdditionalContext = () => {}const WorkflowAppWrapper = () => {+ const { appId } = useParams<{ appId: string }>()+ const { data: mode } = useSuspenseQuery(+ consoleQuery.apps.byAppId.get.queryOptions({+ input: { params: { app_id: appId } },+ select: (app) => app.mode,+ }),+ )+ if (!isWorkflowAppMode(mode)) throw new Error('This app does not have a workflow editor')+return (- <WorkflowContextProvider- injectWorkflowStoreSliceFn={createWorkflowSlice as InjectWorkflowStoreSliceFn}- >- <WorkflowAppWithAdditionalContext />- </WorkflowContextProvider>+ <EditorResourceScope resource={{ kind: 'app', appId, mode }}>+ <WorkflowContextProvider+ injectWorkflowStoreSliceFn={createWorkflowSlice as InjectWorkflowStoreSliceFn}+ >+ <WorkflowAppWithAdditionalContext />+ </WorkflowContextProvider>+ </EditorResourceScope>)}diff --git a/web/app/components/workflow-app/store/workflow/workflow-slice.ts b/web/app/components/workflow-app/store/workflow/workflow-slice.tsindex 42354247c3f..51d03120d5c 100644--- a/web/app/components/workflow-app/store/workflow/workflow-slice.ts+++ b/web/app/components/workflow-app/store/workflow/workflow-slice.ts@@ -1,8 +1,6 @@import type { StateCreator } from 'zustand'export type WorkflowSliceShape = {- appId: string- appName: stringnotInitialWorkflow: booleansetNotInitialWorkflow: (notInitialWorkflow: boolean) => voidshouldAutoOpenStartNodeSelector: boolean@@ -18,8 +16,6 @@ export type WorkflowSliceShape = {}export const createWorkflowSlice: StateCreator<WorkflowSliceShape> = (set) => ({- appId: '',- appName: '',notInitialWorkflow: false,setNotInitialWorkflow: (notInitialWorkflow) => set(() => ({ notInitialWorkflow })),shouldAutoOpenStartNodeSelector: false,diff --git a/web/app/components/workflow/__tests__/edge-insert-focus.browser.spec.tsx b/web/app/components/workflow/__tests__/edge-insert-focus.browser.spec.tsxindex 6dfddd9018c..07f34d8ac68 100644--- a/web/app/components/workflow/__tests__/edge-insert-focus.browser.spec.tsx+++ b/web/app/components/workflow/__tests__/edge-insert-focus.browser.spec.tsx@@ -5,6 +5,7 @@ import { page, userEvent } from 'vite-plus/test/browser'import { render } from 'vitest-browser-react'import { WorkflowContext } from '../context'import CustomEdge from '../custom-edge'+import { EditorResourceScope } from '../editor-resource/provider'import { createWorkflowStore } from '../store/workflow'import { BlockEnum } from '../types'import 'reactflow/dist/style.css'@@ -53,20 +54,22 @@ const edges = [function Fixture() {const [store] = useState(() => createWorkflowStore({}))return (- <WorkflowContext value={store}>- <ReactFlowProvider>- <button type="button">Before canvas</button>- <div style={{ width: 800, height: 500 }}>- <ReactFlow- nodes={nodes}- edges={edges}- edgeTypes={edgeTypes}- nodesFocusable={false}- edgesFocusable={false}- />- </div>- </ReactFlowProvider>- </WorkflowContext>+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>+ <WorkflowContext value={store}>+ <ReactFlowProvider>+ <button type="button">Before canvas</button>+ <div style={{ width: 800, height: 500 }}>+ <ReactFlow+ nodes={nodes}+ edges={edges}+ edgeTypes={edgeTypes}+ nodesFocusable={false}+ edgesFocusable={false}+ />+ </div>+ </ReactFlowProvider>+ </WorkflowContext>+ </EditorResourceScope>)}diff --git a/web/app/components/workflow/__tests__/features.spec.tsx b/web/app/components/workflow/__tests__/features.spec.tsxindex 5d9da98e74c..4b68fefa8ad 100644--- a/web/app/components/workflow/__tests__/features.spec.tsx+++ b/web/app/components/workflow/__tests__/features.spec.tsx@@ -35,7 +35,7 @@ vi.mock('../hooks/use-workflow', async (importOriginal) => {const actual = await importOriginal<typeof import('../hooks/use-workflow')>()return {...actual,- useIsChatMode: () => mockIsChatMode,+useNodesReadOnly: () => ({nodesReadOnly: mockNodesReadOnly,}),@@ -230,3 +230,10 @@ describe('Features', () => {})})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockIsChatMode) }+})diff --git a/web/app/components/workflow-app/hooks/__tests__/use-available-nodes-meta-data.spec.ts b/web/app/components/workflow/__tests__/node-catalog.spec.tssimilarity index 74%rename from web/app/components/workflow-app/hooks/__tests__/use-available-nodes-meta-data.spec.tsrename to web/app/components/workflow/__tests__/node-catalog.spec.tsindex 8d105f403b7..057d2392ff0 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-available-nodes-meta-data.spec.ts+++ b/web/app/components/workflow/__tests__/node-catalog.spec.ts@@ -1,15 +1,11 @@-import { renderHook } from '@testing-library/react'+import { renderWorkflowHook } from '@/app/components/workflow/__tests__/workflow-test-env'+import { useWorkflowNodeCatalog } from '@/app/components/workflow/node-catalog'import { BlockEnum } from '@/app/components/workflow/types'-import { useAvailableNodesMetaData } from '../use-available-nodes-meta-data'const mockUseIsChatMode = vi.fn()const mockIsAgentV2Enabled = vi.hoisted(() => vi.fn(() => true))const mockIsAgentV2InChatflowEnabled = vi.hoisted(() => vi.fn(() => false))-vi.mock('../use-is-chat-mode', () => ({- useIsChatMode: () => mockUseIsChatMode(),-}))-vi.mock('@/features/agent-v2/feature-flag', () => ({isAgentV2Enabled: () => mockIsAgentV2Enabled(),isAgentV2InChatflowEnabled: () => mockIsAgentV2InChatflowEnabled(),@@ -19,7 +15,7 @@ vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `/docs${path}`,}))-describe('useAvailableNodesMetaData', () => {+describe('useWorkflowNodeCatalog', () => {beforeEach(() => {vi.clearAllMocks()mockIsAgentV2Enabled.mockReturnValue(true)@@ -29,7 +25,13 @@ describe('useAvailableNodesMetaData', () => {it('should include chat-specific nodes and make the start node undeletable in chat mode', () => {mockUseIsChatMode.mockReturnValue(true)- const { result } = renderHook(() => useAvailableNodesMetaData())+ const { result } = renderWorkflowHook(() => useWorkflowNodeCatalog(), {+ resource: {+ kind: 'app',+ appId: 'app-1',+ mode: mockUseIsChatMode() ? 'advanced-chat' : 'workflow',+ },+ })expect(result.current.nodesMap?.[BlockEnum.Start]?.metaData.isUndeletable).toBe(true)expect(result.current.nodesMap?.[BlockEnum.Answer]).toBeDefined()@@ -46,7 +48,13 @@ describe('useAvailableNodesMetaData', () => {it('should expose only legacy Agent in chat mode by default even when Agent v2 is enabled', () => {mockUseIsChatMode.mockReturnValue(true)- const { result } = renderHook(() => useAvailableNodesMetaData())+ const { result } = renderWorkflowHook(() => useWorkflowNodeCatalog(), {+ resource: {+ kind: 'app',+ appId: 'app-1',+ mode: mockUseIsChatMode() ? 'advanced-chat' : 'workflow',+ },+ })const nodeTypes = result.current.nodes.map((node) => node.metaData.type)expect(nodeTypes).toContain(BlockEnum.Agent)@@ -59,7 +67,13 @@ describe('useAvailableNodesMetaData', () => {mockUseIsChatMode.mockReturnValue(true)mockIsAgentV2InChatflowEnabled.mockReturnValue(true)- const { result } = renderHook(() => useAvailableNodesMetaData())+ const { result } = renderWorkflowHook(() => useWorkflowNodeCatalog(), {+ resource: {+ kind: 'app',+ appId: 'app-1',+ mode: mockUseIsChatMode() ? 'advanced-chat' : 'workflow',+ },+ })const nodeTypes = result.current.nodes.map((node) => node.metaData.type)expect(nodeTypes).toContain(BlockEnum.AgentV2)@@ -73,7 +87,13 @@ describe('useAvailableNodesMetaData', () => {mockIsAgentV2Enabled.mockReturnValue(false)mockIsAgentV2InChatflowEnabled.mockReturnValue(true)- const { result } = renderHook(() => useAvailableNodesMetaData())+ const { result } = renderWorkflowHook(() => useWorkflowNodeCatalog(), {+ resource: {+ kind: 'app',+ appId: 'app-1',+ mode: mockUseIsChatMode() ? 'advanced-chat' : 'workflow',+ },+ })const nodeTypes = result.current.nodes.map((node) => node.metaData.type)expect(nodeTypes).toContain(BlockEnum.Agent)@@ -85,7 +105,13 @@ describe('useAvailableNodesMetaData', () => {it('should include workflow-specific trigger and end nodes outside chat mode', () => {mockUseIsChatMode.mockReturnValue(false)- const { result } = renderHook(() => useAvailableNodesMetaData())+ const { result } = renderWorkflowHook(() => useWorkflowNodeCatalog(), {+ resource: {+ kind: 'app',+ appId: 'app-1',+ mode: mockUseIsChatMode() ? 'advanced-chat' : 'workflow',+ },+ })expect(result.current.nodesMap?.[BlockEnum.Start]?.metaData.isUndeletable).toBe(false)expect(result.current.nodesMap?.[BlockEnum.End]).toBeDefined()@@ -103,7 +129,13 @@ describe('useAvailableNodesMetaData', () => {it('should use explicit docs pages and skip nodes without generated docs pages', () => {mockUseIsChatMode.mockReturnValue(false)- const { result } = renderHook(() => useAvailableNodesMetaData())+ const { result } = renderWorkflowHook(() => useWorkflowNodeCatalog(), {+ resource: {+ kind: 'app',+ appId: 'app-1',+ mode: mockUseIsChatMode() ? 'advanced-chat' : 'workflow',+ },+ })expect(result.current.nodesMap?.[BlockEnum.End]?.metaData.helpLinkUri).toBe('/docs/use-dify/nodes/output',@@ -121,7 +153,13 @@ describe('useAvailableNodesMetaData', () => {it('should hide legacy Agent from the node picker but retain its validator when Agent v2 is enabled', () => {mockUseIsChatMode.mockReturnValue(false)- const { result } = renderHook(() => useAvailableNodesMetaData())+ const { result } = renderWorkflowHook(() => useWorkflowNodeCatalog(), {+ resource: {+ kind: 'app',+ appId: 'app-1',+ mode: mockUseIsChatMode() ? 'advanced-chat' : 'workflow',+ },+ })const nodeTypes = result.current.nodes.map((node) => node.metaData.type)expect(nodeTypes).toContain(BlockEnum.AgentV2)@@ -137,7 +175,13 @@ describe('useAvailableNodesMetaData', () => {mockUseIsChatMode.mockReturnValue(false)mockIsAgentV2Enabled.mockReturnValue(false)- const { result } = renderHook(() => useAvailableNodesMetaData())+ const { result } = renderWorkflowHook(() => useWorkflowNodeCatalog(), {+ resource: {+ kind: 'app',+ appId: 'app-1',+ mode: mockUseIsChatMode() ? 'advanced-chat' : 'workflow',+ },+ })const nodeTypes = result.current.nodes.map((node) => node.metaData.type)expect(nodeTypes).toContain(BlockEnum.Agent)diff --git a/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx b/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsxindex 7a418254010..a81bf60dcb8 100644--- a/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx+++ b/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx@@ -3,7 +3,6 @@ import { detectPlatform } from '@tanstack/react-hotkeys'import { act, fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { withSelectorKey } from '@/test/i18n-mock'-import { FlowType } from '@/types/common'import { fullWorkflowAccessControl } from '../hooks-store'import { PanelContextmenu } from '../panel-contextmenu'import { BlockEnum } from '../types'@@ -76,7 +75,7 @@ vi.mock('../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => mockUseIsChatMode(),+useNodesReadOnly: () => mockUseNodesReadOnly(),}})@@ -237,12 +236,9 @@ describe('PanelContextmenu', () => {initialStoreState: {contextMenuTarget: { type: 'panel' },},+ resource: { kind: 'snippet' as const, snippetId: 'snippet-1' },hooksStoreProps: {- configsMap: {- flowId: 'snippet-1',- flowType: FlowType.snippet,- fileSettings: {},- },+ fileSettings: {},},})@@ -293,3 +289,10 @@ describe('PanelContextmenu', () => {expect(screen.queryByText('nodes.note.addNote')).not.toBeInTheDocument()})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/__tests__/update-dsl-modal.helpers.spec.ts b/web/app/components/workflow/__tests__/update-dsl-modal.helpers.spec.tsindex a8a91801f70..95e6c46fe11 100644--- a/web/app/components/workflow/__tests__/update-dsl-modal.helpers.spec.ts+++ b/web/app/components/workflow/__tests__/update-dsl-modal.helpers.spec.ts@@ -1,5 +1,4 @@import { DSLImportStatus } from '@/models/app'-import { AppModeEnum } from '@/types/app'import { BlockEnum } from '../types'import {getImportNotificationPayload,@@ -20,7 +19,7 @@ workflow:type: trigger-webhook`- expect(validateDSLContent(content, AppModeEnum.ADVANCED_CHAT)).toBe(false)+ expect(validateDSLContent(content, 'advanced-chat')).toBe(false)})it('should reject disallowed node types inherited through YAML merge keys', () => {@@ -34,11 +33,11 @@ workflow:<<: *trigger`- expect(validateDSLContent(content, AppModeEnum.ADVANCED_CHAT)).toBe(false)+ expect(validateDSLContent(content, 'advanced-chat')).toBe(false)})it('should reject malformed yaml and answer nodes in non-advanced mode', () => {- expect(validateDSLContent('[', AppModeEnum.CHAT)).toBe(false)+ expect(validateDSLContent('[', 'chat')).toBe(false)expect(validateDSLContent(`@@ -48,7 +47,7 @@ workflow:- data:type: answer`,- AppModeEnum.CHAT,+ 'chat',),).toBe(false)})@@ -63,28 +62,28 @@ workflow:- data:type: tool`,- AppModeEnum.ADVANCED_CHAT,+ 'advanced-chat',),).toBe(true)})it('should accept empty yaml content', () => {- expect(validateDSLContent('', AppModeEnum.CHAT)).toBe(true)+ expect(validateDSLContent('', 'chat')).toBe(true)})it('should accept comment-only yaml content', () => {- expect(validateDSLContent('# No document', AppModeEnum.CHAT)).toBe(true)+ expect(validateDSLContent('# No document', 'chat')).toBe(true)})it('should reject yaml streams with multiple documents', () => {- expect(validateDSLContent('---\n{}\n---\n{}', AppModeEnum.CHAT)).toBe(false)+ expect(validateDSLContent('---\n{}\n---\n{}', 'chat')).toBe(false)})it('should expose the invalid node sets per mode', () => {- expect(getInvalidNodeTypes(AppModeEnum.ADVANCED_CHAT)).toEqual(+ expect(getInvalidNodeTypes('advanced-chat')).toEqual(expect.arrayContaining([BlockEnum.End, BlockEnum.TriggerWebhook]),)- expect(getInvalidNodeTypes(AppModeEnum.CHAT)).toEqual([BlockEnum.Answer])+ expect(getInvalidNodeTypes('chat')).toEqual([BlockEnum.Answer])})})diff --git a/web/app/components/workflow/__tests__/workflow-edge-events.spec.tsx b/web/app/components/workflow/__tests__/workflow-edge-events.spec.tsxindex 706e6378461..9d34dc5bb7d 100644--- a/web/app/components/workflow/__tests__/workflow-edge-events.spec.tsx+++ b/web/app/components/workflow/__tests__/workflow-edge-events.spec.tsx@@ -3,7 +3,6 @@ import { act, fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'import { BaseEdge, internalsSymbol, Position, ReactFlowProvider, useStoreApi } from 'reactflow'-import { FlowType } from '@/types/common'import { WORKFLOW_DATA_UPDATE } from '../constants'import { Workflow } from '../index'import { ControlMode } from '../types'@@ -415,7 +414,7 @@ vi.mock('../hooks/use-workflow', () => ({nodesReadOnly: false,getNodesReadOnly: () => false,}),- useIsChatMode: () => false,+useWorkflow: () => ({isValidConnection: workflowHookMocks.isValidConnection,}),@@ -512,12 +511,9 @@ function renderSubject(options?: {</ReactFlowProvider>,{initialStoreState,+ resource: { kind: 'app' as const, appId: 'flow-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'flow-1',- flowType: FlowType.appFlow,- fileSettings: {},- },+ fileSettings: {},},},)@@ -939,3 +935,10 @@ describe('Workflow edge event wiring', () => {})})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})diff --git a/web/app/components/workflow/__tests__/workflow-test-env.spec.tsx b/web/app/components/workflow/__tests__/workflow-test-env.spec.tsxindex 529a2aadc50..27d6e9f8358 100644--- a/web/app/components/workflow/__tests__/workflow-test-env.spec.tsx+++ b/web/app/components/workflow/__tests__/workflow-test-env.spec.tsx@@ -5,7 +5,6 @@ import type { Shape } from '../store/workflow'import { act, screen } from '@testing-library/react'import * as React from 'react'import { useNodes } from 'reactflow'-import { FlowType } from '@/types/common'import { useHooksStore } from '../hooks-store/store'import { useStore, useWorkflowStore } from '../store/workflow'import { createNode } from './fixtures'@@ -43,8 +42,12 @@ function StoreWriter() {}function HooksStoreReader() {- const flowId = useHooksStore((s) => s.configsMap?.flowId ?? 'none')- return React.createElement('div', { 'data-testid': 'hooks-reader' }, flowId)+ const fileSettings = useHooksStore((s) => s.fileSettings)+ return React.createElement(+ 'div',+ { 'data-testid': 'hooks-reader' },+ fileSettings ? 'configured' : 'none',+ )}function NodeRenderer(props: { id: string; data: { title: string }; selected?: boolean }) {@@ -104,11 +107,12 @@ describe('renderWorkflowComponent', () => {it('should provide HooksStoreContext when hooksStoreProps given', () => {renderWorkflowComponent(React.createElement(HooksStoreReader), {+ resource: { kind: 'app' as const, appId: 'test-123', mode: 'workflow' as const },hooksStoreProps: {- configsMap: { flowId: 'test-123', flowType: FlowType.appFlow, fileSettings: {} },+ fileSettings: {},},})- expect(screen.getByTestId('hooks-reader'))!.toHaveTextContent('test-123')+ expect(screen.getByTestId('hooks-reader'))!.toHaveTextContent('configured')})it('should provide HooksStoreContext with default store', () => {diff --git a/web/app/components/workflow/__tests__/workflow-test-env.tsx b/web/app/components/workflow/__tests__/workflow-test-env.tsxindex caba2808b04..6f6076a5ba9 100644--- a/web/app/components/workflow/__tests__/workflow-test-env.tsx+++ b/web/app/components/workflow/__tests__/workflow-test-env.tsx@@ -66,6 +66,7 @@ import type {RenderOptions,RenderResult,} from '@testing-library/react'+import type { EditorResource } from '../editor-resource/resource'import type { Shape as HooksStoreShape } from '../hooks-store/store'import type { Shape } from '../store/workflow'import type { WorkflowHistoryState } from '../store/workflow/history-slice'@@ -73,11 +74,14 @@ import type { Edge, Node, WorkflowRunningData } from '../types'import { QueryClient } from '@tanstack/react-query'import * as React from 'react'import ReactFlow, { ReactFlowProvider } from 'reactflow'+import { consoleQuery } from '@/service/console'import { seedAccountProfileQuery } from '@/test/console/account-profile'import { createQueryClientWrapper } from '@/test/console/query-client'-import { seedAppDslVersion, seedSystemFeatures } from '@/test/console/query-data'+import { seedAppDetail, seedAppDslVersion, seedSystemFeatures } from '@/test/console/query-data'import { render, renderHook } from '@/test/console/render'+import { createAppDetailFixture } from '@/test/fixtures/app'import { WorkflowContext } from '../context'+import { EditorResourceScope } from '../editor-resource/provider'import { HooksStoreContext } from '../hooks-store/provider'import { createHooksStore } from '../hooks-store/store'import { createWorkflowStore } from '../store/workflow'@@ -133,6 +137,7 @@ type HistoryStoreConfig = {}type WorkflowProviderOptions = {+ resource?: EditorResourceinitialStoreState?: Partial<Shape>hooksStoreProps?: Partial<HooksStoreShape>historyStore?: HistoryStoreConfig@@ -154,6 +159,7 @@ function createWorkflowWrapper(stores: StoreInstances,historyConfig?: HistoryStoreConfig,externalQueryClient?: QueryClient,+ resource: EditorResource = { kind: 'app', appId: 'app-1', mode: 'workflow' },) {if (historyConfig) {stores.store.temporal.getState().pause()@@ -176,6 +182,25 @@ function createWorkflowWrapper(if (!externalQueryClient) seedSystemFeatures(queryClient)if (!externalQueryClient) seedAppDslVersion(queryClient)if (!externalQueryClient) seedAccountProfileQuery(queryClient)+ if (resource.kind === 'app') {+ const input = { input: { params: { app_id: resource.appId } } }+ for (const endpoint of [+ consoleQuery.apps.byAppId.workflows.draft.systemVariables.get,+ consoleQuery.apps.byAppId.workflows.draft.conversationVariables.get,+ ]) {+ const variableKey = endpoint.queryKey(input)+ if (!queryClient.getQueryData(variableKey))+ queryClient.setQueryData(variableKey, { items: [] })+ }+ const key = consoleQuery.apps.byAppId.get.queryKey({+ input: { params: { app_id: resource.appId } },+ })+ if (!queryClient.getQueryData(key))+ seedAppDetail(+ queryClient,+ createAppDetailFixture({ id: resource.appId, mode: resource.mode }),+ )+ }const QueryClientWrapper = createQueryClientWrapper(queryClient)return ({ children }: { children: React.ReactNode }) => {@@ -188,7 +213,10 @@ function createWorkflowWrapper(return React.createElement(QueryClientWrapper,null,- React.createElement(WorkflowContext.Provider, { value: stores.store }, inner),+ React.createElement(EditorResourceScope, {+ resource,+ children: React.createElement(WorkflowContext.Provider, { value: stores.store }, inner),+ }),)}}@@ -218,11 +246,12 @@ export function renderWorkflowHook<R, P = undefined>(hooksStoreProps,historyStore: historyConfig,queryClient,+ resource,...rest} = options ?? {}const stores = createStoresFromOptions({ initialStoreState, hooksStoreProps })- const wrapper = createWorkflowWrapper(stores, historyConfig, queryClient)+ const wrapper = createWorkflowWrapper(stores, historyConfig, queryClient, resource)const renderResult = renderHook(hook, { wrapper, ...rest })return { ...renderResult, ...stores }@@ -253,11 +282,12 @@ export function renderWorkflowComponent(hooksStoreProps,historyStore: historyConfig,queryClient,+ resource,...renderOptions} = options ?? {}const stores = createStoresFromOptions({ initialStoreState, hooksStoreProps })- const wrapper = createWorkflowWrapper(stores, historyConfig, queryClient)+ const wrapper = createWorkflowWrapper(stores, historyConfig, queryClient, resource)const renderResult = render(ui, { wrapper, ...renderOptions })return { ...renderResult, ...stores }@@ -285,9 +315,11 @@ function createWorkflowFlowWrapper(edges = [],reactFlowProps,canvasStyle,+ resource,+ queryClient,}: WorkflowFlowOptions,) {- const workflowWrapper = createWorkflowWrapper(stores, historyConfig)+ const workflowWrapper = createWorkflowWrapper(stores, historyConfig, queryClient, resource)return ({ children }: { children: React.ReactNode }) =>React.createElement(@@ -318,6 +350,8 @@ export function renderWorkflowFlowComponent(edges,reactFlowProps,canvasStyle,+ resource,+ queryClient,...renderOptions} = options ?? {}@@ -328,6 +362,8 @@ export function renderWorkflowFlowComponent(edges,reactFlowProps,canvasStyle,+ resource,+ queryClient,})const renderResult = render(ui, { wrapper, ...renderOptions })@@ -346,6 +382,8 @@ export function renderWorkflowFlowHook<R, P = undefined>(edges,reactFlowProps,canvasStyle,+ resource,+ queryClient,...rest} = options ?? {}@@ -356,6 +394,8 @@ export function renderWorkflowFlowHook<R, P = undefined>(edges,reactFlowProps,canvasStyle,+ resource,+ queryClient,})const renderResult = renderHook(hook, { wrapper, ...rest })diff --git a/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsx b/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsxindex ce256df8513..6c50561a59f 100644--- a/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsx+++ b/web/app/components/workflow/block-selector/__tests__/agent-selector.spec.tsx@@ -1,8 +1,10 @@import type { AgentRosterNodeData } from '../types'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import { Button } from '@langgenius/dify-ui/button'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { EditorResourceScope } from '@/app/components/workflow/editor-resource/provider'import {AgentSelectorMenu,AgentSelectorMenuContent,@@ -23,23 +25,28 @@ vi.mock('@/app/notifications', () => ({toast: { error: mocks.toastError },}))-vi.mock('@/service/console', () => ({- consoleQuery: {- agent: {- inviteOptions: {- get: {- queryOptions: (args: unknown) => {- mocks.queryOptions(args)- return {- queryKey: ['agent-invite-options', args],- queryFn: async () => ({ data: mocks.agents }),- }+vi.mock('@/service/console', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/console')>()+ return {+ ...actual,+ consoleQuery: {+ ...actual.consoleQuery,+ agent: {+ inviteOptions: {+ get: {+ queryOptions: (args: unknown) => {+ mocks.queryOptions(args)+ return {+ queryKey: ['agent-invite-options', args],+ queryFn: async () => ({ data: mocks.agents }),+ }+ },},},},},- },-}))+ }+})const createAgent = (overrides: Record<string, unknown> = {}) => ({id: 'agent-1',@@ -56,19 +63,23 @@ const createAgent = (overrides: Record<string, unknown> = {}) => ({const renderMenu = async ({onSelect = vi.fn<(agent: AgentRosterNodeData) => void>(),onStartFromScratch,+ identity = { kind: 'app', appId: 'app-1', mode: 'workflow' },}: {onSelect?: ReturnType<typeof vi.fn<(agent: AgentRosterNodeData) => void>>onStartFromScratch?: () => void+ identity?: EditorResource} = {}) => {const user = userEvent.setup()const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })render(<QueryClientProvider client={queryClient}>- <AgentSelectorMenu>- <AgentSelectorMenuTrigger>Open agents</AgentSelectorMenuTrigger>- <AgentSelectorMenuContent onSelect={onSelect} onStartFromScratch={onStartFromScratch} />- </AgentSelectorMenu>+ <EditorResourceScope resource={identity}>+ <AgentSelectorMenu>+ <AgentSelectorMenuTrigger>Open agents</AgentSelectorMenuTrigger>+ <AgentSelectorMenuContent onSelect={onSelect} onStartFromScratch={onStartFromScratch} />+ </AgentSelectorMenu>+ </EditorResourceScope></QueryClientProvider>,)@@ -85,6 +96,13 @@ describe('AgentSelectorMenu', () => {mocks.toastError.mockClear()})+ it('does not send a snippet ID as the workflow app filter', async () => {+ await renderMenu({ identity: { kind: 'snippet', snippetId: 'snippet-1' } })+ expect(mocks.queryOptions).toHaveBeenCalledWith({+ input: { query: { limit: 8, page: 1 } },+ })+ })+it('lists agents and keeps the footer actions inside the menu', async () => {mocks.agents = [createAgent(), createAgent({ id: 'agent-2', name: 'Bob' })]const { menu } = await renderMenu({ onStartFromScratch: vi.fn() })@@ -149,12 +167,14 @@ describe('AgentSelectorMenu', () => {render(<QueryClientProvider client={queryClient}>- <AgentSelectorMenu>- <AgentSelectorMenuContent onSelect={vi.fn()} />- <AgentSelectorMenuTrigger render={<Button loading />}>- Open agents- </AgentSelectorMenuTrigger>- </AgentSelectorMenu>+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>+ <AgentSelectorMenu>+ <AgentSelectorMenuContent onSelect={vi.fn()} />+ <AgentSelectorMenuTrigger render={<Button loading />}>+ Open agents+ </AgentSelectorMenuTrigger>+ </AgentSelectorMenu>+ </EditorResourceScope></QueryClientProvider>,)diff --git a/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsx b/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsxindex 98a4868765d..afce1f62939 100644--- a/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsx+++ b/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsx@@ -6,7 +6,7 @@ import { useLocale } from '#i18n'import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/query'import { PluginCategoryEnum } from '@/app/components/plugins/types'import { CollectionType } from '@/app/components/tools/types'-import { useAvailableNodesMetaData } from '@/app/components/workflow-app/hooks/use-available-nodes-meta-data'+import { useWorkflowNodeCatalog } from '@/app/components/workflow/node-catalog'import { useGetLanguage } from '@/context/i18n'import useTheme from '@/hooks/use-theme'import { useFeaturedTriggersRecommendations } from '@/service/use-plugins'@@ -48,8 +48,8 @@ vi.mock('../../store/workflow/use-nodes', () => ({default: vi.fn(),}))-vi.mock('@/app/components/workflow-app/hooks/use-available-nodes-meta-data', () => ({- useAvailableNodesMetaData: vi.fn(),+vi.mock('@/app/components/workflow/node-catalog', () => ({+ useWorkflowNodeCatalog: vi.fn(),}))vi.mock('@/utils/var', async (importOriginal) => {@@ -75,7 +75,7 @@ const mockUseAllTriggerPlugins = vi.mocked(useAllTriggerPlugins)const mockUseInvalidateAllTriggerPlugins = vi.mocked(useInvalidateAllTriggerPlugins)const mockUseFeaturedTriggersRecommendations = vi.mocked(useFeaturedTriggersRecommendations)const mockUseNodes = vi.mocked(useNodes)-const mockUseAvailableNodesMetaData = vi.mocked(useAvailableNodesMetaData)+const mockUseAvailableNodesMetaData = vi.mocked(useWorkflowNodeCatalog)type UseMarketplacePluginsReturn = ReturnType<typeof useMarketplacePlugins>type UseAllTriggerPluginsReturn = ReturnType<typeof useAllTriggerPlugins>@@ -175,10 +175,10 @@ const createFeaturedTriggersRecommendationsMock = (...overrides,})-const createAvailableNodesMetaData = (): ReturnType<typeof useAvailableNodesMetaData> =>+const createAvailableNodesMetaData = (): ReturnType<typeof useWorkflowNodeCatalog> =>({nodes: [],- }) as unknown as ReturnType<typeof useAvailableNodesMetaData>+ }) as unknown as ReturnType<typeof useWorkflowNodeCatalog>describe('AllStartBlocks', () => {beforeEach(() => {diff --git a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsxindex 659890e3852..c87221a95fd 100644--- a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx+++ b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx@@ -2,11 +2,12 @@ import type {AgentInviteOptionResponse,AgentInviteOptionsResponse,} from '@dify/contracts/api/console/agent/types.gen'+import type { ReactElement } from 'react'import type { NodeDefault } from '../../types'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { render, screen, waitFor } from '@testing-library/react'+import { render as baseRender, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { FlowType } from '@/types/common'+import { EditorResourceScope } from '../../editor-resource/provider'import { HooksStoreContext } from '../../hooks-store/provider'import { createHooksStore } from '../../hooks-store/store'import { BlockEnum } from '../../types'@@ -173,11 +174,7 @@ describe('Blocks', () => {},})const hooksStore = createHooksStore({- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,})render(@@ -221,11 +218,7 @@ describe('Blocks', () => {},})const hooksStore = createHooksStore({- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,})render(@@ -313,11 +306,7 @@ describe('Blocks', () => {},})const hooksStore = createHooksStore({- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,})render(@@ -371,11 +360,7 @@ describe('Blocks', () => {},})const hooksStore = createHooksStore({- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,})render(@@ -414,11 +399,7 @@ describe('Blocks', () => {},})const hooksStore = createHooksStore({- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,})render(@@ -467,11 +448,7 @@ describe('Blocks', () => {},})const hooksStore = createHooksStore({- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,})render(@@ -503,3 +480,11 @@ describe('Blocks', () => {})})})++function render(ui: ReactElement) {+ return baseRender(+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>+ {ui}+ </EditorResourceScope>,+ )+}diff --git a/web/app/components/workflow/block-selector/__tests__/index.spec.tsx b/web/app/components/workflow/block-selector/__tests__/index.spec.tsxindex 65673beaebf..a9a019821a3 100644--- a/web/app/components/workflow/block-selector/__tests__/index.spec.tsx+++ b/web/app/components/workflow/block-selector/__tests__/index.spec.tsx@@ -4,7 +4,6 @@ import { Button } from '@langgenius/dify-ui/button'import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'-import { FlowType } from '@/types/common'import BlockSelector from '..'import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'import { BlockEnum } from '../../types'@@ -64,14 +63,10 @@ type RenderBlockSelectorOptions = Parameters<typeof renderWorkflowComponent>[1]const renderBlockSelector = (ui: ReactElement, options?: RenderBlockSelectorOptions) => {return renderWorkflowComponent(ui, {...options,+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {...options?.hooksStoreProps,- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- ...options?.hooksStoreProps?.configsMap,- },+ fileSettings: {} as never,},})}diff --git a/web/app/components/workflow/block-selector/__tests__/start-blocks.spec.tsx b/web/app/components/workflow/block-selector/__tests__/start-blocks.spec.tsxindex bf757ae1a05..65d69d6e0e1 100644--- a/web/app/components/workflow/block-selector/__tests__/start-blocks.spec.tsx+++ b/web/app/components/workflow/block-selector/__tests__/start-blocks.spec.tsx@@ -1,7 +1,7 @@import type { CommonNodeType } from '../../types'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { useAvailableNodesMetaData } from '@/app/components/workflow-app/hooks/use-available-nodes-meta-data'+import { useWorkflowNodeCatalog } from '@/app/components/workflow/node-catalog'import useNodes from '@/app/components/workflow/store/workflow/use-nodes'import { BlockEnum } from '../../types'import StartBlocks from '../start-blocks'@@ -10,22 +10,22 @@ vi.mock('@/app/components/workflow/store/workflow/use-nodes', () => ({default: vi.fn(),}))-vi.mock('@/app/components/workflow-app/hooks/use-available-nodes-meta-data', () => ({- useAvailableNodesMetaData: vi.fn(),+vi.mock('@/app/components/workflow/node-catalog', () => ({+ useWorkflowNodeCatalog: vi.fn(),}))const mockUseNodes = vi.mocked(useNodes)-const mockUseAvailableNodesMetaData = vi.mocked(useAvailableNodesMetaData)+const mockUseAvailableNodesMetaData = vi.mocked(useWorkflowNodeCatalog)const createNode = (type: BlockEnum) =>({data: { type } as Pick<CommonNodeType, 'type'>,}) as ReturnType<typeof useNodes>[number]-const createAvailableNodesMetaData = (): ReturnType<typeof useAvailableNodesMetaData> =>+const createAvailableNodesMetaData = (): ReturnType<typeof useWorkflowNodeCatalog> =>({nodes: [],- }) as unknown as ReturnType<typeof useAvailableNodesMetaData>+ }) as unknown as ReturnType<typeof useWorkflowNodeCatalog>describe('StartBlocks', () => {beforeEach(() => {diff --git a/web/app/components/workflow/block-selector/agent-selector.tsx b/web/app/components/workflow/block-selector/agent-selector.tsxindex 1a5e28c2382..d9d2b570725 100644--- a/web/app/components/workflow/block-selector/agent-selector.tsx+++ b/web/app/components/workflow/block-selector/agent-selector.tsx@@ -19,11 +19,12 @@ import {} from '@langgenius/dify-ui/dropdown-menu'import { keepPreviousData, useQuery } from '@tanstack/react-query'import { useDebounce } from 'ahooks'+import { useAtomValue } from 'jotai'import { createContext, use, useState } from 'react'import { useTranslation } from 'react-i18next'import AppIcon from '@/app/components/base/app-icon'import Badge from '@/app/components/base/badge'-import { useHooksStore } from '@/app/components/workflow/hooks-store'+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'import { toast } from '@/app/notifications'import Link from '@/next/link'import { consoleQuery } from '@/service/console'@@ -83,7 +84,7 @@ function AgentSelectorList({onStartFromScratch,}: Pick<AgentSelectorMenuContentProps, 'onSelect' | 'onStartFromScratch'>) {const { t } = useTranslation(['workflow', 'common', 'agentRoster'])- const appId = useHooksStore((s) => s.configsMap?.flowId)+ const appId = useAtomValue(editorAppIdAtom)const searchText = use(SearchTextContext)const keyword = useDebounce(searchText.trim(), { wait: 300 })const agentsQuery = useQuery({diff --git a/web/app/components/workflow/block-selector/index.tsx b/web/app/components/workflow/block-selector/index.tsxindex fc76a7f505d..f224fe25987 100644--- a/web/app/components/workflow/block-selector/index.tsx+++ b/web/app/components/workflow/block-selector/index.tsx@@ -19,11 +19,12 @@ import {PopoverTitle,PopoverTrigger,} from '@langgenius/dify-ui/popover'+import { useAtomValue } from 'jotai'import { memo, useCallback, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'+import { editorResourceKindAtom } from '@/app/components/workflow/editor-resource/state'import { useHooksStore } from '@/app/components/workflow/hooks-store'import useNodes from '@/app/components/workflow/store/workflow/use-nodes'-import { FlowType } from '@/types/common'import TipPopup from '../operator/tip-popup'import { useStore } from '../store'import { BlockEnum, isTriggerNode } from '../types'@@ -252,7 +253,7 @@ export function BlockSelectorContent({standalonePanel,}: BlockSelectorContentProps) {const nodes = useNodes()- const flowType = useHooksStore((state) => state.configsMap?.flowType)+ const resourceKind = useAtomValue(editorResourceKindAtom)const availableNodesMetaData = useHooksStore((state) => state.availableNodesMetaData)const fallbackDataSources = useStore((state) => state.dataSourceList)const blocks = useMemo(() => {@@ -296,12 +297,12 @@ export function BlockSelectorContent({return result}, [filteredNodes])- const disableStartTab = flowType === FlowType.snippet+ const disableStartTab = resourceKind === 'snippet'const { initialTab, tabs } = useTabs({noBlocks,noSources: !dataSources.length,noTools,- noSnippets: flowType === FlowType.snippet,+ noSnippets: resourceKind === 'snippet',noStart: !showStartTab,defaultActiveTab,hasStartPlaceholderNode,diff --git a/web/app/components/workflow/collaboration/hooks/use-collaboration.ts b/web/app/components/workflow/collaboration/hooks/use-collaboration.tsindex 4d4002999a2..10bd1a3df9f 100644--- a/web/app/components/workflow/collaboration/hooks/use-collaboration.ts+++ b/web/app/components/workflow/collaboration/hooks/use-collaboration.ts@@ -29,7 +29,11 @@ const initialState: CollaborationViewState = {isLeader: false,}-export function useCollaboration(appId: string, canEdit: boolean, reactFlowStore?: ReactFlowStore) {+export function useCollaboration(+ appId: string | undefined,+ canEdit: boolean,+ reactFlowStore?: ReactFlowStore,+) {const [state, setState] = useState<CollaborationViewState>(initialState)const cursorServiceRef = useRef<CursorService | null>(null)diff --git a/web/app/components/workflow/comment/__tests__/comment-close-focus.spec.tsx b/web/app/components/workflow/comment/__tests__/comment-close-focus.spec.tsxindex 05a6411ac35..c4cf70a4c34 100644--- a/web/app/components/workflow/comment/__tests__/comment-close-focus.spec.tsx+++ b/web/app/components/workflow/comment/__tests__/comment-close-focus.spec.tsx@@ -18,10 +18,6 @@ vi.mock('reactflow', async () =>(await import('../../__tests__/reactflow-mock-state')).createReactFlowModuleMock(),)-vi.mock('@/next/navigation', () => ({- useParams: () => ({ appId: 'app-1' }),-}))-vi.mock('@/hooks/use-format-time-from-now', () => ({useFormatTimeFromNow: () => ({ formatTimeFromNow: () => 'just now' }),}))diff --git a/web/app/components/workflow/comment/__tests__/comment-thread-focus.spec.tsx b/web/app/components/workflow/comment/__tests__/comment-thread-focus.spec.tsxindex 8bde90723c2..2b5db15b602 100644--- a/web/app/components/workflow/comment/__tests__/comment-thread-focus.spec.tsx+++ b/web/app/components/workflow/comment/__tests__/comment-thread-focus.spec.tsx@@ -2,20 +2,24 @@ import type { UserProfile, WorkflowCommentDetail, WorkflowCommentList } from '..import { act, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'-import { renderWithAccountProfile } from '@/test/console/account-profile'+import { renderWithAccountProfile as renderAccountProfile } from '@/test/console/account-profile'+import { EditorResourceScope } from '../../editor-resource/provider'import { CommentIcon } from '../comment-icon'import { CommentInput } from '../comment-input'import { CommentThread } from '../thread'+const renderWithAccountProfile = (ui: Parameters<typeof renderAccountProfile>[0]) =>+ renderAccountProfile(+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>+ {ui}+ </EditorResourceScope>,+ )+const storeState = vi.hoisted(() => ({mentionableUsersCache: { 'app-1': [] } as Record<string, UserProfile[]>,setCommentPreviewHovering: vi.fn(),}))-vi.mock('@/next/navigation', () => ({- useParams: () => ({ appId: 'app-1' }),-}))-vi.mock('reactflow', () => ({useReactFlow: () => ({flowToScreenPosition: (position: { x: number; y: number }) => position,diff --git a/web/app/components/workflow/comment/mention-input.spec.tsx b/web/app/components/workflow/comment/mention-input.spec.tsxindex 06af12b3c3b..2e93e855d9c 100644--- a/web/app/components/workflow/comment/mention-input.spec.tsx+++ b/web/app/components/workflow/comment/mention-input.spec.tsx@@ -1,8 +1,17 @@+import type { ReactElement } from 'react'import type { UserProfile } from '@/app/components/workflow/comment/types'-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, fireEvent, render as renderComponent, screen, waitFor } from '@testing-library/react'import { useState } from 'react'+import { EditorResourceScope } from '../editor-resource/provider'import { MentionInput } from './mention-input'+const render = (ui: ReactElement) =>+ renderComponent(+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>+ {ui}+ </EditorResourceScope>,+ )+const mockFetchMentionableUsers = vi.hoisted(() => vi.fn())const mockSetMentionableUsersLoading = vi.hoisted(() => vi.fn())const mockSetMentionableUsersCache = vi.hoisted(() => vi.fn())@@ -19,10 +28,6 @@ const mentionStoreState = vi.hoisted(() => ({mentionStoreState.mentionableUsersCache[appId] = users},}))-vi.mock('@/next/navigation', () => ({- useParams: () => ({ appId: 'app-1' }),-}))-vi.mock('@/service/console', () => ({consoleClient: {apps: {diff --git a/web/app/components/workflow/comment/mention-input.tsx b/web/app/components/workflow/comment/mention-input.tsxindex ab13b429665..b1a9ff2e9eb 100644--- a/web/app/components/workflow/comment/mention-input.tsx+++ b/web/app/components/workflow/comment/mention-input.tsx@@ -6,6 +6,7 @@ import { Avatar, AvatarFallback, AvatarImage } from '@langgenius/dify-ui/avatar'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useAtomValue } from 'jotai'import {forwardRef,memo,@@ -20,7 +21,7 @@ import {import { createPortal } from 'react-dom'import { useTranslation } from 'react-i18next'import Textarea from 'react-textarea-autosize'-import { useParams } from '@/next/navigation'+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'import { consoleClient } from '@/service/console'import { getAvatarInitial } from '@/utils/avatar'import { useStore, useWorkflowStore } from '../store'@@ -56,9 +57,8 @@ const MentionInputInner = forwardRef<HTMLTextAreaElement, MentionInputProps>(},forwardedRef,) => {- const params = useParams()const { t } = useTranslation(['common', 'workflowComments', 'workflowAgent'])- const appId = params.appId as string+ const appId = useAtomValue(editorAppIdAtom)const textareaRef = useRef<HTMLTextAreaElement>(null)const highlightContentRef = useRef<HTMLDivElement>(null)const actionContainerRef = useRef<HTMLDivElement | null>(null)diff --git a/web/app/components/workflow/comment/placement-preview.spec.tsx b/web/app/components/workflow/comment/placement-preview.spec.tsxindex aa45ea15116..2d91e902d19 100644--- a/web/app/components/workflow/comment/placement-preview.spec.tsx+++ b/web/app/components/workflow/comment/placement-preview.spec.tsx@@ -4,8 +4,6 @@ import userEvent from '@testing-library/user-event'import { renderWorkflowComponent } from '../__tests__/workflow-test-env'import { CommentPlacementPreview } from './placement-preview'-vi.mock('next/navigation', () => ({ useParams: () => ({ appId: 'app-1' }) }))-function renderPlacement(placing = true) {const onCancel = vi.fn()const result = renderWorkflowComponent(diff --git a/web/app/components/workflow/comment/reply-deletion.browser.spec.tsx b/web/app/components/workflow/comment/reply-deletion.browser.spec.tsxindex 704b63499ad..8914bc0bfd8 100644--- a/web/app/components/workflow/comment/reply-deletion.browser.spec.tsx+++ b/web/app/components/workflow/comment/reply-deletion.browser.spec.tsx@@ -3,9 +3,9 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { Suspense, useState } from 'react'import { page, userEvent } from 'vite-plus/test/browser'import { render } from 'vitest-browser-react'+import { EditorResourceScope } from '../editor-resource/provider'import { CommentThread } from './thread'-vi.mock('@/next/navigation', () => ({ useParams: () => ({ appId: 'app-1' }) }))vi.mock('reactflow', () => ({useReactFlow: () => ({ flowToScreenPosition: (position: { x: number; y: number }) => position }),useViewport: () => ({ x: 0, y: 0, zoom: 1 }),@@ -54,18 +54,20 @@ function Fixture({ onDelete }: { onDelete: (id: string) => void }) {)return (<QueryClientProvider client={queryClient}>- <Suspense fallback={<p>Loading profile</p>}>- <button type="button">Outside thread</button>- <div id="workflow-container" style={{ position: 'relative', width: 1000, height: 650 }}>- <CommentThread- comment={comment}- onClose={() => {}}- onReply={() => {}}- onReplyEdit={() => {}}- onReplyDeleteDirect={onDelete}- />- </div>- </Suspense>+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>+ <Suspense fallback={<p>Loading profile</p>}>+ <button type="button">Outside thread</button>+ <div id="workflow-container" style={{ position: 'relative', width: 1000, height: 650 }}>+ <CommentThread+ comment={comment}+ onClose={() => {}}+ onReply={() => {}}+ onReplyEdit={() => {}}+ onReplyDeleteDirect={onDelete}+ />+ </div>+ </Suspense>+ </EditorResourceScope></QueryClientProvider>)}diff --git a/web/app/components/workflow/comment/thread.spec.tsx b/web/app/components/workflow/comment/thread.spec.tsxindex c955415b3f4..51ecda037f4 100644--- a/web/app/components/workflow/comment/thread.spec.tsx+++ b/web/app/components/workflow/comment/thread.spec.tsx@@ -4,6 +4,7 @@ import { fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { createAccountProfileQueryWrapper } from '@/test/console/account-profile'import { render as renderWithConsoleState } from '@/test/console/render'+import { EditorResourceScope } from '../editor-resource/provider'import { CommentThread } from './thread'const mockSetCommentPreviewHovering = vi.hoisted(() => vi.fn())@@ -19,9 +20,14 @@ const mockConsoleState = vi.hoisted(() => ({}))const render = (ui: ReactElement) =>- renderWithConsoleState(ui, {- wrapper: createAccountProfileQueryWrapper(mockConsoleState.userProfile),- })+ renderWithConsoleState(+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>+ {ui}+ </EditorResourceScope>,+ {+ wrapper: createAccountProfileQueryWrapper(mockConsoleState.userProfile),+ },+ )const storeState = vi.hoisted(() => ({mentionableUsersCache: {@@ -32,10 +38,6 @@ const storeState = vi.hoisted(() => ({} as Record<string, Array<{ id: string; name: string; email: string; avatar_url: string }>>,setCommentPreviewHovering: (...args: unknown[]) => mockSetCommentPreviewHovering(...args),}))-vi.mock('@/next/navigation', () => ({- useParams: () => ({ appId: 'app-1' }),-}))-vi.mock('@/hooks/use-format-time-from-now', () => ({useFormatTimeFromNow: () => ({formatTimeFromNow: () => 'just now',diff --git a/web/app/components/workflow/comment/thread.tsx b/web/app/components/workflow/comment/thread.tsxindex a11bf428ad8..cac0974f962 100644--- a/web/app/components/workflow/comment/thread.tsx+++ b/web/app/components/workflow/comment/thread.tsx@@ -34,13 +34,14 @@ import {RiMoreFill,} from '@remixicon/react'import { useSuspenseQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { useReactFlow, useViewport } from 'reactflow'import { getUserColor } from '@/app/components/workflow/collaboration/utils/user-color'+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'import { userProfileQueryOptions } from '@/features/account-profile/client'import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'-import { useParams } from '@/next/navigation'import { getAvatarInitial } from '@/utils/avatar'import { useStore } from '../store'import { MentionInput } from './mention-input'@@ -197,8 +198,7 @@ function CommentThreadComponent({onReplyDelete,onReplyDeleteDirect,}: CommentThreadProps) {- const params = useParams()- const appId = params.appId as string+ const appId = useAtomValue(editorAppIdAtom)const { flowToScreenPosition } = useReactFlow()const viewport = useViewport()const { data: userProfile } = useSuspenseQuery({diff --git a/web/app/components/workflow/constants.ts b/web/app/components/workflow/constants.tsindex 6d1fd2745ac..04d2bc2b721 100644--- a/web/app/components/workflow/constants.ts+++ b/web/app/components/workflow/constants.ts@@ -32,10 +32,10 @@ export const isInWorkflowPage = () => {const pathname = globalThis.location.pathnamereturn /^\/app\/[^/]+\/workflow$/.test(pathname) || /^\/workflow\/[^/]+$/.test(pathname)}-export const getGlobalVars = (isChatMode: boolean): Var[] => {+export const getGlobalVars = (isChatflow: boolean): Var[] => {const isInWorkflow = isInWorkflowPage()const vars: Var[] = [- ...(isChatMode+ ...(isChatflow? [{variable: 'sys.dialogue_count',@@ -63,7 +63,7 @@ export const getGlobalVars = (isChatMode: boolean): Var[] => {variable: 'sys.workflow_run_id',type: VarType.string,},- ...(isInWorkflow && !isChatMode+ ...(isInWorkflow && !isChatflow? [{variable: 'sys.timestamp',diff --git a/web/app/components/workflow/editor-resource/__tests__/render.ts b/web/app/components/workflow/editor-resource/__tests__/render.tsnew file mode 100644index 00000000000..c68881da155--- /dev/null+++ b/web/app/components/workflow/editor-resource/__tests__/render.ts@@ -0,0 +1,66 @@+import type { RenderHookOptions, RenderOptions } from '@testing-library/react'+import type { ReactElement, ReactNode } from 'react'+import type { EditorResource } from '../resource'+import type { ConsoleQueryTestOptions } from '@/test/console/query-data'+import { useQueryClient } from '@tanstack/react-query'+import { createElement } from 'react'+import { consoleQuery } from '@/service/console'+import { createConsoleQueryWrapper, seedAppDetail } from '@/test/console/query-data'+import { QueryClientTestProvider } from '@/test/console/query-provider'+import { render, renderHook } from '@/test/console/render'+import { createAppDetailFixture } from '@/test/fixtures/app'+import { EditorResourceScope } from '../provider'++type ResourceOption = { resource?: EditorResource }++function createWrapper({+ resource = { kind: 'app', appId: 'app-1', mode: 'workflow' },+ wrapper: Wrapper,+ ...options+}: ResourceOption & ConsoleQueryTestOptions & Pick<RenderOptions, 'wrapper'>) {+ const { wrapper: ConsoleWrapper, ...query } = createConsoleQueryWrapper(options)+ function ResourceFixture({ children }: { children: ReactNode }) {+ const client = useQueryClient()+ if (+ resource.kind === 'app' &&+ !client.getQueryData(+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: resource.appId } } }),+ )+ )+ seedAppDetail(client, createAppDetailFixture({ id: resource.appId, mode: resource.mode }))+ return createElement(+ QueryClientTestProvider,+ { queryClient: client },+ createElement(EditorResourceScope, { resource, children }),+ )+ }+ function EditorWrapper({ children }: { children: ReactNode }) {+ const content = createElement(ResourceFixture, { children })+ return createElement(+ ConsoleWrapper,+ undefined,+ Wrapper ? createElement(Wrapper, undefined, content) : content,+ )+ }+ return { ...query, wrapper: EditorWrapper }+}++export function renderEditor(+ ui: ReactElement,+ { resource, wrapper, ...options }: RenderOptions & ConsoleQueryTestOptions & ResourceOption = {},+) {+ const { wrapper: EditorWrapper, ...query } = createWrapper({ ...options, resource, wrapper })+ return { ...render(ui, { ...options, wrapper: EditorWrapper }), ...query }+}++export function renderEditorHook<Result, Props = void>(+ callback: (props: Props) => Result,+ {+ resource,+ wrapper,+ ...options+ }: RenderHookOptions<Props> & ConsoleQueryTestOptions & ResourceOption = {},+) {+ const { wrapper: EditorWrapper, ...query } = createWrapper({ ...options, resource, wrapper })+ return { ...renderHook(callback, { ...options, wrapper: EditorWrapper }), ...query }+}diff --git a/web/app/components/workflow/editor-resource/__tests__/scope.spec.tsx b/web/app/components/workflow/editor-resource/__tests__/scope.spec.tsxnew file mode 100644index 00000000000..509d63acc95--- /dev/null+++ b/web/app/components/workflow/editor-resource/__tests__/scope.spec.tsx@@ -0,0 +1,163 @@+import { act, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { useAtomValue } from 'jotai'+import { useState } from 'react'+import { WorkflowContextProvider } from '@/app/components/workflow/context'+import { useStore } from '@/app/components/workflow/store'+import { consoleQuery } from '@/service/console'+import { createConsoleQueryClient, seedAppDetail } from '@/test/console/query-data'+import { QueryClientTestProvider } from '@/test/console/query-provider'+import { createAppDetailFixture } from '@/test/fixtures/app'+import { EditorResourceScope } from '../provider'+import { getEditorResourceId } from '../resource'+import { editorResourceAtom, isChatflowAtom } from '../state'+import { renderEditorHook } from './render'++function ResourceSummary({ label }: { label: string }) {+ const id = getEditorResourceId(useAtomValue(editorResourceAtom))+ const isChatflow = useAtomValue(isChatflowAtom)+ return <output aria-label={label}>{`${id}:${isChatflow ? 'chatflow' : 'other'}`}</output>+}++function EditorSession() {+ const [draft, setDraft] = useState('')+ const showPreview = useStore((state) => state.showDebugAndPreviewPanel)+ const setShowPreview = useStore((state) => state.setShowDebugAndPreviewPanel)++ return (+ <>+ <ResourceSummary label="Editor" />+ <input+ aria-label="Unsaved draft"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ />+ <button type="button" onClick={() => setShowPreview(true)}>+ Open preview+ </button>+ {showPreview && <section aria-label="Preview">Preview is open</section>}+ </>+ )+}++describe('workflow editor resource scope', () => {+ it('preserves shared App details when the editor unmounts after a failed background refresh', async () => {+ const queryClient = createConsoleQueryClient()+ const app = createAppDetailFixture({ id: 'app-1', mode: 'workflow', name: 'Workflow' })+ const queryKey = consoleQuery.apps.byAppId.get.queryKey({+ input: { params: { app_id: app.id } },+ })+ seedAppDetail(queryClient, app)+ const { unmount } = render(+ <QueryClientTestProvider queryClient={queryClient}>+ <EditorResourceScope resource={{ kind: 'app', appId: app.id, mode: 'workflow' }}>+ <ResourceSummary label="Editor" />+ </EditorResourceScope>+ </QueryClientTestProvider>,+ )+ const error = new Error('App detail refresh failed')+ await act(async () => {+ await expect(+ queryClient.query({ queryKey, staleTime: 0, queryFn: () => Promise.reject(error) }),+ ).rejects.toThrow(error)+ })+ expect(queryClient.getQueryState(queryKey)?.status).toBe('error')+ expect(screen.getByLabelText('Editor')).toHaveTextContent('app-1:other')++ unmount()++ expect(queryClient.getQueryData(queryKey)).toEqual(app)+ expect(queryClient.getQueryState(queryKey)?.status).toBe('error')+ })++ it('isolates simultaneous App editors with different modes alongside pipeline and snippet editors', () => {+ const queryClient = createConsoleQueryClient()+ seedAppDetail(+ queryClient,+ createAppDetailFixture({ id: 'app-1', mode: 'advanced-chat', name: 'Chatflow' }),+ )+ render(+ <QueryClientTestProvider queryClient={queryClient}>+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'advanced-chat' }}>+ <ResourceSummary label="App" />+ </EditorResourceScope>+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-2', mode: 'workflow' }}>+ <ResourceSummary label="Second App" />+ </EditorResourceScope>+ <EditorResourceScope resource={{ kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' }}>+ <ResourceSummary label="Pipeline" />+ </EditorResourceScope>+ <EditorResourceScope resource={{ kind: 'snippet', snippetId: 'snippet-1' }}>+ <ResourceSummary label="Snippet" />+ </EditorResourceScope>+ </QueryClientTestProvider>,+ )+ expect(screen.getByLabelText('App')).toHaveTextContent('app-1:chatflow')+ expect(screen.getByLabelText('Second App')).toHaveTextContent('app-2:other')+ expect(screen.getByLabelText('Pipeline')).toHaveTextContent('pipeline-1:other')+ expect(screen.getByLabelText('Snippet')).toHaveTextContent('snippet-1:other')+ })++ it('keeps the supplied resource mode independent of cached App details', () => {+ const queryClient = createConsoleQueryClient()+ const app = createAppDetailFixture({ id: 'app-1', mode: 'workflow' })+ seedAppDetail(queryClient, app)+ const resource = { kind: 'app', appId: app.id, mode: 'advanced-chat' } as const+ const { result } = renderEditorHook(() => useAtomValue(editorResourceAtom), {+ queryClient,+ resource,+ })+ expect(result.current).toEqual(resource)+ expect(+ queryClient.getQueryData(+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: app.id } } }),+ ),+ ).toEqual(app)+ })++ it('preserves the editor session when app facts refresh and resets it when the resource changes', async () => {+ const user = userEvent.setup()+ const queryClient = createConsoleQueryClient()+ seedAppDetail(+ queryClient,+ createAppDetailFixture({ id: 'app-1', mode: 'workflow', name: 'First' }),+ )+ seedAppDetail(+ queryClient,+ createAppDetailFixture({ id: 'app-2', mode: 'advanced-chat', name: 'Second' }),+ )+ const view = (appId: string) => (+ <QueryClientTestProvider queryClient={queryClient}>+ <EditorResourceScope+ resource={{ kind: 'app', appId, mode: appId === 'app-1' ? 'workflow' : 'advanced-chat' }}+ >+ <WorkflowContextProvider>+ <EditorSession />+ </WorkflowContextProvider>+ </EditorResourceScope>+ </QueryClientTestProvider>+ )+ const { rerender } = render(view('app-1'))++ await user.type(screen.getByRole('textbox', { name: 'Unsaved draft' }), 'Unpublished changes')+ await user.click(screen.getByRole('button', { name: 'Open preview' }))++ await act(async () => {+ seedAppDetail(+ queryClient,+ createAppDetailFixture({ id: 'app-1', mode: 'workflow', name: 'Renamed' }),+ )+ })+ await waitFor(() => expect(screen.getByLabelText('Editor')).toHaveTextContent('app-1:other'))+ rerender(view('app-1'))+ expect(screen.getByRole('textbox', { name: 'Unsaved draft' })).toHaveValue(+ 'Unpublished changes',+ )+ expect(screen.getByRole('region', { name: 'Preview' })).toBeVisible()++ rerender(view('app-2'))+ expect(screen.getByLabelText('Editor')).toHaveTextContent('app-2:chatflow')+ expect(screen.getByRole('textbox', { name: 'Unsaved draft' })).toHaveValue('')+ expect(screen.queryByRole('region', { name: 'Preview' })).not.toBeInTheDocument()+ })+})diff --git a/web/app/components/workflow/editor-resource/provider.tsx b/web/app/components/workflow/editor-resource/provider.tsxnew file mode 100644index 00000000000..ee0f51710fe--- /dev/null+++ b/web/app/components/workflow/editor-resource/provider.tsx@@ -0,0 +1,25 @@+'use client'++import type { ReactNode } from 'react'+import type { EditorResource } from './resource'+import { ScopeProvider } from 'jotai-scope'+import { getEditorResourceId } from './resource'+import { editorResourceAtom } from './state'++export function EditorResourceScope({+ resource,+ children,+}: {+ resource: EditorResource+ children: ReactNode+}) {+ return (+ <ScopeProvider+ key={`${resource.kind}:${getEditorResourceId(resource)}`}+ atoms={[[editorResourceAtom, resource]]}+ name="WorkflowEditor"+ >+ {children}+ </ScopeProvider>+ )+}diff --git a/web/app/components/workflow/editor-resource/resource.ts b/web/app/components/workflow/editor-resource/resource.tsnew file mode 100644index 00000000000..5ebeedb291e--- /dev/null+++ b/web/app/components/workflow/editor-resource/resource.ts@@ -0,0 +1,21 @@+import type { WorkflowAppMode } from '@/app/components/apps/app-type'++export type EditorResource =+ | Readonly<{ kind: 'app'; appId: string; mode: WorkflowAppMode }>+ | Readonly<{ kind: 'knowledge-pipeline'; pipelineId: string }>+ | Readonly<{ kind: 'snippet'; snippetId: string }>++export function getEditorResourceId(resource: EditorResource): string {+ switch (resource.kind) {+ case 'app':+ return resource.appId+ case 'knowledge-pipeline':+ return resource.pipelineId+ case 'snippet':+ return resource.snippetId+ }+}++export function isChatflow(resource: EditorResource): boolean {+ return resource.kind === 'app' && resource.mode === 'advanced-chat'+}diff --git a/web/app/components/workflow/editor-resource/state.ts b/web/app/components/workflow/editor-resource/state.tsnew file mode 100644index 00000000000..6dd538c8547--- /dev/null+++ b/web/app/components/workflow/editor-resource/state.ts@@ -0,0 +1,39 @@+import type { EditorResource } from './resource'+import { atom } from 'jotai'+import { atomWithLazy } from 'jotai/utils'+import { isChatflow } from './resource'++export const editorResourceAtom = atomWithLazy<EditorResource>(() => {+ throw new Error('EditorResourceScope is required for the workflow editor')+})++export const editorResourceKindAtom = atom((get) => get(editorResourceAtom).kind)+export const editorAppIdAtom = atom((get) => {+ const resource = get(editorResourceAtom)+ return resource.kind === 'app' ? resource.appId : undefined+})+export const editorPipelineIdAtom = atom((get) => {+ const resource = get(editorResourceAtom)+ return resource.kind === 'knowledge-pipeline' ? resource.pipelineId : undefined+})++export const isChatflowAtom = atom((get) => isChatflow(get(editorResourceAtom)))++export const workflowAppIdentityAtom = atom((get) => {+ const resource = get(editorResourceAtom)+ if (resource.kind !== 'app') throw new Error('This operation requires a workflow app editor')+ return resource+})++export const knowledgePipelineIdentityAtom = atom((get) => {+ const resource = get(editorResourceAtom)+ if (resource.kind !== 'knowledge-pipeline')+ throw new Error('This operation requires a knowledge pipeline editor')+ return resource+})++export const snippetIdentityAtom = atom((get) => {+ const resource = get(editorResourceAtom)+ if (resource.kind !== 'snippet') throw new Error('This operation requires a snippet editor')+ return resource+})diff --git a/web/app/components/workflow/features.tsx b/web/app/components/workflow/features.tsxindex 91150b44f88..bb91305ad0d 100644--- a/web/app/components/workflow/features.tsx+++ b/web/app/components/workflow/features.tsx@@ -2,21 +2,23 @@ import type { StartNodeType } from './nodes/start/types'import type { CommonNodeType, InputVar, Node } from './types'import type { PromptVariable } from '@/models/debug'import type { WorkflowDraftFeaturesPayload } from '@/service/workflow'+import { useAtomValue } from 'jotai'import { memo, useCallback } from 'react'import { useNodes } from 'reactflow'import { useFeaturesStore } from '@/app/components/base/features/hooks'import NewFeaturePanel from '@/app/components/base/features/new-feature-panel'import { webSocketClient } from '@/app/components/workflow/collaboration/core/websocket-manager'+import { editorAppIdAtom, isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { updateFeatures } from '@/service/workflow'-import { useIsChatMode, useNodesReadOnly } from './hooks/use-workflow'+import { useNodesReadOnly } from './hooks/use-workflow'import useConfig from './nodes/start/use-config'import { useStore } from './store'import { InputVarType } from './types'const Features = () => {const setShowFeaturesPanel = useStore((s) => s.setShowFeaturesPanel)- const appId = useStore((s) => s.appId)- const isChatMode = useIsChatMode()+ const appId = useAtomValue(editorAppIdAtom)+ const isChatflow = useAtomValue(isChatflowAtom)const { nodesReadOnly } = useNodesReadOnly()const featuresStore = useFeaturesStore()const nodes = useNodes<CommonNodeType>()@@ -81,7 +83,7 @@ const Features = () => {return (<NewFeaturePanelshow- isChatMode={isChatMode}+ isChatMode={isChatflow}disabled={nodesReadOnly}onChange={handleFeaturesChange}onClose={() => setShowFeaturesPanel(false)}diff --git a/web/app/components/workflow/header/__tests__/header-in-restoring.spec.tsx b/web/app/components/workflow/header/__tests__/header-in-restoring.spec.tsxindex 315b4f5bea0..f2c42b707a3 100644--- a/web/app/components/workflow/header/__tests__/header-in-restoring.spec.tsx+++ b/web/app/components/workflow/header/__tests__/header-in-restoring.spec.tsx@@ -8,7 +8,6 @@ import {seedFeatures,seedSystemFeatures,} from '@/test/console/query-data'-import { FlowType } from '@/types/common'import { renderWorkflowComponent as renderWorkflow } from '../../__tests__/workflow-test-env'import { WorkflowVersion } from '../../types'import HeaderInRestoring from '../header-in-restoring'@@ -40,7 +39,7 @@ vi.mock('@/hooks/use-format-time-from-now', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mockInvalidAllLastRun,+ useInvalidateAllLastRun: () => mockInvalidAllLastRun,useResetWorkflowVersionHistory: () => mockResetWorkflowVersionHistory,useRestoreWorkflow: () => ({mutateAsync: mockRestoreWorkflow,@@ -92,31 +91,12 @@ describe('HeaderInRestoring', () => {deploymentEdition = 'CLOUD'})- it('should disable restore when the flow id is not ready yet', () => {- renderWorkflowComponent(<HeaderInRestoring />, {- initialStoreState: {- currentVersion: createVersion(),- },- hooksStoreProps: {- configsMap: undefined,- },- })-- expect(screen.getByRole('button', { name: 'workflow.common.restore' })).toBeDisabled()- })-it('should enable restore when version and flow id are both ready', () => {renderWorkflowComponent(<HeaderInRestoring />, {initialStoreState: {currentVersion: createVersion(),},- hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: undefined as never,- fileSettings: {} as never,- },- },+ hooksStoreProps: {},})expect(screen.getByRole('button', { name: 'workflow.common.restore' })).toBeEnabled()@@ -129,12 +109,9 @@ describe('HeaderInRestoring', () => {version: WorkflowVersion.Draft,}),},+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},})@@ -147,12 +124,9 @@ describe('HeaderInRestoring', () => {initialStoreState: {currentVersion: createVersion(),},+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},})diff --git a/web/app/components/workflow/header/__tests__/header-layouts.spec.tsx b/web/app/components/workflow/header/__tests__/header-layouts.spec.tsxindex 08ad1a58dac..1e1b3bc2969 100644--- a/web/app/components/workflow/header/__tests__/header-layouts.spec.tsx+++ b/web/app/components/workflow/header/__tests__/header-layouts.spec.tsx@@ -2,7 +2,6 @@ import type { Shape } from '../../store/workflow'import { fireEvent, screen, waitFor } from '@testing-library/react'import { createAccountProfileQueryClient } from '@/test/console/account-profile'import { seedSystemFeatures } from '@/test/console/query-data'-import { FlowType } from '@/types/common'import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'import { WorkflowVersion } from '../../types'import HeaderInNormal from '../header-in-normal'@@ -71,7 +70,7 @@ vi.mock('@/hooks/use-theme', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mockInvalidAllLastRun,+ useInvalidateAllLastRun: () => mockInvalidAllLastRun,useResetWorkflowVersionHistory: () => mockResetWorkflowVersionHistory,useRestoreWorkflow: () => ({mutateAsync: mockRestoreWorkflow,@@ -269,12 +268,9 @@ describe('Header layout components', () => {isRestoring: true,showWorkflowVersionHistoryPanel: true,},+ resource: { kind: 'app' as const, appId: 'flow-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowType: FlowType.appFlow,- flowId: 'flow-1',- fileSettings: {},- },+ fileSettings: {},},})@@ -303,12 +299,9 @@ describe('Header layout components', () => {currentVersion,deleteAllInspectVars,},+ resource: { kind: 'app' as const, appId: 'flow-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowType: FlowType.appFlow,- flowId: 'flow-1',- fileSettings: {},- },+ fileSettings: {},},queryClient,},@@ -317,7 +310,7 @@ describe('Header layout components', () => {fireEvent.click(screen.getByRole('button', { name: 'workflow.common.restore' }))await waitFor(() => {- expect(mockRestoreWorkflow).toHaveBeenCalledWith('/apps/flow-1/workflows/version-1/restore')+ expect(mockRestoreWorkflow).toHaveBeenCalledWith('version-1')expect(store.getState().showWorkflowVersionHistoryPanel).toBe(false)expect(store.getState().isRestoring).toBe(false)expect(store.getState().backupDraft).toBeUndefined()@@ -354,21 +347,16 @@ describe('Header layout components', () => {backupDraft: createBackupDraft(),currentVersion,},+ resource: { kind: 'knowledge-pipeline' as const, pipelineId: 'pipeline-1' },hooksStoreProps: {- configsMap: {- flowType: FlowType.ragPipeline,- flowId: 'pipeline-1',- fileSettings: {},- },+ fileSettings: {},},})fireEvent.click(screen.getByRole('button', { name: 'workflow.common.restore' }))await waitFor(() => {- expect(mockRestoreWorkflow).toHaveBeenCalledWith(- '/rag/pipelines/pipeline-1/workflows/version-1/restore',- )+ expect(mockRestoreWorkflow).toHaveBeenCalledWith('version-1')expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalledTimes(1)})expect(mockEmitRestoreIntent).not.toHaveBeenCalled()@@ -386,21 +374,16 @@ describe('Header layout components', () => {backupDraft: createBackupDraft(),currentVersion,},+ resource: { kind: 'snippet' as const, snippetId: 'snippet-1' },hooksStoreProps: {- configsMap: {- flowType: FlowType.snippet,- flowId: 'snippet-1',- fileSettings: {},- },+ fileSettings: {},},})fireEvent.click(screen.getByRole('button', { name: 'workflow.common.restore' }))await waitFor(() => {- expect(mockRestoreWorkflow).toHaveBeenCalledWith(- '/snippets/snippet-1/workflows/version-1/restore',- )+ expect(mockRestoreWorkflow).toHaveBeenCalledWith('version-1')expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalledTimes(1)})expect(mockEmitRestoreIntent).not.toHaveBeenCalled()diff --git a/web/app/components/workflow/header/__tests__/running-title.spec.tsx b/web/app/components/workflow/header/__tests__/running-title.spec.tsxindex bdc62573a2c..aff8025c396 100644--- a/web/app/components/workflow/header/__tests__/running-title.spec.tsx+++ b/web/app/components/workflow/header/__tests__/running-title.spec.tsx@@ -4,9 +4,7 @@ import RunningTitle from '../running-title'let mockIsChatMode = falseconst mockFormatWorkflowRunIdentifier = vi.fn()-vi.mock('../../hooks/use-workflow', () => ({- useIsChatMode: () => mockIsChatMode,-}))+vi.mock('../../hooks/use-workflow', () => ({}))vi.mock('../../utils', () => ({formatWorkflowRunIdentifier: (finishedAt?: number) => mockFormatWorkflowRunIdentifier(finishedAt),@@ -59,3 +57,10 @@ describe('RunningTitle', () => {expect(container).toHaveTextContent('Test Run (14:30:25)')})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockIsChatMode) }+})diff --git a/web/app/components/workflow/header/__tests__/view-history.spec.tsx b/web/app/components/workflow/header/__tests__/view-history.spec.tsxindex 4674bef1111..a51e96d952b 100644--- a/web/app/components/workflow/header/__tests__/view-history.spec.tsx+++ b/web/app/components/workflow/header/__tests__/view-history.spec.tsx@@ -17,9 +17,7 @@ const mockFormatWorkflowRunIdentifier = vi.fn(let mockIsChatMode = false-vi.mock('../../hooks/use-workflow', () => ({- useIsChatMode: () => mockIsChatMode,-}))+vi.mock('../../hooks/use-workflow', () => ({}))vi.mock('../../hooks/use-nodes-interactions', () => ({useNodesInteractions: () => ({@@ -256,3 +254,10 @@ describe('ViewHistory', () => {expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockIsChatMode) }+})diff --git a/web/app/components/workflow/header/checklist/__tests__/index.spec.tsx b/web/app/components/workflow/header/checklist/__tests__/index.spec.tsxindex 4cdef83f1a1..fa9f29bb3eb 100644--- a/web/app/components/workflow/header/checklist/__tests__/index.spec.tsx+++ b/web/app/components/workflow/header/checklist/__tests__/index.spec.tsx@@ -1,6 +1,7 @@import type { ChecklistItem } from '../../../hooks/use-checklist'-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum } from '../../../types'import WorkflowChecklist from '../index'@@ -56,10 +57,10 @@ vi.mock('../../../store', () => ({}))vi.mock('../../../hooks-store/store', () => ({- useHooksStore: (selector: (state: { configsMap: { flowType: string } }) => unknown) =>+ useHooksStore: (selector: (state: { configsMap: { resourceKind: string } }) => unknown) =>selector({configsMap: {- flowType: 'workflow',+ resourceKind: 'workflow',},}),}))@@ -109,7 +110,9 @@ describe('WorkflowChecklist', () => {it('should split checklist items into plugin and node groups and delegate clicks to node selection by default', async () => {const user = userEvent.setup()- render(<WorkflowChecklist disabled={false} />)+ render(<WorkflowChecklist disabled={false} />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })expect(screen.getByText('2')).toBeInTheDocument()await user.click(screen.getByRole('button', { name: 'workflow.panel.checklist 2' }))@@ -123,7 +126,9 @@ describe('WorkflowChecklist', () => {it('should use the custom item click handler when provided', async () => {const user = userEvent.setup()const onItemClick = vi.fn()- render(<WorkflowChecklist disabled={false} onItemClick={onItemClick} />)+ render(<WorkflowChecklist disabled={false} onItemClick={onItemClick} />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await user.click(screen.getByRole('button', { name: 'workflow.panel.checklist 2' }))await user.click(screen.getByTestId('node-group-Broken Node'))@@ -134,7 +139,9 @@ describe('WorkflowChecklist', () => {it('should show the tooltip without replacing the warning count in the accessible name', async () => {const user = userEvent.setup()- render(<WorkflowChecklist disabled={false} />)+ render(<WorkflowChecklist disabled={false} />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })const trigger = screen.getByRole('button', { name: 'workflow.panel.checklist 2' })await user.hover(trigger)@@ -153,7 +160,9 @@ describe('WorkflowChecklist', () => {title: 'Inline Agent',openInlineAgentPanel: true,}- render(<WorkflowChecklist disabled={false} />)+ render(<WorkflowChecklist disabled={false} />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await user.click(screen.getByRole('button', { name: 'workflow.panel.checklist 2' }))await user.click(screen.getByTestId('node-group-Inline Agent'))@@ -166,14 +175,18 @@ describe('WorkflowChecklist', () => {const user = userEvent.setup()mockChecklistItems = []- render(<WorkflowChecklist disabled={false} />)+ render(<WorkflowChecklist disabled={false} />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await user.click(screen.getByRole('button', { name: 'workflow.panel.checklist' }))expect(screen.getByText(/checklistResolved/i)).toBeInTheDocument()})it('should ignore popover open changes when the checklist is disabled', () => {- render(<WorkflowChecklist disabled={true} />)+ render(<WorkflowChecklist disabled={true} />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })expect(screen.getByText('2').closest('button')).toBeDisabled()})diff --git a/web/app/components/workflow/header/checklist/index.tsx b/web/app/components/workflow/header/checklist/index.tsxindex 2b96fdda4c9..a0395f53a2b 100644--- a/web/app/components/workflow/header/checklist/index.tsx+++ b/web/app/components/workflow/header/checklist/index.tsx@@ -15,7 +15,6 @@ import { memo, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { useEdges } from 'reactflow'import useNodes from '@/app/components/workflow/store/workflow/use-nodes'-import { useHooksStore } from '../../hooks-store/store'import { useChecklist } from '../../hooks/use-checklist'import { useNodesInteractions } from '../../hooks/use-nodes-interactions'import { useStore } from '../../store'@@ -33,8 +32,7 @@ const WorkflowChecklist = ({ disabled, showGoTo = true, onItemClick }: WorkflowCconst [open, setOpen] = useState(false)const edges = useEdges<CommonEdgeType>()const nodes = useNodes()- const flowType = useHooksStore((s) => s.configsMap?.flowType)- const needWarningNodes = useChecklist(nodes, edges, { flowType })+ const needWarningNodes = useChecklist(nodes, edges)const { handleNodeSelect } = useNodesInteractions()const setOpenInlineAgentPanelNodeId = useStore((state) => state.setOpenInlineAgentPanelNodeId)const checklistLabel = t(($) => $['panel.checklist'], { ns: 'workflow' })diff --git a/web/app/components/workflow/header/header-in-restoring.tsx b/web/app/components/workflow/header/header-in-restoring.tsxindex 4085eec3bb8..f4bcf577fd3 100644--- a/web/app/components/workflow/header/header-in-restoring.tsx+++ b/web/app/components/workflow/header/header-in-restoring.tsx@@ -6,6 +6,8 @@ import { useAtomValue } from 'jotai'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import { PlanUpgradeModal } from '@/app/components/billing/plan-upgrade-modal'+import { getEditorResourceId } from '@/app/components/workflow/editor-resource/resource'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import { getWorkflowVersionName } from '@/app/components/workflow/utils/version'import { toast } from '@/app/notifications'import { userProfileQueryOptions } from '@/features/account-profile/client'@@ -13,12 +15,10 @@ import { deploymentEditionAtom } from '@/features/system-features/state'import useTheme from '@/hooks/use-theme'import { consoleQuery } from '@/service/console'import {- useInvalidAllLastRun,+ useInvalidateAllLastRun,useResetWorkflowVersionHistory,useRestoreWorkflow,} from '@/service/use-workflow'-import { FlowType } from '@/types/common'-import { useHooksStore } from '../hooks-store'import { useWorkflowRefreshDraft } from '../hooks/use-workflow-refresh-draft'import { useWorkflowRun } from '../hooks/use-workflow-run'import { useStore, useWorkflowStore } from '../store'@@ -44,20 +44,21 @@ const HeaderInRestoring = ({ onRestoreSettled }: HeaderInRestoringProps) => {...userProfileQueryOptions(),select: (data) => data.profile,})- const configsMap = useHooksStore((s) => s.configsMap)- const invalidAllLastRun = useInvalidAllLastRun(configsMap?.flowType, configsMap?.flowId)+ const resource = useAtomValue(editorResourceAtom)+ const resourceId = getEditorResourceId(resource)+ const invalidAllLastRun = useInvalidateAllLastRun(resource)const { deleteAllInspectVars } = workflowStore.getState()const currentVersion = useStore((s) => s.currentVersion)const setShowWorkflowVersionHistoryPanel = useStore((s) => s.setShowWorkflowVersionHistoryPanel)const { handleLoadBackupDraft } = useWorkflowRun()const { handleRefreshWorkflowDraft } = useWorkflowRefreshDraft()- const { mutateAsync: restoreWorkflow } = useRestoreWorkflow()+ const { mutateAsync: restoreWorkflow } = useRestoreWorkflow(resource)const resetWorkflowVersionHistory = useResetWorkflowVersionHistory()const canRestore =- !!currentVersion?.id && !!configsMap?.flowId && currentVersion.version !== WorkflowVersion.Draft+ !!currentVersion?.id && !!resourceId && currentVersion.version !== WorkflowVersion.Draftconst isPlanUnavailable = deploymentEdition === 'CLOUD' && plan === undefined- const canEmitCollaborationEvents = configsMap?.flowType === FlowType.appFlow+ const canEmitCollaborationEvents = resource.kind === 'app'const handleCancelRestore = useCallback(() => {handleLoadBackupDraft()@@ -65,18 +66,6 @@ const HeaderInRestoring = ({ onRestoreSettled }: HeaderInRestoringProps) => {setShowWorkflowVersionHistoryPanel(false)}, [workflowStore, handleLoadBackupDraft, setShowWorkflowVersionHistoryPanel])- const restoreVersionUrl = useCallback(- (versionId: string) => {- if (!configsMap?.flowId) return ''- if (configsMap.flowType === FlowType.ragPipeline)- return `/rag/pipelines/${configsMap.flowId}/workflows/${versionId}/restore`- if (configsMap.flowType === FlowType.snippet)- return `/snippets/${configsMap.flowId}/workflows/${versionId}/restore`- return `/apps/${configsMap.flowId}/workflows/${versionId}/restore`- },- [configsMap?.flowId, configsMap?.flowType],- )-const emitRestoreIntent = useCallback(async () => {if (!currentVersion || !canEmitCollaborationEvents) returntry {@@ -113,14 +102,14 @@ const HeaderInRestoring = ({ onRestoreSettled }: HeaderInRestoringProps) => {)const emitWorkflowUpdate = useCallback(async () => {- if (!configsMap?.flowId || !canEmitCollaborationEvents) return+ if (!resourceId || !canEmitCollaborationEvents) returntry {const { collaborationManager } = await import('../collaboration/core/collaboration-manager')- collaborationManager.emitWorkflowUpdate(configsMap.flowId)+ collaborationManager.emitWorkflowUpdate(resourceId)} catch (error) {console.error('Failed to emit workflow update:', error)}- }, [canEmitCollaborationEvents, configsMap?.flowId])+ }, [canEmitCollaborationEvents, resourceId])const handleRestore = useCallback(async () => {if (isPlanUnavailable || !canRestore || !currentVersion) return@@ -134,7 +123,7 @@ const HeaderInRestoring = ({ onRestoreSettled }: HeaderInRestoringProps) => {await emitRestoreIntent()try {- await restoreWorkflow(restoreVersionUrl(currentVersion.id))+ await restoreWorkflow(currentVersion.id)workflowStore.setState({ isRestoring: false })workflowStore.setState({ backupDraft: undefined })handleRefreshWorkflowDraft()@@ -159,7 +148,6 @@ const HeaderInRestoring = ({ onRestoreSettled }: HeaderInRestoringProps) => {setShowWorkflowVersionHistoryPanel,emitRestoreIntent,restoreWorkflow,- restoreVersionUrl,workflowStore,handleRefreshWorkflowDraft,t,diff --git a/web/app/components/workflow/header/online-users.tsx b/web/app/components/workflow/header/online-users.tsxindex b56e12cd8c0..40aaa09281f 100644--- a/web/app/components/workflow/header/online-users.tsx+++ b/web/app/components/workflow/header/online-users.tsx@@ -7,16 +7,17 @@ import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { useSuspenseQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import { useReactFlow } from 'reactflow'+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'import { userProfileQueryOptions } from '@/features/account-profile/client'import { getAvatar } from '@/service/common'import { getAvatarInitial } from '@/utils/avatar'import { useCollaboration } from '../collaboration/hooks/use-collaboration'import { getUserColor } from '../collaboration/utils/user-color'import { useHooksStore } from '../hooks-store'-import { useStore } from '../store'const useAvatarUrls = (users: OnlineUser[]) => {const [avatarUrls, setAvatarUrls] = useState<Record<string, string>>({})@@ -50,13 +51,13 @@ const useAvatarUrls = (users: OnlineUser[]) => {const OnlineUsers = () => {const { t } = useTranslation(['workspaceMembers', 'workflowComments'])- const appId = useStore((s) => s.appId)+ const appId = useAtomValue(editorAppIdAtom)const canEdit = useHooksStore((s) => s.accessControl.canEdit)const {onlineUsers,cursors,isEnabled: isCollaborationEnabled,- } = useCollaboration(appId as string, canEdit)+ } = useCollaboration(appId, canEdit)const { data: currentUserId } = useSuspenseQuery({...userProfileQueryOptions(),select: (data) => data.profile.id,diff --git a/web/app/components/workflow/header/running-title.tsx b/web/app/components/workflow/header/running-title.tsxindex 6ce99e1b2b5..d05ac1f5afa 100644--- a/web/app/components/workflow/header/running-title.tsx+++ b/web/app/components/workflow/header/running-title.tsx@@ -1,12 +1,13 @@+import { useAtomValue } from 'jotai'import { memo } from 'react'import { useTranslation } from 'react-i18next'-import { useIsChatMode } from '../hooks/use-workflow'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { useStore } from '../store'import { formatWorkflowRunIdentifier } from '../utils'const RunningTitle = () => {- const { t } = useTranslation(['workflow'])- const isChatMode = useIsChatMode()+ const { t } = useTranslation(['workflow'] as const)+ const isChatflow = useAtomValue(isChatflowAtom)const historyWorkflowData = useStore((s) => s.historyWorkflowData)return (@@ -16,7 +17,7 @@ const RunningTitle = () => {className="mr-1 i-custom-vender-line-time-clock-play size-3 text-gray-500"/><span>- {isChatMode+ {isChatflow? `Test Chat${formatWorkflowRunIdentifier(historyWorkflowData?.finished_at)}`: `Test Run${formatWorkflowRunIdentifier(historyWorkflowData?.finished_at)}`}</span>diff --git a/web/app/components/workflow/header/view-history.tsx b/web/app/components/workflow/header/view-history.tsxindex 26527f982dd..dd0930f62de 100644--- a/web/app/components/workflow/header/view-history.tsx+++ b/web/app/components/workflow/header/view-history.tsx@@ -1,15 +1,16 @@import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { useAtomValue } from 'jotai'import { memo, useState } from 'react'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { useInputFieldPanel } from '@/app/components/rag-pipeline/hooks/use-input-field-panel'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { useStore, useWorkflowStore } from '@/app/components/workflow/store'import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'import { useWorkflowRunHistory } from '@/service/use-workflow'import { useNodesInteractions } from '../hooks/use-nodes-interactions'-import { useIsChatMode } from '../hooks/use-workflow'import { useWorkflowInteractions } from '../hooks/use-workflow-panel-interactions'import { useWorkflowRun } from '../hooks/use-workflow-run'import { ControlMode, WorkflowRunningStatus } from '../types'@@ -22,7 +23,7 @@ export type ViewHistoryProps = {}const ViewHistory = ({ withText, onClearLogAndMessageModal, historyUrl }: ViewHistoryProps) => {const { t } = useTranslation(['common', 'workflow'])- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const [open, setOpen] = useState(false)const { formatTimeFromNow } = useFormatTimeFromNow()const { handleNodesCancelSelected } = useNodesInteractions()@@ -145,13 +146,13 @@ const ViewHistory = ({ withText, onClearLogAndMessageModal, historyUrl }: ViewHisetControlMode(ControlMode.Hand)}}>- {!isChatMode && interruptedStatuses.includes(item.status) && (+ {!isChatflow && interruptedStatuses.includes(item.status) && (<span className="mt-0.5 mr-1.5 i-custom-vender-line-alertsAndFeedback-alert-triangle h-3.5 w-3.5 text-[#F79009]" />)}- {!isChatMode && item.status === WorkflowRunningStatus.Failed && (+ {!isChatflow && item.status === WorkflowRunningStatus.Failed && (<span className="mt-0.5 mr-1.5 i-ri-error-warning-line h-3.5 w-3.5 text-[#F04438]" />)}- {!isChatMode && item.status === WorkflowRunningStatus.Succeeded && (+ {!isChatflow && item.status === WorkflowRunningStatus.Succeeded && (<span className="mt-0.5 mr-1.5 i-ri-checkbox-circle-line h-3.5 w-3.5 text-[#12B76A]" />)}<div>@@ -161,7 +162,7 @@ const ViewHistory = ({ withText, onClearLogAndMessageModal, historyUrl }: ViewHiitem.id === historyWorkflowData?.id && 'text-text-accent',)}>- {`Test ${isChatMode ? 'Chat' : 'Run'}${formatWorkflowRunIdentifier(item.finished_at, item.status)}`}+ {`Test ${isChatflow ? 'Chat' : 'Run'}${formatWorkflowRunIdentifier(item.finished_at, item.status)}`}</div><div className="flex items-center text-xs leading-4.5 text-text-tertiary">{item.created_by_account?.name} ·diff --git a/web/app/components/workflow/hooks-store/provider.tsx b/web/app/components/workflow/hooks-store/provider.tsxindex bf3b552bf0e..fc7e5193595 100644--- a/web/app/components/workflow/hooks-store/provider.tsx+++ b/web/app/components/workflow/hooks-store/provider.tsx@@ -15,7 +15,13 @@ export const HooksStoreContextProvider = ({const [store] = useState(() => createHooksStore(restProps))const d3Selection = useStore((s) => s.d3Selection)const d3Zoom = useStore((s) => s.d3Zoom)- const { accessControl, exportCheck, handleExportDSL, isExporting = false } = restProps+ const {+ fileSettings,+ accessControl,+ exportCheck,+ handleExportDSL,+ isExporting = false,+ } = restPropsuseEffect(() => {if (d3Selection && d3Zoom) store.getState().refreshAll(restProps)@@ -27,8 +33,9 @@ export const HooksStoreContextProvider = ({...(exportCheck && { exportCheck }),...(handleExportDSL && { handleExportDSL }),isExporting,+ fileSettings,})- }, [accessControl, exportCheck, handleExportDSL, isExporting, store])+ }, [fileSettings, accessControl, exportCheck, handleExportDSL, isExporting, store])return <HooksStoreContext.Provider value={store}>{children}</HooksStoreContext.Provider>}diff --git a/web/app/components/workflow/hooks-store/store.ts b/web/app/components/workflow/hooks-store/store.tsindex 1ac58ab4ce5..dbaec1ca49e 100644--- a/web/app/components/workflow/hooks-store/store.ts+++ b/web/app/components/workflow/hooks-store/store.ts@@ -9,7 +9,6 @@ import type {import type { IOtherOptions } from '@/service/base'import type { SchemaTypeDefinition } from '@/service/use-common'import type { EnvironmentVariablePatch } from '@/service/workflow'-import type { FlowType } from '@/types/common'import type { VarInInspect } from '@/types/workflow'import { noop } from 'es-toolkit/function'import { use } from 'react'@@ -105,11 +104,7 @@ type CommonHooksFnMap = {resetConversationVar: (varId: string) => Promise<void>invalidateConversationVarValues: () => voidaccessControl: WorkflowAccessControl- configsMap?: {- flowId: string- flowType: FlowType- fileSettings: FileUpload- }+ fileSettings?: FileUpload}export type Shape = {@@ -157,7 +152,7 @@ export const createHooksStore = ({invalidateSysVarValues = noop,resetConversationVar = async () => noop(),invalidateConversationVarValues = noop,- configsMap,+ fileSettings,accessControl = fullWorkflowAccessControl,}: Partial<Shape>) => {return createStore<Shape>((set) => ({@@ -197,7 +192,7 @@ export const createHooksStore = ({invalidateSysVarValues,resetConversationVar,invalidateConversationVarValues,- configsMap,+ fileSettings,accessControl,}))}diff --git a/web/app/components/workflow/hooks/__tests__/use-auto-generate-webhook-url.spec.ts b/web/app/components/workflow/hooks/__tests__/use-auto-generate-webhook-url.spec.tsindex 6de78fb9557..0d859832e4d 100644--- a/web/app/components/workflow/hooks/__tests__/use-auto-generate-webhook-url.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-auto-generate-webhook-url.spec.ts@@ -1,8 +1,15 @@+import type { EditorResource } from '../../editor-resource/resource'import type { Node } from '../../types'-import { act, waitFor } from '@testing-library/react'+import { act, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { createElement } from 'react'import { useNodes } from 'reactflow'import { createNode } from '../../__tests__/fixtures'-import { renderWorkflowFlowHook } from '../../__tests__/workflow-test-env'+import {+ renderWorkflowFlowComponent,+ renderWorkflowFlowHook,+} from '../../__tests__/workflow-test-env'+import { EditorResourceScope } from '../../editor-resource/provider'import { BlockEnum } from '../../types'import { useAutoGenerateWebhookUrl } from '../use-auto-generate-webhook-url'@@ -13,14 +20,8 @@ type WebhookFlowNode = Node & {}}-const routeParams = vi.hoisted(() => ({ appId: 'app-123' as string | undefined }))const mockRequest = vi.hoisted(() => vi.fn())-vi.mock('@/next/navigation', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/next/navigation')>()),- useParams: () => routeParams,-}))-vi.mock('@/service/console/browser', () => ({consoleBrowserLink: { call: mockRequest },}))@@ -45,13 +46,13 @@ describe('useAutoGenerateWebhookUrl', () => {nodes: useNodes<WebhookFlowNode>(),}),{+ resource: { kind: 'app', appId: 'app-123', mode: 'workflow' },nodes: createFlowNodes(),edges: [],},)beforeEach(() => {- routeParams.appId = 'app-123'mockRequest.mockReset()})@@ -82,29 +83,43 @@ describe('useAutoGenerateWebhookUrl', () => {})})- it('uses the current route after switching apps and skips routes without an app', async () => {- routeParams.appId = undefined- const { result, rerender } = renderAutoGenerateWebhookUrlHook()-- await act(async () => {- await result.current.autoGenerateWebhookUrl('webhook-1')- })+ it('uses the scoped app after switching resources and skips snippets', async () => {+ const user = userEvent.setup()+ function GenerateButton() {+ const generate = useAutoGenerateWebhookUrl()+ return createElement(+ 'button',+ { type: 'button', onClick: () => generate('webhook-1') },+ 'Generate URL',+ )+ }+ const view = (identity: EditorResource) =>+ createElement(EditorResourceScope, {+ resource: identity,+ children: createElement(GenerateButton),+ })+ const { rerender } = renderWorkflowFlowComponent(+ view({ kind: 'snippet', snippetId: 'snippet-1' }),+ {+ nodes: createFlowNodes(),+ edges: [],+ },+ )+ await user.click(screen.getByRole('button', { name: 'Generate URL' }))expect(mockRequest).not.toHaveBeenCalled()- routeParams.appId = 'app-456'- rerender()mockRequest.mockResolvedValue({webhook_url: 'https://example.com/other-webhook',webhook_debug_url: 'https://example.com/other-debug',})- await act(async () => {- await result.current.autoGenerateWebhookUrl('webhook-1')- })-- expect(mockRequest).toHaveBeenCalledWith(- ['apps', 'byAppId', 'workflows', 'triggers', 'webhook', 'get'],- { params: { app_id: 'app-456' }, query: { node_id: 'webhook-1' } },- expect.any(Object),+ rerender(view({ kind: 'app', appId: 'app-456', mode: 'workflow' }))+ await user.click(screen.getByRole('button', { name: 'Generate URL' }))+ await waitFor(() =>+ expect(mockRequest).toHaveBeenCalledWith(+ ['apps', 'byAppId', 'workflows', 'triggers', 'webhook', 'get'],+ { params: { app_id: 'app-456' }, query: { node_id: 'webhook-1' } },+ expect.any(Object),+ ),)})diff --git a/web/app/components/workflow/hooks/__tests__/use-checklist.spec.ts b/web/app/components/workflow/hooks/__tests__/use-checklist.spec.tsindex 054a4d6d729..be597ff9f66 100644--- a/web/app/components/workflow/hooks/__tests__/use-checklist.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-checklist.spec.ts@@ -14,8 +14,6 @@ import { createElement, Fragment } from 'react'import { CollectionType } from '@/app/components/tools/types'import { consoleQuery } from '@/service/console'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import { createEdge, createNode, resetFixtureCounters } from '../../__tests__/fixtures'import { resetReactFlowMockState, rfState } from '../../__tests__/reactflow-mock-state'import { renderWorkflowComponent, renderWorkflowHook } from '../../__tests__/workflow-test-env'@@ -323,12 +321,9 @@ function buildInlineAgentGraph({nodes: [startNode, agentNode],options: {queryClient,+ resource: { kind: 'app' as const, appId, mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: appId,- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},},}@@ -555,14 +550,14 @@ describe('useChecklist', () => {const edges = [createEdge({ source: 'start', target: 'llm' })]- renderWorkflowHook(() =>- useChecklist([startNode, llmNode], edges, { flowType: FlowType.snippet }),- )+ renderWorkflowHook(() => useChecklist([startNode, llmNode], edges), {+ resource: { kind: 'snippet', snippetId: 'snippet-1' },+ })expect(checkValid).toHaveBeenCalledWith(expect.objectContaining({ type: BlockEnum.LLM }),expect.any(Function),- expect.objectContaining({ flowType: FlowType.snippet }),+ expect.objectContaining({ resourceKind: 'snippet' }),)})@@ -863,7 +858,7 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {select?: (data: AppDetailWithSite) => unknown}) => {if (options.queryKey[0].join('.') === 'console.apps.byAppId.get') {- const appDetail = createAppDetailFixture({ mode: AppModeEnum.WORKFLOW })+ const appDetail = createAppDetailFixture({ mode: 'workflow' as const })return { data: options.select ? options.select(appDetail) : appDetail }}if (options.queryKey[0].includes('modelProviders') && options.queryKey[0].includes('summary'))diff --git a/web/app/components/workflow/hooks/__tests__/use-config-vision.spec.ts b/web/app/components/workflow/hooks/__tests__/use-config-vision.spec.tsindex 6670bd68d4e..16a222e8487 100644--- a/web/app/components/workflow/hooks/__tests__/use-config-vision.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-config-vision.spec.ts@@ -12,9 +12,7 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', ()mockUseTextGenerationCurrentProviderAndModelAndModelList(...args),}))-vi.mock('../use-workflow', () => ({- useIsChatMode: () => mockUseIsChatMode(),-}))+vi.mock('../use-workflow', () => ({}))const createModel = (overrides: Partial<ModelConfig> = {}): ModelConfig => ({provider: 'openai',@@ -181,3 +179,10 @@ describe('useConfigVision', () => {})})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/hooks/__tests__/use-fetch-workflow-inspect-vars.spec.ts b/web/app/components/workflow/hooks/__tests__/use-fetch-workflow-inspect-vars.spec.tsindex 553dc9f224f..624a6cecb8c 100644--- a/web/app/components/workflow/hooks/__tests__/use-fetch-workflow-inspect-vars.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-fetch-workflow-inspect-vars.spec.ts@@ -1,7 +1,6 @@import type { SchemaTypeDefinition } from '@/service/use-common'import type { VarInInspect } from '@/types/workflow'import { act, waitFor } from '@testing-library/react'-import { FlowType } from '@/types/common'import { createNode } from '../../__tests__/fixtures'import { resetReactFlowMockState, rfState } from '../../__tests__/reactflow-mock-state'import { renderWorkflowHook } from '../../__tests__/workflow-test-env'@@ -110,18 +109,11 @@ describe('use-fetch-workflow-inspect-vars', () => {}),])- const { result, store } = renderWorkflowHook(- () =>- useSetWorkflowVarsWithValue({- flowType: FlowType.appFlow,- flowId: 'flow-1',- }),- {- initialStoreState: {- dataSourceList: [],- },+ const { result, store } = renderWorkflowHook(() => useSetWorkflowVarsWithValue(), {+ initialStoreState: {+ dataSourceList: [],},- )+ })await act(async () => {await result.current.fetchInspectVars({})@@ -129,7 +121,11 @@ describe('use-fetch-workflow-inspect-vars', () => {expect(mockInvalidateConversationVarValues).toHaveBeenCalledTimes(1)expect(mockInvalidateSysVarValues).toHaveBeenCalledTimes(1)- expect(mockFetchAllInspectVars).toHaveBeenCalledWith(FlowType.appFlow, 'flow-1')+ expect(mockFetchAllInspectVars).toHaveBeenCalledWith({+ kind: 'app',+ appId: 'app-1',+ mode: 'workflow',+ })expect(mockHandleCancelAllNodeSuccessStatus).toHaveBeenCalledTimes(1)expect(store.getState().nodesWithInspectVars).toEqual([expect.objectContaining({@@ -163,18 +159,11 @@ describe('use-fetch-workflow-inspect-vars', () => {dataSourceList: [],}- const { result, store } = renderWorkflowHook(- () =>- useSetWorkflowVarsWithValue({- flowType: FlowType.appFlow,- flowId: 'flow-2',- }),- {- initialStoreState: {- dataSourceList: [],- },+ const { result, store } = renderWorkflowHook(() => useSetWorkflowVarsWithValue(), {+ initialStoreState: {+ dataSourceList: [],},- )+ })await act(async () => {await result.current.fetchInspectVars({diff --git a/web/app/components/workflow/hooks/__tests__/use-inspect-vars-crud-common.spec.ts b/web/app/components/workflow/hooks/__tests__/use-inspect-vars-crud-common.spec.tsindex c91c3b8f686..64f5ce1af0d 100644--- a/web/app/components/workflow/hooks/__tests__/use-inspect-vars-crud-common.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-inspect-vars-crud-common.spec.ts@@ -1,13 +1,15 @@import type { SchemaTypeDefinition } from '@/service/use-common'import type { VarInInspect } from '@/types/workflow'import { act, waitFor } from '@testing-library/react'-import { FlowType } from '@/types/common'import { createNode } from '../../__tests__/fixtures'import { resetReactFlowMockState, rfState } from '../../__tests__/reactflow-mock-state'import { renderWorkflowHook } from '../../__tests__/workflow-test-env'import { BlockEnum, VarType } from '../../types'import { useInspectVarsCrudCommon } from '../use-inspect-vars-crud-common'+const mockResetInspectorVar = vi.hoisted(() => vi.fn())+const mockDeleteInspectVar = vi.hoisted(() => vi.fn())+const mockDeleteNodeInspectorVars = vi.hoisted(() => vi.fn())const mockFetchNodeInspectVars = vi.hoisted(() => vi.fn())const mockDoDeleteAllInspectorVars = vi.hoisted(() => vi.fn())const mockInvalidateConversationVarValues = vi.hoisted(() => vi.fn())@@ -29,17 +31,14 @@ vi.mock('reactflow', async () =>(await import('../../__tests__/reactflow-mock-state')).createReactFlowModuleMock(),)-vi.mock('@/service/use-flow', () => ({- default: () => ({- useInvalidateConversationVarValues: () => mockInvalidateConversationVarValues,- useInvalidateSysVarValues: () => mockInvalidateSysVarValues,- useResetConversationVar: () => ({ mutateAsync: vi.fn() }),- useResetToLastRunValue: () => ({ mutateAsync: vi.fn() }),- useDeleteAllInspectorVars: () => ({ mutateAsync: mockDoDeleteAllInspectorVars }),- useDeleteNodeInspectorVars: () => ({ mutate: vi.fn() }),- useDeleteInspectVar: () => ({ mutate: vi.fn() }),- useEditInspectorVar: () => ({ mutateAsync: vi.fn() }),- }),+vi.mock('@/service/use-workflow', () => ({+ useInvalidateConversationVarValues: () => mockInvalidateConversationVarValues,+ useInvalidateSysVarValues: () => mockInvalidateSysVarValues,+ useResetInspectorVar: () => ({ mutateAsync: mockResetInspectorVar }),+ useDeleteAllInspectorVars: () => ({ mutateAsync: mockDoDeleteAllInspectorVars }),+ useDeleteNodeInspectorVars: () => ({ mutateAsync: mockDeleteNodeInspectorVars }),+ useDeleteInspectVar: () => ({ mutateAsync: mockDeleteInspectVar }),+ useEditInspectorVar: () => ({ mutateAsync: vi.fn() }),}))vi.mock('@/service/use-tools', async () =>@@ -118,18 +117,11 @@ describe('useInspectVarsCrudCommon', () => {})it('invalidates cached system vars without refetching node values for system selectors', async () => {- const { result } = renderWorkflowHook(- () =>- useInspectVarsCrudCommon({- flowId: 'flow-1',- flowType: FlowType.appFlow,- }),- {- initialStoreState: {- dataSourceList: [],- },+ const { result } = renderWorkflowHook(() => useInspectVarsCrudCommon(), {+ initialStoreState: {+ dataSourceList: [],},- )+ })await act(async () => {await result.current.fetchInspectVarValue(['sys', 'query'], schemaTypeDefinitions)@@ -142,38 +134,34 @@ describe('useInspectVarsCrudCommon', () => {it('fetches node inspect vars, adds schema types, and marks the node as fetched', async () => {mockFetchNodeInspectVars.mockResolvedValue([createInspectVar()])- const { result, store } = renderWorkflowHook(- () =>- useInspectVarsCrudCommon({- flowId: 'flow-1',- flowType: FlowType.appFlow,- }),- {- initialStoreState: {- dataSourceList: [],- nodesWithInspectVars: [- {- nodeId: 'node-1',- nodePayload: {- type: BlockEnum.Code,- title: 'Code',- desc: '',- } as never,- nodeType: BlockEnum.Code,+ const { result, store } = renderWorkflowHook(() => useInspectVarsCrudCommon(), {+ initialStoreState: {+ dataSourceList: [],+ nodesWithInspectVars: [+ {+ nodeId: 'node-1',+ nodePayload: {+ type: BlockEnum.Code,title: 'Code',- vars: [],- },- ],- },+ desc: '',+ } as never,+ nodeType: BlockEnum.Code,+ title: 'Code',+ vars: [],+ },+ ],},- )+ })await act(async () => {await result.current.fetchInspectVarValue(['node-1', 'answer'], schemaTypeDefinitions)})await waitFor(() => {- expect(mockFetchNodeInspectVars).toHaveBeenCalledWith(FlowType.appFlow, 'flow-1', 'node-1')+ expect(mockFetchNodeInspectVars).toHaveBeenCalledWith(+ { kind: 'app', appId: 'app-1', mode: 'workflow' },+ 'node-1',+ )expect(store.getState().nodesWithInspectVars[0]).toMatchObject({nodeId: 'node-1',isValueFetched: true,@@ -190,30 +178,23 @@ describe('useInspectVarsCrudCommon', () => {it('deletes all inspect vars, invalidates cached values, and clears edge running state', async () => {mockDoDeleteAllInspectorVars.mockResolvedValue(undefined)- const { result, store } = renderWorkflowHook(- () =>- useInspectVarsCrudCommon({- flowId: 'flow-1',- flowType: FlowType.appFlow,- }),- {- initialStoreState: {- nodesWithInspectVars: [- {- nodeId: 'node-1',- nodePayload: {- type: BlockEnum.Code,- title: 'Code',- desc: '',- } as never,- nodeType: BlockEnum.Code,+ const { result, store } = renderWorkflowHook(() => useInspectVarsCrudCommon(), {+ initialStoreState: {+ nodesWithInspectVars: [+ {+ nodeId: 'node-1',+ nodePayload: {+ type: BlockEnum.Code,title: 'Code',- vars: [createInspectVar()],- },- ],- },+ desc: '',+ } as never,+ nodeType: BlockEnum.Code,+ title: 'Code',+ vars: [createInspectVar()],+ },+ ],},- )+ })await act(async () => {await result.current.deleteAllInspectorVars()@@ -225,4 +206,51 @@ describe('useInspectVarsCrudCommon', () => {expect(mockHandleEdgeCancelRunningStatus).toHaveBeenCalledTimes(1)expect(store.getState().nodesWithInspectVars).toEqual([])})+ it.each(['variable', 'node'] as const)(+ 'keeps inspected values when %s deletion fails and removes them only after success',+ async (target) => {+ const { result, store } = renderWorkflowHook(() => useInspectVarsCrudCommon())+ act(() =>+ result.current.appendNodeInspectVars(+ 'node-1',+ [createInspectVar()],+ [createNode({ id: 'node-1', data: { type: BlockEnum.Code } })],+ ),+ )+ const deleteRequest =+ target === 'variable' ? mockDeleteInspectVar : mockDeleteNodeInspectorVars+ const deleteValues = () =>+ target === 'variable'+ ? result.current.deleteInspectVar('node-1', 'var-1')+ : result.current.deleteNodeInspectorVars('node-1')+ deleteRequest.mockRejectedValueOnce(new Error('Delete failed'))+ await act(async () => {+ await expect(deleteValues()).resolves.toBeUndefined()+ })+ expect(store.getState().nodesWithInspectVars[0]?.vars).toEqual([createInspectVar()])+ deleteRequest.mockResolvedValueOnce(undefined)+ await act(async () => {+ await deleteValues()+ })+ expect(store.getState().nodesWithInspectVars.flatMap((node) => node.vars ?? [])).toEqual([])+ },+ )++ it('removes a variable reset with no historical value and preserves neighboring schemas', async () => {+ const { result, store } = renderWorkflowHook(() => useInspectVarsCrudCommon())+ const neighbor = createInspectVar({ id: 'var-2', name: 'other', schemaType: 'simple' })+ act(() =>+ result.current.appendNodeInspectVars(+ 'node-1',+ [createInspectVar(), neighbor],+ [createNode({ id: 'node-1', data: { type: BlockEnum.Code } })],+ ),+ )+ mockResetInspectorVar.mockResolvedValueOnce(undefined)+ await act(async () => {+ await result.current.resetToLastRunVar('node-1', 'var-1')+ })+ expect(store.getState().nodesWithInspectVars[0]?.vars).toEqual([neighbor])+ expect(mockFetchNodeInspectVars).not.toHaveBeenCalled()+ })})diff --git a/web/app/components/workflow/hooks/__tests__/use-inspect-vars-crud.spec.ts b/web/app/components/workflow/hooks/__tests__/use-inspect-vars-crud.spec.tsindex e9befc499ad..aed0d9ae28c 100644--- a/web/app/components/workflow/hooks/__tests__/use-inspect-vars-crud.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-inspect-vars-crud.spec.ts@@ -1,5 +1,4 @@import type { VarInInspect } from '@/types/workflow'-import { FlowType } from '@/types/common'import { renderWorkflowHook } from '../../__tests__/workflow-test-env'import { BlockEnum, VarType } from '../../types'import useInspectVarsCrud from '../use-inspect-vars-crud'@@ -65,17 +64,22 @@ describe('useInspectVarsCrud', () => {it('should pass the flow id to shared variable queries for app flows', () => {renderWorkflowHook(() => useInspectVarsCrud(), {+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},})- expect(mockUseConversationVarValues).toHaveBeenCalledWith(FlowType.appFlow, 'app-1')- expect(mockUseSysVarValues).toHaveBeenCalledWith(FlowType.appFlow, 'app-1')+ expect(mockUseConversationVarValues).toHaveBeenCalledWith({+ kind: 'app',+ appId: 'app-1',+ mode: 'workflow',+ })+ expect(mockUseSysVarValues).toHaveBeenCalledWith({+ kind: 'app',+ appId: 'app-1',+ mode: 'workflow',+ })})it('should append query and files vars to the start node and keep other system vars separate', () => {@@ -104,12 +108,9 @@ describe('useInspectVarsCrud', () => {},],},+ resource: { kind: 'app' as const, appId: 'flow-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'flow-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,hasNodeInspectVars,fetchInspectVarValue,editInspectVarValue: vi.fn(),@@ -139,33 +140,27 @@ describe('useInspectVarsCrud', () => {expect(result.current.deleteAllInspectorVars).toBe(deleteAllInspectorVars)})- it('should use an empty flow id for shared variable queries in rag pipelines', () => {+ it('should disable app-only variable queries in rag pipelines', () => {renderWorkflowHook(() => useInspectVarsCrud(), {+ resource: { kind: 'knowledge-pipeline' as const, pipelineId: 'pipeline-1' },hooksStoreProps: {- configsMap: {- flowId: 'pipeline-1',- flowType: FlowType.ragPipeline,- fileSettings: {} as never,- },+ fileSettings: {} as never,},})- expect(mockUseConversationVarValues).toHaveBeenCalledWith(FlowType.ragPipeline, '')- expect(mockUseSysVarValues).toHaveBeenCalledWith(FlowType.ragPipeline, '')+ expect(mockUseConversationVarValues).toHaveBeenCalledWith(undefined)+ expect(mockUseSysVarValues).toHaveBeenCalledWith(undefined)})- it('should use an empty flow id for shared variable queries in snippets', () => {+ it('should disable app-only variable queries in snippets', () => {renderWorkflowHook(() => useInspectVarsCrud(), {+ resource: { kind: 'snippet' as const, snippetId: 'snippet-1' },hooksStoreProps: {- configsMap: {- flowId: 'snippet-1',- flowType: FlowType.snippet,- fileSettings: {} as never,- },+ fileSettings: {} as never,},})- expect(mockUseConversationVarValues).toHaveBeenCalledWith(FlowType.snippet, '')- expect(mockUseSysVarValues).toHaveBeenCalledWith(FlowType.snippet, '')+ expect(mockUseConversationVarValues).toHaveBeenCalledWith(undefined)+ expect(mockUseSysVarValues).toHaveBeenCalledWith(undefined)})})diff --git a/web/app/components/workflow/hooks/__tests__/use-nodes-available-var-list.spec.ts b/web/app/components/workflow/hooks/__tests__/use-nodes-available-var-list.spec.tsindex c2b6d41b2f6..167141e9e24 100644--- a/web/app/components/workflow/hooks/__tests__/use-nodes-available-var-list.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-nodes-available-var-list.spec.ts@@ -1,8 +1,8 @@import type { Node, NodeOutPutVar, Var } from '../../types'-import { renderHook } from '@testing-library/react'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import { useSnippetDraftStore } from '@/app/components/snippets/draft-store'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { PipelineInputVarType } from '@/models/pipeline'-import { FlowType } from '@/types/common'import { BlockEnum, VarType } from '../../types'import useNodesAvailableVarList, {useGetNodesAvailableVarList,@@ -12,7 +12,7 @@ const mockGetTreeLeafNodes = vi.hoisted(() => vi.fn())const mockGetBeforeNodesInSameBranchIncludeParent = vi.hoisted(() => vi.fn())const mockGetNodeAvailableVars = vi.hoisted(() => vi.fn())const mockFlowType = vi.hoisted(() => ({- value: undefined as FlowType | undefined,+ value: undefined as EditorResource['kind'] | undefined,}))vi.mock('../use-workflow', async (importOriginal) => {@@ -20,7 +20,7 @@ vi.mock('../use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => true,+useWorkflow: () => ({getTreeLeafNodes: mockGetTreeLeafNodes,getBeforeNodesInSameBranchIncludeParent: mockGetBeforeNodesInSameBranchIncludeParent,@@ -40,10 +40,12 @@ vi.mock('../use-workflow-variables', async (importOriginal) => {})vi.mock('@/app/components/workflow/hooks-store/store', () => ({- useHooksStore: (selector: (state: { configsMap?: { flowType?: FlowType } }) => unknown) =>+ useHooksStore: (+ selector: (state: { configsMap?: { resourceKind?: EditorResource['kind'] } }) => unknown,+ ) =>selector({configsMap: {- flowType: mockFlowType.value,+ resourceKind: mockFlowType.value,},}),}))@@ -136,12 +138,14 @@ describe('useNodesAvailableVarList', () => {})const filterVar = vi.fn(() => true)- const { result } = renderHook(() =>- useNodesAvailableVarList([loopNode, childNode], {- filterVar,- hideEnv: true,- hideChatVar: true,- }),+ const { result } = renderHook(+ () =>+ useNodesAvailableVarList([loopNode, childNode], {+ filterVar,+ hideEnv: true,+ hideChatVar: true,+ }),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)expect(mockGetBeforeNodesInSameBranchIncludeParent).toHaveBeenCalledWith('loop-1')@@ -155,7 +159,7 @@ describe('useNodesAvailableVarList', () => {2,expect.objectContaining({parentNode: loopNode,- isChatMode: true,+ isChatflow: true,filterVar,hideEnv: true,hideChatVar: true,@@ -164,7 +168,6 @@ describe('useNodesAvailableVarList', () => {})it('adds snippet input fields as virtual start variables on snippet canvases', () => {- globalThis.history.pushState({}, '', '/snippets/snippet-1/orchestrate')useSnippetDraftStore.getState().setInputFields([{type: PipelineInputVarType.textInput,@@ -176,10 +179,12 @@ describe('useNodesAvailableVarList', () => {const currentNode = createNode({ id: 'node-a' })- const { result } = renderHook(() =>- useNodesAvailableVarList([currentNode], {- filterVar: () => true,- }),+ const { result } = renderHook(+ () =>+ useNodesAvailableVarList([currentNode], {+ filterVar: () => true,+ }),+ { resource: { kind: 'snippet', snippetId: 'snippet-1' } },)expect(result.current['node-a']?.availableNodes[0]).toEqual(@@ -205,15 +210,16 @@ describe('useNodesAvailableVarList', () => {})it('filters system variables on snippet canvases', () => {- globalThis.history.pushState({}, '', '/snippets/snippet-1/orchestrate')mockGetNodeAvailableVars.mockReturnValue(outputVarsWithSystemVars)const currentNode = createNode({ id: 'node-a' })- const { result } = renderHook(() =>- useNodesAvailableVarList([currentNode], {- filterVar: () => true,- }),+ const { result } = renderHook(+ () =>+ useNodesAvailableVarList([currentNode], {+ filterVar: () => true,+ }),+ { resource: { kind: 'snippet', snippetId: 'snippet-1' } },)expect(result.current['node-a']?.availableVars).toEqual([@@ -235,25 +241,28 @@ describe('useNodesAvailableVarList', () => {const currentNode = createNode({ id: 'node-a' })- const { result } = renderHook(() =>- useNodesAvailableVarList([currentNode], {- filterVar: () => true,- }),+ const { result } = renderHook(+ () =>+ useNodesAvailableVarList([currentNode], {+ filterVar: () => true,+ }),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)expect(result.current['node-a']?.availableVars).toEqual(outputVarsWithSystemVars)})it('filters system variables when the current flow is a snippet', () => {- mockFlowType.value = FlowType.snippetmockGetNodeAvailableVars.mockReturnValue(outputVarsWithSystemVars)const currentNode = createNode({ id: 'node-a' })- const { result } = renderHook(() =>- useNodesAvailableVarList([currentNode], {- filterVar: () => true,- }),+ const { result } = renderHook(+ () =>+ useNodesAvailableVarList([currentNode], {+ filterVar: () => true,+ }),+ { resource: { kind: 'snippet', snippetId: 'snippet-1' } },)expect(result.current['node-a']?.availableVars).toEqual([@@ -276,7 +285,9 @@ describe('useNodesAvailableVarList', () => {const filterVar = vi.fn(() => true)const passedInAvailableNodes = [createNode({ id: 'manual-node' })]- const { result } = renderHook(() => useGetNodesAvailableVarList())+ const { result } = renderHook(() => useGetNodesAvailableVarList(), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })const leafMap = result.current.getNodesAvailableVarList([firstNode], {onlyLeafNodeVar: true,@@ -292,3 +303,10 @@ describe('useNodesAvailableVarList', () => {expect(manualMap['node-b']?.availableNodes).toBe(passedInAvailableNodes)})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => true) }+})diff --git a/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts b/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.tsindex c8a4e756a8e..00548868027 100644--- a/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts@@ -30,7 +30,7 @@ const runtimeNodesMetaDataMap = vi.hoisted(() => ({}))const runtimeState = vi.hoisted(() => ({- isChatMode: false,+ isChatflow: false,nodesReadOnly: false,workflowReadOnly: false,}))@@ -43,7 +43,6 @@ vi.mock('reactflow', async () =>)vi.mock('../use-workflow', () => ({- useIsChatMode: () => runtimeState.isChatMode,useWorkflow: () => ({getAfterNodesInSameBranch: () => [],}),@@ -119,7 +118,7 @@ describe('useNodesInteractions', () => {beforeEach(() => {vi.clearAllMocks()resetReactFlowMockState()- runtimeState.isChatMode = false+ runtimeState.isChatflow = falseruntimeState.nodesReadOnly = falseruntimeState.workflowReadOnly = falsemockCreateInlineAgentBinding.mockImplementation(@@ -974,13 +973,13 @@ describe('useNodesInteractions', () => {BlockEnum.ParameterExtractor,BlockEnum.Agent,].flatMap((type) => [- { type, isChatMode: false },- { type, isChatMode: true },+ { type, isChatflow: false },+ { type, isChatflow: true },]),)(- 'pastes $type with conversation memory only when isChatMode=$isChatMode',- async ({ type, isChatMode }) => {- runtimeState.isChatMode = isChatMode+ 'pastes $type with conversation memory only when isChatflow=$isChatflow',+ async ({ type, isChatflow }) => {+ runtimeState.isChatflow = isChatflowruntimeNodesMetaDataMap.value = {[type]: { defaultValue: { type, title: type, desc: '' } },}@@ -997,7 +996,7 @@ describe('useNodesInteractions', () => {const pastedNodes = rfState.setNodes.mock.calls.at(-1)?.[0] as Node[]const pastedNode = pastedNodes.find((node) => node.data.type === type)!- if (isChatMode) expect(pastedNode.data).toHaveProperty('memory', memory)+ if (isChatflow) expect(pastedNode.data).toHaveProperty('memory', memory)else expect(pastedNode.data).not.toHaveProperty('memory')expect(pastedNode.data).toHaveProperty('prompt_template', promptTemplate)expect(store.getState().clipboardElements[0]?.data).toHaveProperty('memory', memory)@@ -1390,3 +1389,10 @@ describe('useNodesInteractions', () => {)})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => runtimeState.isChatflow) }+})diff --git a/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts b/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.tsindex cc3da3f2204..560c77c95e5 100644--- a/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts@@ -51,10 +51,6 @@ vi.mock('reactflow', () => ({}),}))-vi.mock('@/next/navigation', () => ({- useParams: () => ({ appId: 'app-1' }),-}))-vi.mock('@/service/console', async (importOriginal) => {const actual = await importOriginal<typeof import('@/service/console')>()diff --git a/web/app/components/workflow/hooks/__tests__/use-workflow-variables.spec.ts b/web/app/components/workflow/hooks/__tests__/use-workflow-variables.spec.tsindex 6bdb76d83f5..55c4b83a3e0 100644--- a/web/app/components/workflow/hooks/__tests__/use-workflow-variables.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-workflow-variables.spec.ts@@ -25,9 +25,7 @@ vi.mock('../../nodes/_base/components/variable/use-match-schema-type', () => ({}))let mockIsChatMode = false-vi.mock('../use-workflow', () => ({- useIsChatMode: () => mockIsChatMode,-}))+vi.mock('../use-workflow', () => ({}))describe('useWorkflowVariables', () => {beforeEach(() => {@@ -45,13 +43,13 @@ describe('useWorkflowVariables', () => {result.current.getNodeAvailableVars({beforeNodes: [],- isChatMode: true,+ isChatflow: true,filterVar: () => true,})expect(mockToNodeAvailableVars).toHaveBeenCalledOnce()const args = mockToNodeAvailableVars.mock.calls[0]![0]- expect(args.isChatMode).toBe(true)+ expect(args.isChatflow).toBe(true)expect(args.conversationVariables).toHaveLength(1)expect(args.environmentVariables).toHaveLength(1)})@@ -65,7 +63,7 @@ describe('useWorkflowVariables', () => {result.current.getNodeAvailableVars({beforeNodes: [],- isChatMode: false,+ isChatflow: false,filterVar: () => true,hideEnv: true,})@@ -83,7 +81,7 @@ describe('useWorkflowVariables', () => {result.current.getNodeAvailableVars({beforeNodes: [],- isChatMode: false,+ isChatflow: false,filterVar: () => true,})@@ -101,7 +99,7 @@ describe('useWorkflowVariables', () => {const type = result.current.getCurrentVariableType({valueSelector: ['node-1', 'output'],availableNodes: [],- isChatMode: false,+ isChatflow: false,})expect(mockGetVarType).toHaveBeenCalledOnce()@@ -143,3 +141,10 @@ describe('useWorkflowVariableType', () => {expect((args.parentNode as { id: string }).id).toBe('iter-1')})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockIsChatMode) }+})diff --git a/web/app/components/workflow/hooks/__tests__/use-workflow.spec.ts b/web/app/components/workflow/hooks/__tests__/use-workflow.spec.tsindex b53a9fd7640..8dd39891e96 100644--- a/web/app/components/workflow/hooks/__tests__/use-workflow.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-workflow.spec.ts@@ -1,9 +1,5 @@import type { NodeDefault } from '../../types'import { act } from '@testing-library/react'-import { consoleQuery } from '@/service/console'-import { createAppDetailFixture } from '@/test/fixtures/app'-import { createTestQueryClient } from '@/test/query-client'-import { AppModeEnum } from '@/types/app'import { createNode } from '../../__tests__/fixtures'import {baseRunningData,@@ -13,7 +9,6 @@ import {import { BlockClassification } from '../../block-selector/types'import { BlockEnum, WorkflowRunningStatus } from '../../types'import {- useIsChatMode,useIsNodeInIteration,useIsNodeInLoop,useNodesReadOnly,@@ -41,77 +36,7 @@ function createNodeDefault(type: BlockEnum): NodeDefault {}// ----------------------------------------------------------------------------// useIsChatMode-// -----------------------------------------------------------------------------describe('useIsChatMode', () => {- let queryClient: ReturnType<typeof createTestQueryClient>-- beforeEach(() => {- queryClient = createTestQueryClient()- })-- afterEach(() => {- queryClient.clear()- })-- it.each([- { mode: AppModeEnum.ADVANCED_CHAT, expected: true },- { mode: AppModeEnum.WORKFLOW, expected: false },- ])('should return $expected for the current $mode app', ({ mode, expected }) => {- queryClient.setQueryData(- consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),- createAppDetailFixture({ id: 'app-1', mode }),- )-- const { result } = renderWorkflowHook(() => useIsChatMode(), {- initialStoreState: { appId: 'app-1' },- queryClient,- })-- expect(result.current).toBe(expected)- })-- it('should return false without an app id even when another chatflow is cached', () => {- queryClient.setQueryData(- consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'chatflow-app' } } }),- createAppDetailFixture({ id: 'chatflow-app', mode: AppModeEnum.ADVANCED_CHAT }),- )-- const { result } = renderWorkflowHook(() => useIsChatMode(), { queryClient })-- expect(result.current).toBe(false)- expect(globalThis.fetch).not.toHaveBeenCalled()- })-- it('should follow the current app id when switching between cached workflow and chatflow apps', () => {- for (const [appId, mode] of [- ['workflow-app', AppModeEnum.WORKFLOW],- ['chatflow-app', AppModeEnum.ADVANCED_CHAT],- ] as const) {- queryClient.setQueryData(- consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: appId } } }),- createAppDetailFixture({ id: appId, mode }),- )- }-- const { result, store } = renderWorkflowHook(() => useIsChatMode(), {- initialStoreState: { appId: 'workflow-app' },- queryClient,- })-- expect(result.current).toBe(false)-- act(() => store.setState({ appId: 'chatflow-app' }))- expect(result.current).toBe(true)-- act(() => store.setState({ appId: 'workflow-app' }))- expect(result.current).toBe(false)- })-})--// ----------------------------------------------------------------------------// useWorkflowReadOnly+// useIsChatflow// ---------------------------------------------------------------------------describe('useWorkflowReadOnly', () => {diff --git a/web/app/components/workflow/hooks/use-auto-generate-webhook-url.ts b/web/app/components/workflow/hooks/use-auto-generate-webhook-url.tsindex 5b2fe32e56a..4a597f3ff61 100644--- a/web/app/components/workflow/hooks/use-auto-generate-webhook-url.ts+++ b/web/app/components/workflow/hooks/use-auto-generate-webhook-url.ts@@ -1,13 +1,14 @@import { useQueryClient } from '@tanstack/react-query'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'import { BlockEnum } from '@/app/components/workflow/types'-import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { useCollaborativeWorkflow } from './use-collaborative-workflow'export const useAutoGenerateWebhookUrl = () => {- const { appId } = useParams<{ appId?: string }>()+ const appId = useAtomValue(editorAppIdAtom)const queryClient = useQueryClient()const collaborativeWorkflow = useCollaborativeWorkflow()diff --git a/web/app/components/workflow/hooks/use-checklist.ts b/web/app/components/workflow/hooks/use-checklist.tsindex 29f1b52c606..2fd5985a1f7 100644--- a/web/app/components/workflow/hooks/use-checklist.ts+++ b/web/app/components/workflow/hooks/use-checklist.ts@@ -16,15 +16,21 @@ import type {} from '../types'import type { ModelItem } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { Emoji } from '@/app/components/tools/types'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type { AgentToolPublishIssue } from '@/features/agent-v2/agent-detail/configure/tool-provider-catalog'import type { DataSet } from '@/models/datasets'-import { skipToken, useQueries, useQuery, useQueryClient } from '@tanstack/react-query'+import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query'import isDeepEqual from 'fast-deep-equal'+import { useAtomValue } from 'jotai'import { useCallback, useEffect, useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'import { useEdges, useStoreApi } from 'reactflow'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { normalizeModelProviderModelsResponse } from '@/app/components/header/account-setting/model-provider-page/utils'+import {+ editorResourceAtom,+ editorResourceKindAtom,+} from '@/app/components/workflow/editor-resource/state'import useNodes from '@/app/components/workflow/store/workflow/use-nodes'import { toast } from '@/app/notifications'import { MAX_TREE_DEPTH } from '@/config'@@ -35,7 +41,6 @@ import {getAgentToolPublishIssues,useAgentToolPresentation,} from '@/features/agent-v2/agent-detail/configure/tool-provider-catalog'-import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { fetchDatasets } from '@/service/datasets'import {@@ -45,11 +50,8 @@ import {useAllWorkflowTools,} from '@/service/use-tools'import { useAllTriggerPlugins } from '@/service/use-triggers'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import { CUSTOM_NODE } from '../constants'import { useDatasetsDetailStore } from '../datasets-detail-store/store'-import { useHooksStore } from '../hooks-store/store'import { getNodeUsedVars, isSpecialVar } from '../nodes/_base/components/variable/utils'import { hasValidInlineAgentBinding, isAgentV2NodeData } from '../nodes/agent-v2/types'import AgentDefault from '../nodes/agent/default'@@ -101,12 +103,13 @@ type NodeValidator = NonNullable<const EMPTY_ENVIRONMENT_VARIABLES: EnvironmentVariable[] = []-const withFlowType = (moreDataForCheckValid: CheckValidExtraData, flowType?: FlowType) => {- if (!flowType) return moreDataForCheckValid-+const withResourceKind = (+ moreDataForCheckValid: CheckValidExtraData,+ resourceKind: EditorResource['kind'],+) => {return {...(moreDataForCheckValid ?? {}),- flowType,+ resourceKind,}}@@ -162,7 +165,7 @@ const getDuplicateEndOutputMessages = (return nodeMessages}-export const useChecklist = (nodes: Node[], edges: Edge[], options?: { flowType?: FlowType }) => {+export const useChecklist = (nodes: Node[], edges: Edge[]) => {const { t } = useTranslation(['agentV2', 'common', 'workflow', 'modelProvider'])const language = useGetLanguage()const { nodesMap: nodesExtraData } = useNodesMetaData()@@ -183,22 +186,15 @@ export const useChecklist = (nodes: Node[], edges: Edge[], options?: { flowType?const { data: triggerPlugins } = useAllTriggerPlugins()const datasetsDetail = useDatasetsDetailStore((s) => s.datasetsDetail)const getToolIcon = useGetToolIcon()- const { appId } = useParams<{ appId?: string }>()- const { data: appMode } = useQuery(- consoleQuery.apps.byAppId.get.queryOptions({- input: appId ? { params: { app_id: appId } } : skipToken,- select: (appDetail) => appDetail.mode,- }),- )- const shouldCheckStartNode =- appMode === AppModeEnum.WORKFLOW || appMode === AppModeEnum.ADVANCED_CHAT+ const resourceKind = useAtomValue(editorResourceKindAtom)+ const shouldCheckStartNode = resourceKind === 'app'const { data: modelProviders = EMPTY_MODEL_PROVIDERS } = useQuery(consoleQuery.workspaces.current.modelProviders.summary.get.queryOptions({select: (response) => response.data,}),)const workflowStore = useWorkflowStore()- const configsMap = useHooksStore((s) => s.configsMap)+ const resource = useAtomValue(editorResourceAtom)const map = useNodesAvailableVarList(nodes)const inlineAgentNodes = useMemo(@@ -213,16 +209,15 @@ export const useChecklist = (nodes: Node[], edges: Edge[], options?: { flowType?)const inlineAgentConfigurationIssues = useQueries({queries:- !configsMap?.flowId ||- (configsMap.flowType !== FlowType.appFlow && configsMap.flowType !== FlowType.snippet)+ resource.kind !== 'app' && resource.kind !== 'snippet'? []: inlineAgentNodes.map((node) =>- configsMap.flowType === FlowType.snippet+ resource.kind === 'snippet'? consoleQuery.snippets.bySnippetId.workflows.draft.nodes.byNodeId.agentComposer.get.queryOptions({input: {params: {- snippet_id: configsMap.flowId,+ snippet_id: resource.snippetId,node_id: node.id,},},@@ -232,7 +227,7 @@ export const useChecklist = (nodes: Node[], edges: Edge[], options?: { flowType?{input: {params: {- app_id: configsMap.flowId,+ app_id: resource.appId,node_id: node.id,},},@@ -466,7 +461,7 @@ export const useChecklist = (nodes: Node[], edges: Edge[], options?: { flowType?const validationError = validator(checkData,t,- withFlowType(moreDataForCheckValid, options?.flowType),+ withResourceKind(moreDataForCheckValid, resourceKind),).errorMessageif (validationError) errorMessages.push(validationError)}@@ -610,7 +605,7 @@ export const useChecklist = (nodes: Node[], edges: Edge[], options?: { flowType?modelProviders,inlineAgentConfigurationIssues,inlineAgentToolPresentation.toolDisplayNameById,- options?.flowType,+ resourceKind,])useEffect(() => {@@ -656,16 +651,8 @@ export const useChecklistBeforePublish = () => {const { data: buildInTools } = useAllBuiltInTools()const { data: customTools } = useAllCustomTools()const { data: workflowTools } = useAllWorkflowTools()- const flowType = useHooksStore((s) => s.configsMap?.flowType)- const { appId } = useParams<{ appId?: string }>()- const { data: appMode } = useQuery(- consoleQuery.apps.byAppId.get.queryOptions({- input: appId ? { params: { app_id: appId } } : skipToken,- select: (appDetail) => appDetail.mode,- }),- )- const shouldCheckStartNode =- appMode === AppModeEnum.WORKFLOW || appMode === AppModeEnum.ADVANCED_CHAT+ const resourceKind = useAtomValue(editorResourceKindAtom)+ const shouldCheckStartNode = resourceKind === 'app'const getCheckData = useCallback((@@ -849,7 +836,7 @@ export const useChecklistBeforePublish = () => {const { errorMessage } = validator(checkData,t,- withFlowType(moreDataForCheckValid, flowType),+ withResourceKind(moreDataForCheckValid, resourceKind),)if (errorMessage) {@@ -945,7 +932,7 @@ export const useChecklistBeforePublish = () => {queryClient,strategyProviders,modelProviders,- flowType,+ resourceKind,])return {@@ -954,11 +941,10 @@ export const useChecklistBeforePublish = () => {}export const useWorkflowRunValidation = () => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const nodes = useNodes()const edges = useEdges<CommonEdgeType>()- const flowType = useHooksStore((s) => s.configsMap?.flowType)- const needWarningNodes = useChecklist(nodes, edges, { flowType })+ const needWarningNodes = useChecklist(nodes, edges)const validateBeforeRun = useCallback(() => {if (needWarningNodes.length > 0) {diff --git a/web/app/components/workflow/hooks/use-config-vision.ts b/web/app/components/workflow/hooks/use-config-vision.tsindex 1a88e881909..2e6712e0eb8 100644--- a/web/app/components/workflow/hooks/use-config-vision.ts+++ b/web/app/components/workflow/hooks/use-config-vision.ts@@ -1,10 +1,11 @@import type { ModelConfig, VisionSetting } from '@/app/components/workflow/types'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { Resolution } from '@/types/app'-import { useIsChatMode } from './use-workflow'type Payload = {enabled: boolean@@ -29,7 +30,7 @@ const useConfigVision = (model: model.name,})- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const getIsVisionModel = useCallback(() => {return !!currModel?.features?.includes(ModelFeatureEnum.vision)@@ -41,7 +42,7 @@ const useConfigVision = ((enabled: boolean) => {const newPayload = produce(payload, (draft) => {draft.enabled = enabled- if (enabled && isChatMode) {+ if (enabled && isChatflow) {draft.configs = {detail: Resolution.high,variable_selector: ['sys', 'files'],@@ -52,7 +53,7 @@ const useConfigVision = (})onChange(newPayload)},- [isChatMode, onChange, payload],+ [isChatflow, onChange, payload],)const handleVisionResolutionChange = useCallback(diff --git a/web/app/components/workflow/hooks/use-fetch-workflow-inspect-vars.ts b/web/app/components/workflow/hooks/use-fetch-workflow-inspect-vars.tsindex 653bd9d5595..e4185009f26 100644--- a/web/app/components/workflow/hooks/use-fetch-workflow-inspect-vars.ts+++ b/web/app/components/workflow/hooks/use-fetch-workflow-inspect-vars.ts@@ -1,9 +1,10 @@import type { Node, WorkflowPluginCatalogs } from '@/app/components/workflow/types'import type { SchemaTypeDefinition } from '@/service/use-common'-import type { FlowType } from '@/types/common'import type { NodeWithVar, VarInInspect } from '@/types/workflow'+import { useAtomValue } from 'jotai'import { useCallback, useMemo } from 'react'import { useStoreApi } from 'reactflow'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import { useStore, useWorkflowStore } from '@/app/components/workflow/store'import {useAllBuiltInTools,@@ -20,16 +21,12 @@ import useMatchSchemaType from '../nodes/_base/components/variable/use-match-schimport { toNodeOutputVars } from '../nodes/_base/components/variable/utils'import { useNodesInteractionsWithoutSync } from './use-nodes-interactions-without-sync'-type Params = {- flowType: FlowType- flowId: string-}--export const useSetWorkflowVarsWithValue = ({ flowType, flowId }: Params) => {+export const useSetWorkflowVarsWithValue = () => {+ const resource = useAtomValue(editorResourceAtom)const workflowStore = useWorkflowStore()const store = useStoreApi()- const invalidateConversationVarValues = useInvalidateConversationVarValues(flowType, flowId)- const invalidateSysVarValues = useInvalidateSysVarValues(flowType, flowId)+ const invalidateConversationVarValues = useInvalidateConversationVarValues(resource)+ const invalidateSysVarValues = useInvalidateSysVarValues(resource)const { handleCancelAllNodeSuccessStatus } = useNodesInteractionsWithoutSync()const { schemaTypeDefinitions } = useMatchSchemaType()const { data: buildInTools } = useAllBuiltInTools()@@ -127,15 +124,14 @@ export const useSetWorkflowVarsWithValue = ({ flowType, flowId }: Params) => {const { passInVars, vars, passedInAllPluginInfoList, passedInSchemaTypeDefinitions } = paramsinvalidateConversationVarValues()invalidateSysVarValues()- const data = passInVars ? vars! : await fetchAllInspectVars(flowType, flowId)+ const data = passInVars ? vars! : await fetchAllInspectVars(resource)setInspectVarsToStore(data, passedInAllPluginInfoList, passedInSchemaTypeDefinitions)handleCancelAllNodeSuccessStatus() // to make sure clear node output show the unset status},[invalidateConversationVarValues,invalidateSysVarValues,- flowType,- flowId,+ resource,setInspectVarsToStore,handleCancelAllNodeSuccessStatus,],diff --git a/web/app/components/workflow/hooks/use-inspect-vars-crud-common.ts b/web/app/components/workflow/hooks/use-inspect-vars-crud-common.tsindex d8913d5a5fc..06f2dae4ebb 100644--- a/web/app/components/workflow/hooks/use-inspect-vars-crud-common.ts+++ b/web/app/components/workflow/hooks/use-inspect-vars-crud-common.ts@@ -1,10 +1,11 @@import type { Node, ValueSelector } from '@/app/components/workflow/types'import type { SchemaTypeDefinition } from '@/service/use-common'-import type { FlowType } from '@/types/common'import type { VarInInspect } from '@/types/workflow'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useStoreApi } from 'reactflow'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import {isConversationVar,isENV,@@ -12,45 +13,39 @@ import {toNodeOutputVars,} from '@/app/components/workflow/nodes/_base/components/variable/utils'import { useWorkflowStore } from '@/app/components/workflow/store'-import useFLow from '@/service/use-flow'import {useAllBuiltInTools,useAllCustomTools,useAllMCPTools,useAllWorkflowTools,} from '@/service/use-tools'+import {+ useDeleteAllInspectorVars,+ useDeleteInspectVar,+ useDeleteNodeInspectorVars,+ useEditInspectorVar,+ useInvalidateConversationVarValues,+ useInvalidateSysVarValues,+ useResetInspectorVar,+} from '@/service/use-workflow'import { fetchNodeInspectVars } from '@/service/workflow'import { VarInInspectType } from '@/types/workflow'import { useEdgesInteractionsWithoutSync } from './use-edges-interactions-without-sync'import { useNodesInteractionsWithoutSync } from './use-nodes-interactions-without-sync'-type Params = {- flowId: string- flowType: FlowType-}-export const useInspectVarsCrudCommon = ({ flowId, flowType }: Params) => {+export const useInspectVarsCrudCommon = () => {+ const resource = useAtomValue(editorResourceAtom)const workflowStore = useWorkflowStore()const store = useStoreApi()- const {- useInvalidateConversationVarValues,- useInvalidateSysVarValues,- useResetConversationVar,- useResetToLastRunValue,- useDeleteAllInspectorVars,- useDeleteNodeInspectorVars,- useDeleteInspectVar,- useEditInspectorVar,- } = useFLow({ flowType })- const invalidateConversationVarValues = useInvalidateConversationVarValues(flowId)- const { mutateAsync: doResetConversationVar } = useResetConversationVar(flowId)- const { mutateAsync: doResetToLastRunValue } = useResetToLastRunValue(flowId)- const invalidateSysVarValues = useInvalidateSysVarValues(flowId)+ const invalidateConversationVarValues = useInvalidateConversationVarValues(resource)+ const { mutateAsync: doResetInspectorVar } = useResetInspectorVar(resource)+ const invalidateSysVarValues = useInvalidateSysVarValues(resource)- const { mutateAsync: doDeleteAllInspectorVars } = useDeleteAllInspectorVars(flowId)- const { mutate: doDeleteNodeInspectorVars } = useDeleteNodeInspectorVars(flowId)- const { mutate: doDeleteInspectVar } = useDeleteInspectVar(flowId)+ const { mutateAsync: doDeleteAllInspectorVars } = useDeleteAllInspectorVars(resource)+ const { mutateAsync: doDeleteNodeInspectorVars } = useDeleteNodeInspectorVars(resource)+ const { mutateAsync: doDeleteInspectVar } = useDeleteInspectVar(resource)- const { mutateAsync: doEditInspectorVar } = useEditInspectorVar(flowId)+ const { mutateAsync: doEditInspectorVar } = useEditInspectorVar(resource)const { handleCancelNodeSuccessStatus } = useNodesInteractionsWithoutSync()const { handleEdgeCancelRunningStatus } = useEdgesInteractionsWithoutSync()const { data: buildInTools } = useAllBuiltInTools()@@ -149,7 +144,7 @@ export const useInspectVarsCrudCommon = ({ flowId, flowType }: Params) => {allPluginInfoList,schemaTypeDefinitions,)- const vars = await fetchNodeInspectVars(flowType, flowId, nodeId!)+ const vars = await fetchNodeInspectVars(resource, nodeId!)const varsWithSchemaType = vars.map((varItem) => {const schemaType =currentNodeOutputVars[0]?.vars.find((v) => v.variable === varItem.name)?.schemaType || ''@@ -162,8 +157,7 @@ export const useInspectVarsCrudCommon = ({ flowId, flowType }: Params) => {},[workflowStore,- flowType,- flowId,+ resource,invalidateSysVarValues,invalidateConversationVarValues,buildInTools,@@ -216,7 +210,12 @@ export const useInspectVarsCrudCommon = ({ flowId, flowType }: Params) => {async (nodeId: string, varId: string) => {const { deleteInspectVar } = workflowStore.getState()if (hasNodeInspectVar(nodeId, varId)) {- await doDeleteInspectVar(varId)+ try {+ await doDeleteInspectVar(varId)+ } catch {+ // The Console transport reports the failure; preserve the inspected values.+ return+ }deleteInspectVar(nodeId, varId)}},@@ -225,17 +224,22 @@ export const useInspectVarsCrudCommon = ({ flowId, flowType }: Params) => {const resetConversationVar = useCallback(async (varId: string) => {- await doResetConversationVar(varId)+ await doResetInspectorVar(varId)invalidateConversationVarValues()},- [doResetConversationVar, invalidateConversationVarValues],+ [doResetInspectorVar, invalidateConversationVarValues],)const deleteNodeInspectorVars = useCallback(async (nodeId: string) => {const { deleteNodeInspectVars } = workflowStore.getState()if (hasNodeInspectVars(nodeId)) {- await doDeleteNodeInspectorVars(nodeId)+ try {+ await doDeleteNodeInspectorVars(nodeId)+ } catch {+ // The Console transport reports the failure; preserve the inspected values.+ return+ }deleteNodeInspectVars(nodeId)}},@@ -258,7 +262,7 @@ export const useInspectVarsCrudCommon = ({ flowId, flowType }: Params) => {])const editInspectVarValue = useCallback(- async (nodeId: string, varId: string, value: any) => {+ async (nodeId: string, varId: string, value: VarInInspect['value']) => {const { setInspectVarValue } = workflowStore.getState()await doEditInspectorVar({varId,@@ -301,12 +305,14 @@ export const useInspectVarsCrudCommon = ({ flowId, flowType }: Params) => {async (nodeId: string, varId: string) => {const { resetToLastRunVar } = workflowStore.getState()const isSysVar = nodeId === 'sys'- const data = await doResetToLastRunValue(varId)+ const data = await doResetInspectorVar(varId)if (isSysVar) invalidateSysVarValues()- else resetToLastRunVar(nodeId, varId, data.value)+ else if (data && typeof data === 'object' && 'value' in data)+ resetToLastRunVar(nodeId, varId, data.value)+ else workflowStore.getState().deleteInspectVar(nodeId, varId)},- [doResetToLastRunValue, invalidateSysVarValues, workflowStore],+ [doResetInspectorVar, invalidateSysVarValues, workflowStore],)return {diff --git a/web/app/components/workflow/hooks/use-inspect-vars-crud.ts b/web/app/components/workflow/hooks/use-inspect-vars-crud.tsindex 0a0d76f6587..6e0690a0809 100644--- a/web/app/components/workflow/hooks/use-inspect-vars-crud.ts+++ b/web/app/components/workflow/hooks/use-inspect-vars-crud.ts@@ -1,19 +1,18 @@import { produce } from 'immer'+import { useAtomValue } from 'jotai'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import { useHooksStore } from '@/app/components/workflow/hooks-store'import { useConversationVarValues, useSysVarValues } from '@/service/use-workflow'-import { FlowType } from '@/types/common'import { useStore } from '../store'import { BlockEnum } from '../types'const varsAppendStartNodeKeys = ['query', 'files']const useInspectVarsCrud = () => {const partOfNodesWithInspectVars = useStore((s) => s.nodesWithInspectVars)- const configsMap = useHooksStore((s) => s.configsMap)- const shouldSkipSharedVariableQueries =- configsMap?.flowType === FlowType.ragPipeline || configsMap?.flowType === FlowType.snippet- const variableFlowId = shouldSkipSharedVariableQueries ? '' : configsMap?.flowId- const { data: conversationVars } = useConversationVarValues(configsMap?.flowType, variableFlowId)- const { data: allSystemVars } = useSysVarValues(configsMap?.flowType, variableFlowId)+ const resource = useAtomValue(editorResourceAtom)+ const appResource = resource.kind === 'app' ? resource : undefined+ const { data: conversationVars } = useConversationVarValues(appResource)+ const { data: allSystemVars } = useSysVarValues(appResource)const { varsAppendStartNode, systemVars } = (() => {if (allSystemVars?.length === 0) return { varsAppendStartNode: [], systemVars: [] }const varsAppendStartNode =diff --git a/web/app/components/workflow/hooks/use-nodes-available-var-list.ts b/web/app/components/workflow/hooks/use-nodes-available-var-list.tsindex 5250ef950a9..d805210050f 100644--- a/web/app/components/workflow/hooks/use-nodes-available-var-list.ts+++ b/web/app/components/workflow/hooks/use-nodes-available-var-list.ts@@ -1,16 +1,18 @@import type { Node, NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { useSnippetDraftStore } from '@/app/components/snippets/draft-store'-import { useHooksStore } from '@/app/components/workflow/hooks-store/store'+import {+ editorResourceKindAtom,+ isChatflowAtom,+} from '@/app/components/workflow/editor-resource/state'import {appendSnippetInputFieldVars,filterSnippetSystemVars,- isSnippetCanvas,} from '@/app/components/workflow/nodes/_base/hooks/snippet-input-field-vars'import { BlockEnum } from '@/app/components/workflow/types'-import { FlowType } from '@/types/common'-import { useIsChatMode, useWorkflow } from './use-workflow'+import { useWorkflow } from './use-workflow'import { useWorkflowVariables } from './use-workflow-variables'type Params = {@@ -54,9 +56,8 @@ const useNodesAvailableVarList = (const snippetInputFields = useSnippetDraftStore((s) => s.inputFields)const { getTreeLeafNodes, getBeforeNodesInSameBranchIncludeParent } = useWorkflow()const { getNodeAvailableVars } = useWorkflowVariables()- const isChatMode = useIsChatMode()- const isSnippetFlow =- useHooksStore((s) => s.configsMap?.flowType) === FlowType.snippet || isSnippetCanvas()+ const isChatflow = useAtomValue(isChatflowAtom)+ const isSnippetFlow = useAtomValue(editorResourceKindAtom) === 'snippet'const nodeAvailabilityMap: {[key: string]: { availableVars: NodeOutPutVar[]; availableNodes: Node[] }@@ -69,6 +70,7 @@ const useNodesAvailableVarList = ((onlyLeafNodeVar ? getTreeLeafNodes(nodeId) : getBeforeNodesInSameBranchIncludeParent(nodeId))if (node.data.type === BlockEnum.Loop) availableNodes.push(node)const snippetInputFieldAvailability = appendSnippetInputFieldVars({+ isSnippetFlow,availableNodes,fields: snippetInputFields,title: t(($) => $.panelTitle, { ns: 'snippet' }),@@ -82,7 +84,7 @@ const useNodesAvailableVarList = (...getNodeAvailableVars({parentNode: iterationNode,beforeNodes: availableNodes,- isChatMode,+ isChatflow,filterVar,hideEnv,hideChatVar,@@ -105,9 +107,8 @@ export const useGetNodesAvailableVarList = () => {const snippetInputFields = useSnippetDraftStore((s) => s.inputFields)const { getTreeLeafNodes, getBeforeNodesInSameBranchIncludeParent } = useWorkflow()const { getNodeAvailableVars } = useWorkflowVariables()- const isChatMode = useIsChatMode()- const isSnippetFlow =- useHooksStore((s) => s.configsMap?.flowType) === FlowType.snippet || isSnippetCanvas()+ const isChatflow = useAtomValue(isChatflowAtom)+ const isSnippetFlow = useAtomValue(editorResourceKindAtom) === 'snippet'const getNodesAvailableVarList = useCallback((nodes: Node[],@@ -129,6 +130,7 @@ export const useGetNodesAvailableVarList = () => {: getBeforeNodesInSameBranchIncludeParent(nodeId))if (node.data.type === BlockEnum.Loop) availableNodes.push(node)const snippetInputFieldAvailability = appendSnippetInputFieldVars({+ isSnippetFlow,availableNodes,fields: snippetInputFields,title: t(($) => $.panelTitle, { ns: 'snippet' }),@@ -142,7 +144,7 @@ export const useGetNodesAvailableVarList = () => {...getNodeAvailableVars({parentNode: iterationNode,beforeNodes: availableNodes,- isChatMode,+ isChatflow,filterVar,hideEnv,hideChatVar,@@ -163,7 +165,7 @@ export const useGetNodesAvailableVarList = () => {getTreeLeafNodes,getBeforeNodesInSameBranchIncludeParent,getNodeAvailableVars,- isChatMode,+ isChatflow,isSnippetFlow,snippetInputFields,t,diff --git a/web/app/components/workflow/hooks/use-nodes-interactions.ts b/web/app/components/workflow/hooks/use-nodes-interactions.tsindex a30d3c877ac..ee289b8ae3a 100644--- a/web/app/components/workflow/hooks/use-nodes-interactions.ts+++ b/web/app/components/workflow/hooks/use-nodes-interactions.ts@@ -15,9 +15,11 @@ import type { Edge, Node, OnNodeAdd } from '../types'import type { RAGPipelineVariables } from '@/models/pipeline'import { useQuery } from '@tanstack/react-query'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { getConnectedEdges, getOutgoers, useReactFlow } from 'reactflow'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { toast } from '@/app/notifications'import { consoleQuery } from '@/service/console'import { collaborationManager } from '../collaboration/core/collaboration-manager'@@ -67,7 +69,7 @@ import { useHelpline } from './use-helpline'import useInspectVarsCrud from './use-inspect-vars-crud'import { useNodesMetaData } from './use-nodes-meta-data'import { useNodesSyncDraft } from './use-nodes-sync-draft'-import { useIsChatMode, useNodesReadOnly, useWorkflow, useWorkflowReadOnly } from './use-workflow'+import { useNodesReadOnly, useWorkflow, useWorkflowReadOnly } from './use-workflow'import { useWorkflowHistory, WorkflowHistoryEvent } from './use-workflow-history'// Entry node deletion restriction has been removed to allow empty workflows@@ -163,8 +165,8 @@ const isNoteLinkClickTarget = (target: EventTarget | null, node: Node) => {}export const useNodesInteractions = () => {- const { t } = useTranslation(['workflow'])- const isChatMode = useIsChatMode()+ const { t } = useTranslation(['workflow'] as const)+ const isChatflow = useAtomValue(isChatflowAtom)const { data: appDslVersion = '' } = useQuery(consoleQuery.appDslVersion.get.queryOptions({staleTime: Infinity,@@ -2128,7 +2130,7 @@ export const useNodesInteractions = () => {}})- if (!isChatMode) {+ if (!isChatflow) {const memoryNodeTypes: BlockEnum[] = [BlockEnum.LLM,BlockEnum.QuestionClassifier,@@ -2167,7 +2169,7 @@ export const useNodesInteractions = () => {handleNodeLoopChildrenCopy,getNodeDefaultValueForPaste,appDslVersion,- isChatMode,+ isChatflow,])const handleNodesDuplicate = useCallback(diff --git a/web/app/components/workflow/hooks/use-workflow-comment.ts b/web/app/components/workflow/hooks/use-workflow-comment.tsindex f4024343bc0..e2d63a0e0de 100644--- a/web/app/components/workflow/hooks/use-workflow-comment.ts+++ b/web/app/components/workflow/hooks/use-workflow-comment.ts@@ -4,12 +4,13 @@ import type {WorkflowCommentList,} from '@/app/components/workflow/comment/types'import { useSuspenseQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react'import { useReactFlow } from 'reactflow'import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'import { userProfileQueryOptions } from '@/features/account-profile/client'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { useParams } from '@/next/navigation'import { consoleClient } from '@/service/console'import { useStore } from '../store'import { ControlMode } from '../types'@@ -34,8 +35,7 @@ const toCommentDetailPreview = (comment: WorkflowCommentList): WorkflowCommentDe})export const useWorkflowComment = () => {- const params = useParams()- const appId = params.appId as string+ const appId = useAtomValue(editorAppIdAtom)const reactflow = useReactFlow()const controlMode = useStore((s) => s.controlMode)const pendingComment = useStore((s) => s.pendingComment)diff --git a/web/app/components/workflow/hooks/use-workflow-variables.ts b/web/app/components/workflow/hooks/use-workflow-variables.tsindex 2d722372518..aebc76121d8 100644--- a/web/app/components/workflow/hooks/use-workflow-variables.ts+++ b/web/app/components/workflow/hooks/use-workflow-variables.ts@@ -1,8 +1,10 @@import type { Type } from '../nodes/llm/types'import type { Node, NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { useStoreApi } from 'reactflow'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import {getVarType,toNodeAvailableVars,@@ -15,10 +17,9 @@ import {} from '@/service/use-tools'import useMatchSchemaType from '../nodes/_base/components/variable/use-match-schema-type'import { useWorkflowStore } from '../store'-import { useIsChatMode } from './use-workflow'export const useWorkflowVariables = () => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const workflowStore = useWorkflowStore()const { schemaTypeDefinitions } = useMatchSchemaType()@@ -31,14 +32,14 @@ export const useWorkflowVariables = () => {({parentNode,beforeNodes,- isChatMode,+ isChatflow,filterVar,hideEnv,hideChatVar,}: {parentNode?: Node | nullbeforeNodes: Node[]- isChatMode: boolean+ isChatflow: booleanfilterVar: (payload: Var, selector: ValueSelector) => booleanhideEnv?: booleanhideChatVar?: boolean@@ -49,9 +50,9 @@ export const useWorkflowVariables = () => {parentNode,t,beforeNodes,- isChatMode,+ isChatflow,environmentVariables: hideEnv ? [] : environmentVariables,- conversationVariables: isChatMode && !hideChatVar ? conversationVariables : [],+ conversationVariables: isChatflow && !hideChatVar ? conversationVariables : [],ragVariables: ragPipelineVariables,filterVar,allPluginInfoList: {@@ -74,7 +75,7 @@ export const useWorkflowVariables = () => {isIterationItem,isLoopItem,availableNodes,- isChatMode,+ isChatflow,isConstant,preferSchemaType,}: {@@ -83,7 +84,7 @@ export const useWorkflowVariables = () => {isIterationItem?: booleanisLoopItem?: booleanavailableNodes: any[]- isChatMode: boolean+ isChatflow: booleanisConstant?: booleanpreferSchemaType?: boolean}) => {@@ -95,7 +96,7 @@ export const useWorkflowVariables = () => {isIterationItem,isLoopItem,availableNodes,- isChatMode,+ isChatflow,isConstant,environmentVariables,conversationVariables,@@ -125,7 +126,7 @@ export const useWorkflowVariableType = () => {const { getNodes } = store.getState()const { getCurrentVariableType } = useWorkflowVariables()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const getVarType = ({nodeId,@@ -143,7 +144,7 @@ export const useWorkflowVariableType = () => {parentNode: iterationNode,valueSelector,availableNodes,- isChatMode,+ isChatflow,isConstant: false,})return type as unknown as Typediff --git a/web/app/components/workflow/hooks/use-workflow.ts b/web/app/components/workflow/hooks/use-workflow.tsindex 29e63cd2fa9..ec4722ac247 100644--- a/web/app/components/workflow/hooks/use-workflow.ts+++ b/web/app/components/workflow/hooks/use-workflow.ts@@ -2,14 +2,11 @@ import type { Connection } from 'reactflow'import type { IterationNodeType } from '../nodes/iteration/types'import type { LoopNodeType } from '../nodes/loop/types'import type { BlockEnum, Edge, Node, ValueSelector } from '../types'-import { skipToken, useQuery } from '@tanstack/react-query'import { uniqBy } from 'es-toolkit/compat'import { useCallback } from 'react'import { getIncomers, getOutgoers } from 'reactflow'import { CUSTOM_ITERATION_START_NODE } from '@/app/components/workflow/nodes/iteration-start/constants'import { CUSTOM_LOOP_START_NODE } from '@/app/components/workflow/nodes/loop-start/constants'-import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { SUPPORT_OUTPUT_VARS_NODE } from '../constants'import { useHooksStore } from '../hooks-store'import {@@ -26,18 +23,6 @@ import { useAvailableBlocks } from './use-available-blocks'import { useCollaborativeWorkflow } from './use-collaborative-workflow'import { useNodesMetaData } from './use-nodes-meta-data'-export const useIsChatMode = () => {- const appId = useStore((state) => state.appId)- const { data: isChatMode } = useQuery(- consoleQuery.apps.byAppId.get.queryOptions({- input: appId ? { params: { app_id: appId } } : skipToken,- select: (app) => app.mode === AppModeEnum.ADVANCED_CHAT,- }),- )-- return isChatMode ?? false-}-export const useWorkflow = () => {const collaborativeWorkflow = useCollaborativeWorkflow()const { getAvailableBlocks } = useAvailableBlocks()@@ -295,8 +280,8 @@ export const useWorkflow = () => {)const isNodeVarsUsedInNodes = useCallback(- (node: Node, isChatMode: boolean) => {- const outputVars = getNodeOutputVars(node, isChatMode)+ (node: Node, isChatflow: boolean) => {+ const outputVars = getNodeOutputVars(node, isChatflow)const isUsed = outputVars.some((varSelector) => {return isVarUsedInNodes(varSelector)})diff --git a/web/app/components/workflow/index.tsx b/web/app/components/workflow/index.tsxindex e2f3a6bd476..b37856e42a6 100644--- a/web/app/components/workflow/index.tsx+++ b/web/app/components/workflow/index.tsx@@ -22,6 +22,7 @@ import { cn } from '@langgenius/dify-ui/cn'import { useEventListener } from 'ahooks'import { isEqual } from 'es-toolkit/predicate'import { setAutoFreeze } from 'immer'+import { useAtomValue } from 'jotai'import {Fragment,memo,@@ -46,6 +47,8 @@ import {useReactFlow,useStoreApi,} from 'reactflow'+import { getEditorResourceId } from '@/app/components/workflow/editor-resource/resource'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import { toast } from '@/app/notifications'import { IS_DEV } from '@/config'import { useEventEmitterContextContext } from '@/context/event-emitter'@@ -70,7 +73,7 @@ import CustomConnectionLine from './custom-connection-line'import CustomEdge from './custom-edge'import DatasetsDetailProvider from './datasets-detail-store/provider'import HelpLine from './help-line'-import { HooksStoreContextProvider, useHooksStore } from './hooks-store'+import { HooksStoreContextProvider } from './hooks-store'import { useEdgesInteractions } from './hooks/use-edges-interactions'import { useLocateNode } from './hooks/use-locate-node'import { useNodeKeyboardInteractions } from './hooks/use-node-keyboard-interactions'@@ -573,17 +576,17 @@ export const Workflow: FC<WorkflowProps> = memo(const { data: mcpTools } = useAllMCPTools()const dataSourceList = useStore((s) => s.dataSourceList)// buildInTools, customTools, workflowTools, mcpTools, dataSourceList- const configsMap = useHooksStore((s) => s.configsMap)+ const resource = useAtomValue(editorResourceAtom)const [isLoadedVars, setIsLoadedVars] = useState(false)const [vars, setVars] = useState<VarInInspect[]>([])useEffect(() => {;(async () => {- if (!configsMap?.flowType || !configsMap?.flowId) return- const data = await fetchAllInspectVars(configsMap.flowType, configsMap.flowId)+ if (!getEditorResourceId(resource)) return+ const data = await fetchAllInspectVars(resource)setVars(data)setIsLoadedVars(true)})()- }, [configsMap?.flowType, configsMap?.flowId])+ }, [resource])useEffect(() => {if (schemaTypeDefinitions && isLoadedVars) {fetchInspectVars({diff --git a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsxindex 62334178808..345f6fd89ed 100644--- a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx+++ b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx@@ -6,12 +6,11 @@ import { useHooksStore } from '@/app/components/workflow/hooks-store'import useNodes from '@/app/components/workflow/store/workflow/use-nodes'import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'import { useAllWorkflowTools } from '@/service/use-tools'-import { FlowType } from '@/types/common'import { BlockClassification } from '../../block-selector/types'import { useAvailableBlocks } from '../../hooks/use-available-blocks'import { useNodesInteractions } from '../../hooks/use-nodes-interactions'import { useNodeMetaData } from '../../hooks/use-nodes-meta-data'-import { useIsChatMode, useNodesReadOnly } from '../../hooks/use-workflow'+import { useNodesReadOnly } from '../../hooks/use-workflow'import { NodeActionsDropdown } from '../index'vi.mock('../../hooks/use-available-blocks', async (importOriginal) => {@@ -46,7 +45,7 @@ vi.mock('../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: vi.fn(),+useNodesReadOnly: vi.fn(),}})@@ -80,7 +79,7 @@ vi.mock('@/service/use-triggers', () => ({}))const mockUseAvailableBlocks = vi.mocked(useAvailableBlocks)-const mockUseIsChatMode = vi.mocked(useIsChatMode)+const mockUseIsChatMode = vi.hoisted(() => vi.fn())const mockUseNodeMetaData = vi.mocked(useNodeMetaData)const mockUseNodesInteractions = vi.mocked(useNodesInteractions)const mockUseNodesReadOnly = vi.mocked(useNodesReadOnly)@@ -151,7 +150,7 @@ describe('node actions menu details', () => {>)mockUseHooksStore.mockImplementation((selector: any) =>selector({- configsMap: { flowType: FlowType.appFlow },+ configsMap: { resourceKind: 'app' },accessControl: { canRun: true },availableNodesMetaData: {nodes: [@@ -341,3 +340,10 @@ describe('node actions menu details', () => {expect(screen.queryByText('common.operation.delete')).not.toBeInTheDocument()})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/node-actions-menu/change-block-popup.tsx b/web/app/components/workflow/node-actions-menu/change-block-popup.tsxindex 196df998bf1..292394597a2 100644--- a/web/app/components/workflow/node-actions-menu/change-block-popup.tsx+++ b/web/app/components/workflow/node-actions-menu/change-block-popup.tsx@@ -1,17 +1,19 @@import type { CommonNodeType, Node, OnSelectBlock } from '@/app/components/workflow/types'import { PopoverClose, PopoverPopup, PopoverTitle } from '@langgenius/dify-ui/popover'import { intersection } from 'es-toolkit/array'+import { useAtomValue } from 'jotai'import { useCallback, useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'import { BlockSelectorContent } from '@/app/components/workflow/block-selector'-import { useHooksStore } from '@/app/components/workflow/hooks-store'+import {+ editorResourceKindAtom,+ isChatflowAtom,+} from '@/app/components/workflow/editor-resource/state'import useNodes from '@/app/components/workflow/store/workflow/use-nodes'import { BlockEnum, isTriggerNode } from '@/app/components/workflow/types'import { getNodeCatalogType } from '@/app/components/workflow/utils'-import { FlowType } from '@/types/common'import { useAvailableBlocks } from '../hooks/use-available-blocks'import { useNodesInteractions } from '../hooks/use-nodes-interactions'-import { useIsChatMode } from '../hooks/use-workflow'type ChangeBlockPopupProps = {nodeId: string@@ -35,15 +37,15 @@ export function ChangeBlockPopup({nodeCatalogType,nodeData.isInIteration || nodeData.isInLoop,)- const isChatMode = useIsChatMode()- const flowType = useHooksStore((s) => s.configsMap?.flowType)+ const isChatflow = useAtomValue(isChatflowAtom)+ const resourceKind = useAtomValue(editorResourceKindAtom)const nodes = useNodes()const hasStartNode = useMemo(() => {return nodes.some((n) => (n.data as CommonNodeType | undefined)?.type === BlockEnum.Start)}, [nodes])const showStartTab =- flowType !== FlowType.ragPipeline &&- (!isChatMode || nodeData.type === BlockEnum.Start || !hasStartNode)+ resourceKind !== 'knowledge-pipeline' &&+ (!isChatflow || nodeData.type === BlockEnum.Start || !hasStartNode)const ignoreNodeIds = useMemo(() => {if (isTriggerNode(nodeData.type as BlockEnum) || nodeData.type === BlockEnum.Start)return [nodeId]diff --git a/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts b/web/app/components/workflow/node-catalog.tssimilarity index 88%rename from web/app/components/workflow-app/hooks/use-available-nodes-meta-data.tsrename to web/app/components/workflow/node-catalog.tsindex 09b8a2fc4ff..4902c32823a 100644--- a/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts+++ b/web/app/components/workflow/node-catalog.ts@@ -1,8 +1,10 @@import type { AvailableNodesMetaData } from '@/app/components/workflow/hooks-store/store'import type { DocPathWithoutLang } from '@/types/doc-paths'+import { useAtomValue } from 'jotai'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import { WORKFLOW_COMMON_NODES } from '@/app/components/workflow/constants/node'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import AnswerDefault from '@/app/components/workflow/nodes/answer/default'import EndDefault from '@/app/components/workflow/nodes/end/default'import StartPlaceholderDefault from '@/app/components/workflow/nodes/start-placeholder/default'@@ -14,7 +16,6 @@ import { BlockEnum } from '@/app/components/workflow/types'import { useDocLink } from '@/context/i18n'import { isAgentV2Enabled, isAgentV2InChatflowEnabled } from '@/features/agent-v2/feature-flag'import { isProductlessDocPathWithAnchor } from '@/types/doc-paths'-import { useIsChatMode } from './use-is-chat-mode'const getNodeHelpLinkPath = (helpLinkUri?: string): DocPathWithoutLang | undefined => {if (!helpLinkUri) return undefined@@ -23,31 +24,31 @@ const getNodeHelpLinkPath = (helpLinkUri?: string): DocPathWithoutLang | undefinreturn isProductlessDocPathWithAnchor(helpLinkPath) ? helpLinkPath : undefined}-export const useAvailableNodesMetaData = () => {+export const useWorkflowNodeCatalog = () => {const { t } = useTranslation(['workflow'])- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const docLink = useDocLink()const agentV2Enabled = isAgentV2Enabled()// Chatflow (advanced-chat) keeps Agent v2 hidden by default; opt in via// NEXT_PUBLIC_ENABLE_AGENT_V2_IN_CHATFLOW. Pure workflows are unaffected.- const shouldUseAgentV2 = agentV2Enabled && (!isChatMode || isAgentV2InChatflowEnabled())+ const shouldUseAgentV2 = agentV2Enabled && (!isChatflow || isAgentV2InChatflowEnabled())const startNodeMetaData = useMemo(() => ({...StartDefault,metaData: {...StartDefault.metaData,- isUndeletable: isChatMode, // start node is undeletable in chat mode, @use-nodes-interactions: handleNodeDelete function+ isUndeletable: isChatflow, // start node is undeletable in chat mode, @use-nodes-interactions: handleNodeDelete function},}),- [isChatMode],+ [isChatflow],)const mergedNodesMetaData = useMemo(() => {return [...WORKFLOW_COMMON_NODES,startNodeMetaData,- ...(isChatMode+ ...(isChatflow? [AnswerDefault]: [StartPlaceholderDefault,@@ -57,7 +58,7 @@ export const useAvailableNodesMetaData = () => {TriggerPluginDefault,]),]- }, [isChatMode, startNodeMetaData])+ }, [isChatflow, startNodeMetaData])const nodesMetaData = useMemo(() =>@@ -106,13 +107,14 @@ export const useAvailableNodesMetaData = () => {[nodesMetaData],)- return useMemo(() => {- return {+ return useMemo(+ () => ({nodes: availableNodesMetaData,nodesMap: {...nodesMetaDataMap,[BlockEnum.VariableAssigner]: nodesMetaDataMap?.[BlockEnum.VariableAggregator],},- }- }, [availableNodesMetaData, nodesMetaDataMap])+ }),+ [availableNodesMetaData, nodesMetaDataMap],+ )}diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/add-variable-popup-with-position.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/add-variable-popup-with-position.spec.tsxindex 1ea4cfa2749..1ac77774489 100644--- a/web/app/components/workflow/nodes/_base/components/__tests__/add-variable-popup-with-position.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/__tests__/add-variable-popup-with-position.spec.tsx@@ -35,7 +35,6 @@ vi.mock('../../../../hooks/use-node-data-update', () => ({useNodeDataUpdate: () => ({ handleNodeDataUpdate: vi.fn() }),}))vi.mock('../../../../hooks/use-workflow', () => ({- useIsChatMode: () => false,useWorkflow: () => ({ getBeforeNodesInSameBranch: () => [] }),}))vi.mock('../../../../hooks/use-workflow-variables', () => ({@@ -74,3 +73,10 @@ it('selects a connection variable from the owning canvas and preserves its focus)expect(canvas).toHaveFocus()})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy.spec.tsxindex f6a0650ad7b..080a0dc8eed 100644--- a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy.spec.tsx@@ -3,8 +3,8 @@ import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'import { WorkflowContext } from '@/app/components/workflow/context'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { createWorkflowStore } from '@/app/components/workflow/store'-import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { createProvider, createStrategy } from '../../../agent/__tests__/strategy-fixture'import { AgentStrategy } from '../agent-strategy'diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/code-generator-button.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/code-generator-button.spec.tsxindex 42fd14813c5..7f7c9fb04a2 100644--- a/web/app/components/workflow/nodes/_base/components/__tests__/code-generator-button.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/__tests__/code-generator-button.spec.tsx@@ -1,5 +1,6 @@-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'import CodeGenerateBtn from '../code-generator-button'@@ -15,7 +16,9 @@ vi.mock('@/app/components/workflow/hooks-store', () => ({describe('CodeGenerateBtn', () => {it('should open the code generator from the named action', async () => {const user = userEvent.setup()- render(<CodeGenerateBtn nodeId="node-1" codeLanguages={CodeLanguage.python3} />)+ render(<CodeGenerateBtn nodeId="node-1" codeLanguages={CodeLanguage.python3} />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await user.click(screen.getByRole('button', { name: 'appDebug.operation.automatic' }))diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.branches.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.branches.spec.tsxindex d745254c884..776f008d74c 100644--- a/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.branches.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.branches.spec.tsx@@ -39,7 +39,7 @@ vi.mock('../../../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => false,+useWorkflow: () => ({getTreeLeafNodes: () => [],getNodeById: () => undefined,@@ -421,3 +421,10 @@ describe('FormInputItem branches', () => {})})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.spec.tsxindex 38d88829de4..b707c0e4f5a 100644--- a/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/__tests__/form-input-item.spec.tsx@@ -16,7 +16,7 @@ vi.mock('../../../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => false,+useWorkflow: () => ({getTreeLeafNodes: () => [],getNodeById: () => undefined,@@ -220,3 +220,10 @@ it.each([false, 0])(})},)++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/node-focus.browser.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/node-focus.browser.spec.tsxindex cacd1ca5b69..776ad6420fc 100644--- a/web/app/components/workflow/nodes/_base/components/__tests__/node-focus.browser.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/__tests__/node-focus.browser.spec.tsx@@ -1,13 +1,34 @@+import type { ReactElement } from 'react'import type { NodeProps } from 'reactflow'import type { CommonNodeType } from '../../../../types'import ReactFlow from 'reactflow'import { page, userEvent } from 'vite-plus/test/browser'-import { render } from 'vitest-browser-react'+import { render as renderBrowser } from 'vitest-browser-react'+import { consoleQuery } from '@/service/console'+import { QueryClientTestProvider } from '@/test/console/query-provider'+import { createAppDetailFixture } from '@/test/fixtures/app'+import { createTestQueryClient } from '@/test/query-client'+import { EditorResourceScope } from '../../../../editor-resource/provider'import { BlockEnum } from '../../../../types'import NodeControl from '../node-control'import { NodeSourceHandle, NodeTargetHandle } from '../node-handle'import 'reactflow/dist/style.css'+const render = (ui: ReactElement) => {+ const queryClient = createTestQueryClient()+ queryClient.setQueryData(+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),+ createAppDetailFixture({ id: 'app-1', mode: 'workflow' }),+ )+ return renderBrowser(+ <QueryClientTestProvider queryClient={queryClient}>+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>+ {ui}+ </EditorResourceScope>+ </QueryClientTestProvider>,+ )+}+// Plugin installation is outside node trigger and popup focus ownership.vi.mock('@/app/components/plugins/install-plugin/install-from-marketplace', () => ({default: () => null,@@ -23,7 +44,6 @@ vi.mock('../../../../hooks/use-nodes-interactions', () => ({useNodesInteractions: () => ({ handleNodeAdd: vi.fn(), handleNodeSelect: vi.fn() }),}))vi.mock('../../../../hooks/use-workflow', () => ({- useIsChatMode: () => false,useNodesReadOnly: () => ({ nodesReadOnly: false, getNodesReadOnly: () => false }),}))vi.mock('../../../../hooks/use-nodes-meta-data', () => ({@@ -43,7 +63,6 @@ vi.mock('@/app/components/workflow/store', () => ({vi.mock('@/app/components/workflow/hooks-store', () => ({useHooksStore: (selector: (state: Record<string, unknown>) => unknown) =>selector({- configsMap: { flowType: 'app-flow' },availableNodesMetaData: { nodes: [] },accessControl: { canRun: false },}),diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.browser.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.browser.spec.tsxindex acb7fa3685d..31c90bbc3e2 100644--- a/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.browser.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.browser.spec.tsx@@ -1,13 +1,18 @@-import type { RefObject } from 'react'+import type { ReactElement, RefObject } from 'react'import type { Connection, NodeProps } from 'reactflow'import type { CommonNodeType, OnSelectBlock } from '../../../../types'import type { HumanInputNodeType } from '../../../human-input/types'import { useRef, useState } from 'react'import ReactFlow, { ReactFlowProvider, useReactFlow } from 'reactflow'import { page, userEvent } from 'vite-plus/test/browser'-import { render } from 'vitest-browser-react'+import { render as renderBrowser } from 'vitest-browser-react'+import { consoleQuery } from '@/service/console'+import { QueryClientTestProvider } from '@/test/console/query-provider'+import { createAppDetailFixture } from '@/test/fixtures/app'+import { createTestQueryClient } from '@/test/query-client'import { WorkflowContext } from '../../../../context'import CustomEdge from '../../../../custom-edge'+import { EditorResourceScope } from '../../../../editor-resource/provider'import { useWorkflowControlScale } from '../../../../hooks/use-workflow-control-scale'import { createWorkflowStore } from '../../../../store/workflow'import { BlockEnum } from '../../../../types'@@ -17,6 +22,21 @@ import { NodeSourceHandle, NodeTargetHandle } from '../node-handle'import 'reactflow/dist/style.css'import '../../../../style.css'+const render = (ui: ReactElement) => {+ const queryClient = createTestQueryClient()+ queryClient.setQueryData(+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),+ createAppDetailFixture({ id: 'app-1', mode: 'workflow' }),+ )+ return renderBrowser(+ <QueryClientTestProvider queryClient={queryClient}>+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>+ {ui}+ </EditorResourceScope>+ </QueryClientTestProvider>,+ )+}+const { handleNodeAdd } = vi.hoisted(() => ({ handleNodeAdd: vi.fn() }))vi.mock('../../../../hooks/use-available-blocks', () => ({@@ -29,7 +49,6 @@ vi.mock('../../../../hooks/use-nodes-interactions', () => ({useNodesInteractions: () => ({ handleNodeAdd }),}))vi.mock('../../../../hooks/use-workflow', () => ({- useIsChatMode: () => false,useNodesReadOnly: () => ({ getNodesReadOnly: () => false }),}))vi.mock('../../../../hooks-store', () => ({diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.spec.tsxindex 57c7ff0c34b..daba060a013 100644--- a/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/__tests__/node-handle.spec.tsx@@ -1,14 +1,15 @@import type { ReactNode } from 'react'import type { CommonNodeType } from '@/app/components/workflow/types'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum } from '@/app/components/workflow/types'import { NodeSourceHandle, NodeTargetHandle } from '../node-handle'type MockHooksState = {availablePrevBlocks: BlockEnum[]availableNextBlocks: BlockEnum[]- isChatMode: boolean+ isChatflow: booleanisReadOnly: boolean}@@ -31,7 +32,7 @@ const {const mockHooksState: MockHooksState = {availablePrevBlocks: [],availableNextBlocks: [],- isChatMode: false,+ isChatflow: false,isReadOnly: false,}const mockStoreState: MockStoreState = {@@ -112,7 +113,7 @@ vi.mock('../../../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => mockHooksState.isChatMode,+useNodesReadOnly: () => ({getNodesReadOnly: () => mockHooksState.isReadOnly,}),@@ -129,7 +130,7 @@ vi.mock('@/app/components/workflow/store', () => ({vi.mock('@/app/components/workflow/hooks-store', () => ({useHooksStore: (selector: (state: Record<string, unknown>) => unknown) =>selector({- configsMap: { flowType: 'app-flow' },+ configsMap: { resourceKind: 'app-flow' },availableNodesMetaData: { nodes: [] },}),}))@@ -176,6 +177,7 @@ const renderTargetHandle = (dataOverrides: Partial<CommonNodeType> = {}) => {nodeSelectorClassName="custom-selector"handleClassName="custom-target-handle"/>,+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)}@@ -192,6 +194,7 @@ const renderSourceHandle = (handleClassName="custom-source-handle"{...propsOverrides}/>,+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)}@@ -201,7 +204,7 @@ describe('node-handle', () => {mockHooksState.availablePrevBlocks = [BlockEnum.Code]mockHooksState.availableNextBlocks = [BlockEnum.Code]- mockHooksState.isChatMode = false+ mockHooksState.isChatflow = falsemockHooksState.isReadOnly = falsemockStoreState.shouldAutoOpenStartNodeSelector = false@@ -316,7 +319,9 @@ describe('node-handle', () => {describe('NodeSourceHandle auto-open', () => {it('restores the previous focus when the start selector opens automatically', async () => {const user = userEvent.setup()- render(<button type="button">Previous action</button>)+ render(<button type="button">Previous action</button>, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })const previousAction = screen.getByRole('button', { name: 'Previous action' })await user.click(previousAction)mockStoreState.shouldAutoOpenStartNodeSelector = true@@ -347,7 +352,7 @@ describe('node-handle', () => {})it('should skip source auto-open in chat mode and only reset the start selector flag', () => {- mockHooksState.isChatMode = true+ mockHooksState.isChatflow = truemockStoreState.shouldAutoOpenStartNodeSelector = truerenderSourceHandle({ type: BlockEnum.Start })@@ -382,3 +387,10 @@ describe('node-handle', () => {})})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockHooksState.isChatflow) }+})diff --git a/web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsx b/web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsxindex 5a208909911..76c65026c23 100644--- a/web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsx+++ b/web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsx@@ -1,9 +1,11 @@import type { ValueSelector, Var, VarType } from '../../../types'import { useClickAway } from 'ahooks'+import { useAtomValue } from 'jotai'import { memo, useCallback, useMemo, useRef } from 'react'import { useStore as useReactFlowStore } from 'reactflow'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { useNodeDataUpdate } from '../../../hooks/use-node-data-update'-import { useIsChatMode, useWorkflow } from '../../../hooks/use-workflow'+import { useWorkflow } from '../../../hooks/use-workflow'import { useWorkflowVariables } from '../../../hooks/use-workflow-variables'import { useStore } from '../../../store'import { useVariableAssigner } from '../../variable-assigner/hooks'@@ -21,7 +23,7 @@ const AddVariablePopupWithPosition = ({ nodeId, nodeData }: AddVariablePopupWithconst setShowAssignVariablePopup = useStore((s) => s.setShowAssignVariablePopup)const { handleNodeDataUpdate } = useNodeDataUpdate()const { handleAddVariableInAddVariablePopupWithPosition } = useVariableAssigner()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const { getBeforeNodesInSameBranch } = useWorkflow()const { getNodeAvailableVars } = useWorkflowVariables()@@ -51,8 +53,8 @@ const AddVariablePopupWithPosition = ({ nodeId, nodeData }: AddVariablePopupWith} as any,],hideEnv: true,- hideChatVar: !isChatMode,- isChatMode,+ hideChatVar: !isChatflow,+ isChatflow,filterVar: filterVar(outputType as VarType),}).map((node) => ({@@ -66,7 +68,7 @@ const AddVariablePopupWithPosition = ({ nodeId, nodeData }: AddVariablePopupWithshowAssignVariablePopup,getNodeAvailableVars,getBeforeNodesInSameBranch,- isChatMode,+ isChatflow,outputType,])diff --git a/web/app/components/workflow/nodes/_base/components/agent-strategy.tsx b/web/app/components/workflow/nodes/_base/components/agent-strategy.tsxindex 5015e7a78d2..3b7233cf9c9 100644--- a/web/app/components/workflow/nodes/_base/components/agent-strategy.tsx+++ b/web/app/components/workflow/nodes/_base/components/agent-strategy.tsx@@ -37,7 +37,6 @@ import Form from '@/app/components/header/account-setting/model-provider-page/moimport { useDocLink } from '@/context/i18n'import { useRenderI18nObject } from '@/hooks/use-i18n'import Link from '@/next/link'-import { AppModeEnum } from '@/types/app'import { useWorkflowStore } from '../../../store'import { AgentStrategySelector } from './agent-strategy-selector'import Field from './field'@@ -172,7 +171,7 @@ export const AgentStrategy = memo((props: AgentStrategyProps) => {modelConfig={defaultModel.data? {- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,name: defaultModel.data.model,provider: defaultModel.data.provider.provider,completion_params: {},diff --git a/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx b/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsxindex e90f4292cc2..d604e42568d 100644--- a/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx+++ b/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx@@ -57,7 +57,7 @@ const FormItem: FC<Props> = ({const { t } = useTranslation(['appDebug', 'common', 'workflow'])const labelId = React.useId()const { type } = payload- const fileSettings = useHooksStore((s) => s.configsMap?.fileSettings)+ const fileSettings = useHooksStore((s) => s.fileSettings)const jsonSchemaPlaceholder = React.useMemo(() => {const schema = (payload as any)?.json_schemaif (!schema) return ''diff --git a/web/app/components/workflow/nodes/_base/components/code-generator-button.tsx b/web/app/components/workflow/nodes/_base/components/code-generator-button.tsxindex f58943c21f1..864854322a7 100644--- a/web/app/components/workflow/nodes/_base/components/code-generator-button.tsx+++ b/web/app/components/workflow/nodes/_base/components/code-generator-button.tsx@@ -1,15 +1,17 @@'use client'+import type { FC } from 'react'import type { CodeLanguage } from '../../code/types'import type { GenRes } from '@/service/debug'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useAtomValue } from 'jotai'import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import { GetCodeGeneratorResModal } from '@/app/components/app/configuration/config/code-generator/get-code-generator-res'-import { AppModeEnum } from '@/types/app'-import { useHooksStore } from '../../../hooks-store'+import { getEditorResourceId } from '@/app/components/workflow/editor-resource/resource'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'type Props = Readonly<{nodeId: string@@ -35,7 +37,8 @@ const CodeGenerateBtn: FC<Props> = ({},[onGenerated],)- const configsMap = useHooksStore((s) => s.configsMap)+ const resource = useAtomValue(editorResourceAtom)+ const resourceId = getEditorResourceId(resource)return (<div className={cn(className)}>@@ -48,12 +51,12 @@ const CodeGenerateBtn: FC<Props> = ({</IconButton>{showAutomatic && (<GetCodeGeneratorResModal- mode={AppModeEnum.CHAT}+ modelMode="chat"isShow={showAutomatic}codeLanguages={codeLanguages}onClose={() => setShowAutomatic(false)}onFinished={handleAutomaticRes}- flowId={configsMap?.flowId || ''}+ flowId={resourceId || ''}nodeId={nodeId}currentCode={currentCode}/>diff --git a/web/app/components/workflow/nodes/_base/components/input-support-select-var.tsx b/web/app/components/workflow/nodes/_base/components/input-support-select-var.tsxindex 5b59ed2eec5..57ca0455e44 100644--- a/web/app/components/workflow/nodes/_base/components/input-support-select-var.tsx+++ b/web/app/components/workflow/nodes/_base/components/input-support-select-var.tsx@@ -1,14 +1,17 @@'use client'+import type { FC } from 'react'import type { Node, NodeOutPutVar } from '@/app/components/workflow/types'import { cn } from '@langgenius/dify-ui/cn'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { useBoolean } from 'ahooks'import { noop } from 'es-toolkit/function'+import { useAtomValue } from 'jotai'import * as React from 'react'import { useEffect } from 'react'import { useTranslation } from 'react-i18next'import PromptEditor from '@/app/components/base/prompt-editor'+import { editorResourceKindAtom } from '@/app/components/workflow/editor-resource/state'import { useStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'@@ -42,7 +45,7 @@ const Editor: FC<Props> = ({availableNodes = [],insertVarTipToLeft,}) => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const [isFocus, { setTrue: setFocus, setFalse: setBlur }] = useBoolean(false)@@ -50,7 +53,7 @@ const Editor: FC<Props> = ({onFocusChange?.(isFocus)}, [isFocus])- const pipelineId = useStore((s) => s.pipelineId)+ const resourceKind = useAtomValue(editorResourceKindAtom)const setShowInputFieldPanel = useStore((s) => s.setShowInputFieldPanel)return (@@ -100,7 +103,7 @@ const Editor: FC<Props> = ({}return acc}, {} as any),- showManageInputField: !!pipelineId,+ showManageInputField: resourceKind === 'knowledge-pipeline',onManageInputField: () => setShowInputFieldPanel?.(true),}}onChange={onChange}diff --git a/web/app/components/workflow/nodes/_base/components/node-handle.tsx b/web/app/components/workflow/nodes/_base/components/node-handle.tsxindex e26dc4bd2fa..6919ce054ea 100644--- a/web/app/components/workflow/nodes/_base/components/node-handle.tsx+++ b/web/app/components/workflow/nodes/_base/components/node-handle.tsx@@ -3,14 +3,16 @@ import type { MouseEvent } from 'react'import type { BlockDefaultValue } from '../../../block-selector/types'import type { Node } from '../../../types'import { cn } from '@langgenius/dify-ui/cn'+import { useAtomValue } from 'jotai'import { memo, useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { Handle, Position } from 'reactflow'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { hasAgentV2OutputRoutes } from '@/app/components/workflow/nodes/agent-v2/types'import BlockSelector from '../../../block-selector'import { useAvailableBlocks } from '../../../hooks/use-available-blocks'import { useNodesInteractions } from '../../../hooks/use-nodes-interactions'-import { useIsChatMode, useNodesReadOnly } from '../../../hooks/use-workflow'+import { useNodesReadOnly } from '../../../hooks/use-workflow'import { useStore, useWorkflowStore } from '../../../store'import { BlockEnum, NodeRunningStatus } from '../../../types'import { getNodeCatalogType } from '../../../utils'@@ -26,8 +28,8 @@ type NodeHandleProps = {// React Flow measures the 16px handle box. Enlarge its hit area with ::before// and scale the button independently so zoom compensation cannot move edge endpoints.-const canAutoOpenStartNodeSelector = (nodeType: BlockEnum, isChatMode: boolean) => {- if (isChatMode) return false+const canAutoOpenStartNodeSelector = (nodeType: BlockEnum, isChatflow: boolean) => {+ if (isChatflow) return falsereturn (nodeType === BlockEnum.Start ||@@ -147,7 +149,7 @@ export const NodeSourceHandle = memo(nodeSelectorClassName,showExceptionStatus,}: NodeHandleProps) => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const shouldAutoOpenStartNodeSelector = useStore((s) => s.shouldAutoOpenStartNodeSelector)const setShouldAutoOpenStartNodeSelector = useStore((s) => s.setShouldAutoOpenStartNodeSelector)const setHasSelectedStartNode = useStore((s) => s.setHasSelectedStartNode)@@ -159,9 +161,9 @@ export const NodeSourceHandle = memo(data.isInIteration || data.isInLoop,)const isConnectable = !!availableNextBlocks.length- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const shouldAutoOpen =- shouldAutoOpenStartNodeSelector && canAutoOpenStartNodeSelector(data.type, isChatMode)+ shouldAutoOpenStartNodeSelector && canAutoOpenStartNodeSelector(data.type, isChatflow)const [open, setOpen] = useState(() => shouldAutoOpen)const triggerRef = useRef<HTMLButtonElement>(null)const preserveOutsideFocusRef = useRef(false)@@ -208,7 +210,7 @@ export const NodeSourceHandle = memo(useEffect(() => {if (!shouldAutoOpenStartNodeSelector) return- if (isChatMode) {+ if (isChatflow) {setShouldAutoOpenStartNodeSelector?.(false)return}@@ -223,7 +225,7 @@ export const NodeSourceHandle = memo(}, [shouldAutoOpenStartNodeSelector,data.type,- isChatMode,+ isChatflow,setShouldAutoOpenStartNodeSelector,setHasSelectedStartNode,workflowStoreApi,diff --git a/web/app/components/workflow/nodes/_base/components/prompt/editor.tsx b/web/app/components/workflow/nodes/_base/components/prompt/editor.tsxindex 082ab9ead48..488b9217d87 100644--- a/web/app/components/workflow/nodes/_base/components/prompt/editor.tsx+++ b/web/app/components/workflow/nodes/_base/components/prompt/editor.tsx@@ -1,4 +1,5 @@'use client'+import type { FC, ReactNode } from 'react'import type { ModelConfig, Node, NodeOutPutVar, Variable } from '../../../../types'import { cn } from '@langgenius/dify-ui/cn'@@ -9,11 +10,13 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooimport { RiDeleteBinLine } from '@remixicon/react'import { useBoolean } from 'ahooks'import copy from 'copy-to-clipboard'+import { useAtomValue } from 'jotai'import * as React from 'react'import { useCallback, useRef } from 'react'import { useTranslation } from 'react-i18next'import PromptEditor from '@/app/components/base/prompt-editor'import { PROMPT_EDITOR_INSERT_QUICKLY } from '@/app/components/base/prompt-editor/plugins/update-block'+import { editorResourceKindAtom } from '@/app/components/workflow/editor-resource/state'import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor/editor-support-vars'import ToggleExpandBtn from '@/app/components/workflow/nodes/_base/components/toggle-expand-btn'import useToggleExpend from '@/app/components/workflow/nodes/_base/hooks/use-toggle-expend'@@ -132,7 +135,7 @@ const Editor: FC<Props> = ({}const getVarType = useWorkflowVariableType()- const pipelineId = useStore((s) => s.pipelineId)+ const resourceKind = useAtomValue(editorResourceKindAtom)const setShowInputFieldPanel = useStore((s) => s.setShowInputFieldPanel)return (@@ -368,7 +371,7 @@ const Editor: FC<Props> = ({}return acc}, {} as any),- showManageInputField: !!pipelineId,+ showManageInputField: resourceKind === 'knowledge-pipeline',onManageInputField: () => setShowInputFieldPanel?.(true),}}onChange={onChange}diff --git a/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts b/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.tsindex 44b23ab696a..a0a0a0c6b94 100644--- a/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts+++ b/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts@@ -15,7 +15,6 @@ import {PromptRole,VarType,} from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import { findUsedVarNodes, getNodeUsedVars, toNodeAvailableVars, updateNodeVars } from '../utils'const createNode = <T>(data: Node<T>['data']): Node<T> => ({@@ -38,7 +37,7 @@ const createLLMNodeData = (promptTemplate: PromptItem[]): LLMNodeType => ({model: {provider: 'provider',name: 'model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},prompt_template: promptTemplate,@@ -73,7 +72,7 @@ describe('variable utils', () => {const availableVars = toNodeAvailableVars({beforeNodes: [],- isChatMode: false,+ isChatflow: false,environmentVariables,filterVar: () => true,allPluginInfoList: {},@@ -95,7 +94,7 @@ describe('variable utils', () => {})const availableVars = toNodeAvailableVars({beforeNodes: [node],- isChatMode: false,+ isChatflow: false,filterVar: () => true,allPluginInfoList: {},})@@ -124,7 +123,7 @@ describe('variable utils', () => {},},})- const options = { beforeNodes: [node], isChatMode: false, allPluginInfoList: {} }+ const options = { beforeNodes: [node], isChatflow: false, allPluginInfoList: {} }const availableVars = toNodeAvailableVars({ ...options, filterVar: () => true })expect(availableVars.find((item) => item.nodeId === node.id)?.vars).toEqual(expect.arrayContaining([@@ -160,7 +159,7 @@ describe('variable utils', () => {const availableVars = toNodeAvailableVars({beforeNodes: [node],- isChatMode: false,+ isChatflow: false,filterVar: () => true,allPluginInfoList: {},})@@ -204,7 +203,7 @@ describe('variable utils', () => {const availableVars = toNodeAvailableVars({beforeNodes: [node],- isChatMode: false,+ isChatflow: false,filterVar: () => true,allPluginInfoList: {},})@@ -513,7 +512,7 @@ it('keeps datasource output variables typed through the public picker projection})const options = {beforeNodes: [node],- isChatMode: false,+ isChatflow: false,allPluginInfoList: { dataSourceList: [provider] },}const all = toNodeAvailableVars({ ...options, filterVar: () => true }).find(diff --git a/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.branches.spec.tsx b/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.branches.spec.tsxindex df425ac511e..d3f0d8ec5d7 100644--- a/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.branches.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.branches.spec.tsx@@ -27,7 +27,7 @@ vi.mock('../../../../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => false,+useWorkflow: () => ({getTreeLeafNodes: () => [],getNodeById: () => undefined,@@ -294,3 +294,10 @@ describe('VarReferencePicker branches', () => {expect(screen.queryByTestId('var-reference-picker-error-icon')).not.toBeInTheDocument()})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})diff --git a/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.spec.tsx b/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.spec.tsxindex bf3c5d90851..97ae748dc60 100644--- a/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.spec.tsx@@ -15,7 +15,7 @@ vi.mock('../../../../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => false,+useWorkflow: () => ({getTreeLeafNodes: () => [],getNodeById: () => undefined,@@ -174,3 +174,10 @@ describe('VarReferencePicker', () => {expect(onChange).not.toHaveBeenCalled()})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})diff --git a/web/app/components/workflow/nodes/_base/components/variable/utils.ts b/web/app/components/workflow/nodes/_base/components/variable/utils.tsindex 4ac9f6f98ab..85a655a32b8 100644--- a/web/app/components/workflow/nodes/_base/components/variable/utils.ts+++ b/web/app/components/workflow/nodes/_base/components/variable/utils.ts@@ -64,7 +64,6 @@ import { resolveVarType } from '@/app/components/workflow/nodes/tool/output-scheimport PluginTriggerNodeDefault from '@/app/components/workflow/nodes/trigger-plugin/default'import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'import { VAR_REGEX } from '@/config'-import { AppModeEnum } from '@/types/app'import { OUTPUT_FILE_SUB_VARIABLES } from '../../../constants'import { Type } from '../../../llm/types'@@ -300,7 +299,7 @@ const findExceptVarInObject = (const formatItem = (item: any,- isChatMode: boolean,+ isChatflow: boolean,filterVar: (payload: Var, selector: ValueSelector) => boolean,allPluginInfoList: WorkflowPluginCatalogs,ragVars?: Var[],@@ -338,7 +337,7 @@ const formatItem = (return varRes})- if (isChatMode) {+ if (isChatflow) {res.vars.push({variable: 'sys.query',type: VarType.string,@@ -742,7 +741,7 @@ export const removeFileVars = (nodeWithVars: NodeOutPutVar[]) => {export const toNodeOutputVars = (nodes: any[],- isChatMode: boolean,+ isChatflow: boolean,filterVar = (_payload: Var, _selector: ValueSelector) => true,environmentVariables: EnvironmentVariable[] = [],conversationVariables: ConversationVariable[] = [],@@ -774,7 +773,7 @@ export const toNodeOutputVars = (data: {title: 'SYSTEM',type: 'global',- globalVarList: getGlobalVars(isChatMode),+ globalVarList: getGlobalVars(isChatflow),},}// RAG_PIPELINE_NODE data format@@ -805,7 +804,7 @@ export const toNodeOutputVars = (const res = [...sortedNodes.filter((node) => SUPPORT_OUTPUT_VARS_NODE.includes(node?.data?.type)),...(environmentVariables.length > 0 ? [ENV_NODE] : []),- ...(isChatMode && conversationVariables.length > 0 ? [CHAT_VAR_NODE] : []),+ ...(isChatflow && conversationVariables.length > 0 ? [CHAT_VAR_NODE] : []),GLOBAL_VAR_NODE,...(RAG_PIPELINE_NODE.data.ragVariables.length > 0 ? [RAG_PIPELINE_NODE] : []),]@@ -819,7 +818,7 @@ export const toNodeOutputVars = (return {...formatItem(node,- isChatMode,+ isChatflow,filterVar,allPluginInfoList,ragVariablesInDataSource.map((ragVariable: RAGPipelineVariable) => {@@ -947,7 +946,7 @@ export const getVarType = ({isIterationItem,isLoopItem,availableNodes,- isChatMode,+ isChatflow,isConstant,environmentVariables = [],conversationVariables = [],@@ -961,7 +960,7 @@ export const getVarType = ({isIterationItem?: booleanisLoopItem?: booleanavailableNodes: any[]- isChatMode: boolean+ isChatflow: booleanisConstant?: booleanenvironmentVariables?: EnvironmentVariable[]conversationVariables?: ConversationVariable[]@@ -974,7 +973,7 @@ export const getVarType = ({const beforeNodesOutputVars = toNodeOutputVars(availableNodes,- isChatMode,+ isChatflow,undefined,environmentVariables,conversationVariables,@@ -1090,7 +1089,7 @@ export const toNodeAvailableVars = ({parentNode,t,beforeNodes,- isChatMode,+ isChatflow,environmentVariables,conversationVariables,ragVariables,@@ -1102,7 +1101,7 @@ export const toNodeAvailableVars = ({t?: WorkflowTranslate// to get those nodes output varsbeforeNodes: Node[]- isChatMode: boolean+ isChatflow: boolean// envenvironmentVariables?: EnvironmentVariable[]// chat var@@ -1115,7 +1114,7 @@ export const toNodeAvailableVars = ({}): NodeOutPutVar[] => {const beforeNodesOutputVars = toNodeOutputVars(beforeNodes,- isChatMode,+ isChatflow,filterVar,environmentVariables,conversationVariables,@@ -1131,7 +1130,7 @@ export const toNodeAvailableVars = ({isIterationItem: true,valueSelector: iterationNode?.data.iterator_selector || [],availableNodes: beforeNodes,- isChatMode,+ isChatflow,environmentVariables,conversationVariables,allPluginInfoList,@@ -1232,7 +1231,7 @@ export const getNodeUsedVars = (node: Node, { forExecution = false } = {}): Valu}case BlockEnum.LLM: {const payload = data as LLMNodeType- const isChatModel = payload.model?.mode === AppModeEnum.CHAT+ const isChatModel = payload.model?.mode === 'chat'let prompts: string[] = []if (isChatModel) {prompts = (payload.prompt_template as PromptItem[])?.flatMap(getPromptItemTexts) || []@@ -1571,7 +1570,7 @@ export const updateNodeVars = (}case BlockEnum.LLM: {const payload = data as LLMNodeType- const isChatModel = payload.model?.mode === AppModeEnum.CHAT+ const isChatModel = payload.model?.mode === 'chat'if (isChatModel) {payload.prompt_template = (payload.prompt_template as PromptItem[]).map((prompt) =>replaceOldVarInPromptItem(prompt, oldVarSelector, newVarSelector),@@ -1959,7 +1958,7 @@ const varsToValueSelectorList = (varToValueSelectorList(vars as Var, parentValueSelector, res)}-export const getNodeOutputVars = (node: Node, isChatMode: boolean): ValueSelector[] => {+export const getNodeOutputVars = (node: Node, isChatflow: boolean): ValueSelector[] => {const { data, id } = nodeconst { type } = datalet res: ValueSelector[] = []@@ -1971,7 +1970,7 @@ export const getNodeOutputVars = (node: Node, isChatMode: boolean): ValueSelectoreturn [id, v.variable]})- if (isChatMode) {+ if (isChatflow) {res.push([id, 'sys', 'query'])res.push([id, 'sys', 'files'])}diff --git a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsxindex 452a5fca058..7f875dc2cc1 100644--- a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx+++ b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx@@ -21,18 +21,19 @@ import { cn } from '@langgenius/dify-ui/cn'import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'import { noop } from 'es-toolkit/function'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import * as React from 'react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { useNodes, useReactFlow, useStoreApi } from 'reactflow'import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'// import type { BaseResource, BaseResourceProvider } from '@/app/components/workflow/nodes/_base/types'import { VarKindType } from '@/app/components/workflow/nodes/_base/types'import { useStore as useWorkflowStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'import { isExceptionVariable } from '@/app/components/workflow/utils'import { useFetchDynamicOptions } from '@/service/use-plugins'-import { useIsChatMode } from '../../../../hooks/use-workflow'import { useWorkflowVariables } from '../../../../hooks/use-workflow-variables'import useAvailableVarList from '../../hooks/use-available-var-list'import { removeFileVars, varTypeToStructType } from './utils'@@ -122,10 +123,10 @@ const VarReferencePicker: FC<Props> = ({currentProvider,preferSchemaType,}) => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const store = useStoreApi()const nodes = useNodes<CommonNodeType>()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const isWorkflowDataLoaded = useWorkflowStore((s) => s.isWorkflowDataLoaded)const { getCurrentVariableType } = useWorkflowVariables()const { availableVars, availableNodesWithParent: availableNodes } = useAvailableVarList(nodeId, {@@ -276,7 +277,7 @@ const VarReferencePicker: FC<Props> = ({parentNode: isInIteration ? iterationNode : loopNode,valueSelector: value as ValueSelector,availableNodes,- isChatMode,+ isChatflow,isConstant: !!isConstant,preferSchemaType,})diff --git a/web/app/components/workflow/nodes/_base/components/variable/var-reference-popup.tsx b/web/app/components/workflow/nodes/_base/components/variable/var-reference-popup.tsxindex 27aaacc4c8f..5ccd346ed57 100644--- a/web/app/components/workflow/nodes/_base/components/variable/var-reference-popup.tsx+++ b/web/app/components/workflow/nodes/_base/components/variable/var-reference-popup.tsx@@ -1,10 +1,12 @@'use client'+import type { FC, RefObject } from 'react'import type { NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'+import { useAtomValue } from 'jotai'import * as React from 'react'-import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import ListEmpty from '@/app/components/base/list-empty'+import { editorResourceKindAtom } from '@/app/components/workflow/editor-resource/state'import { useStore } from '@/app/components/workflow/store'import VarReferenceVars from './var-reference-vars'@@ -26,9 +28,9 @@ const VarReferencePopup: FC<Props> = ({isSupportFileVar = true,preferSchemaType,}) => {- const { t } = useTranslation(['workflow'])- const pipelineId = useStore((s) => s.pipelineId)- const showManageRagInputFields = useMemo(() => !!pipelineId, [pipelineId])+ const { t } = useTranslation(['workflow'] as const)+ const resourceKind = useAtomValue(editorResourceKindAtom)+ const showManageRagInputFields = resourceKind === 'knowledge-pipeline'const setShowInputFieldPanel = useStore((s) => s.setShowInputFieldPanel)// max-h-[300px] overflow-y-auto todo: use portal to handle long listdiff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/helpers.spec.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/helpers.spec.tsxindex f59d2f3d46d..2b8852e9122 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/helpers.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/helpers.spec.tsx@@ -22,8 +22,8 @@ describe('workflow-panel helpers', () => {payload: Partial<CustomRunFormProps['payload']>,): CustomRunFormProps => ({nodeId: 'node-1',- flowId: 'flow-1',- flowType: 'app' as CustomRunFormProps['flowType'],+ resource: { kind: 'app', appId: 'flow-1', mode: 'workflow' },+payload: payload as CustomRunFormProps['payload'],setRunResult: vi.fn(),setIsRunAfterSingleRun: vi.fn(),diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsxindex 5cfda71a375..b58b36c5e6c 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx@@ -182,14 +182,14 @@ vi.mock('../../../../../hooks/use-workflow-history', async (importOriginal) => {vi.mock('@/app/components/workflow/hooks-store', () => ({useHooksStore: (selector: (state: {- configsMap: { flowId: string; flowType: string }+ configsMap: { flowId: string; resourceKind: string }accessControl: { canRun: boolean }}) => unknown,) =>selector({configsMap: {flowId: 'flow-1',- flowType: 'app',+ resourceKind: 'app',},accessControl: {canRun: mockCanRun,diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsxindex 24b5391f58f..e73379f67ce 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx@@ -8,6 +8,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooimport { RiCloseLine, RiPlayLargeLine } from '@remixicon/react'import { useSuspenseQuery } from '@tanstack/react-query'import { debounce } from 'es-toolkit/compat'+import { useAtomValue } from 'jotai'import { useQueryState } from 'nuqs'import * as React from 'react'import { cloneElement, memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'@@ -31,6 +32,10 @@ import { ReadmeEntrance } from '@/app/components/plugins/readme-panel/entrance'import BlockIcon from '@/app/components/workflow/block-icon'import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'import { useCollaboration } from '@/app/components/workflow/collaboration/hooks/use-collaboration'+import {+ editorAppIdAtom,+ editorResourceAtom,+} from '@/app/components/workflow/editor-resource/state'import { useHooksStore } from '@/app/components/workflow/hooks-store'import { NodeActionsDropdown } from '@/app/components/workflow/node-actions-menu'import Split from '@/app/components/workflow/nodes/_base/components/split'@@ -47,10 +52,8 @@ import {isSupportCustomRunForm,} from '@/app/components/workflow/utils'import { userProfileQueryOptions } from '@/features/account-profile/client'-import { useParams } from '@/next/navigation'import { useAllBuiltInTools } from '@/service/use-tools'import { useAllTriggerPlugins } from '@/service/use-triggers'-import { FlowType } from '@/types/common'import { useAvailableBlocks } from '../../../../hooks/use-available-blocks'import useInspectVarsCrud from '../../../../hooks/use-inspect-vars-crud'import { useNodeDataUpdate } from '../../../../hooks/use-node-data-update'@@ -96,13 +99,13 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {const { t } = useTranslation(['common', 'workflow', 'workflowDebug'])const panelId = useId()const language = useLanguage()- const appId = useStore((s) => s.appId)+ const appId = useAtomValue(editorAppIdAtom)const { data: userProfile } = useSuspenseQuery({...userProfileQueryOptions(),select: (data) => data.profile,})const canEdit = useHooksStore((s) => s.accessControl.canEdit)- const { isConnected, nodePanelPresence } = useCollaboration(appId as string, canEdit)+ const { isConnected, nodePanelPresence } = useCollaboration(appId, canEdit)const messageLogItem = useStore((state) => state.messageLogItem)const isSingleRunning = data._singleRunningStatus === NodeRunningStatus.Running@@ -260,7 +263,6 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {const isChildNode = !!(data.isInIteration || data.isInLoop)const nodeMetaType = getNodeCatalogType(data)const isSupportSingleRun = canRunBySingle(data.type, isChildNode)- const { appId: routeAppId } = useParams<{ appId?: string }>()const hasClickRunning = useRef(false)const [isPaused, setIsPaused] = useState(false)@@ -294,7 +296,7 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {const { nodesMap } = useNodesMetaData()- const configsMap = useHooksStore((s) => s.configsMap)+ const resource = useAtomValue(editorResourceAtom)const canRun = useHooksStore((s) => s.accessControl.canRun)const {isShowSingleRun,@@ -321,8 +323,7 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {getFilteredExistVarForms,} = useLastRun<typeof data>({id,- flowId: configsMap?.flowId || '',- flowType: configsMap?.flowType || FlowType.appFlow,+ resource,data,defaultRunInputData: nodesMap?.[nodeMetaType]?.defaultRunInputData || {},isPaused,@@ -504,8 +505,7 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {const customRunForm = isCustomRunFormNode? getCustomRunForm({nodeId: id,- flowId: configsMap?.flowId || '',- flowType: configsMap?.flowType || FlowType.appFlow,+ resource,payload: data,setRunResult,setIsRunAfterSingleRun,@@ -778,7 +778,6 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {{!isStartPlaceholderPanel && (<TabsPanel value={TabType.lastRun} className="flex flex-1 flex-col overflow-y-auto"><LastRun- appId={routeAppId || ''}nodeId={id}canSingleRun={isSupportSingleRun}runningStatus={runningStatus}diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsxindex b9d4469cdbc..96f3fa69e97 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/index.spec.tsx@@ -1,4 +1,5 @@-import { act, render, screen } from '@testing-library/react'+import { act, screen } from '@testing-library/react'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { NodeRunningStatus } from '@/app/components/workflow/types'import { createHttpError } from '@/service/http-error'import LastRun from '../index'@@ -13,7 +14,7 @@ vi.mock('@remixicon/react', () => ({vi.mock('@/app/components/workflow/hooks-store', () => ({useHooksStore: (- selector: (state: { configsMap?: { flowType?: string; flowId?: string } }) => unknown,+ selector: (state: { configsMap?: { resourceKind?: string; flowId?: string } }) => unknown,) => mockUseHooksStore(selector),}))@@ -46,10 +47,10 @@ describe('LastRun', () => {beforeEach(() => {vi.clearAllMocks()mockUseHooksStore.mockImplementation(- (selector: (state: { configsMap?: { flowType?: string; flowId?: string } }) => unknown) =>+ (selector: (state: { configsMap?: { resourceKind?: string; flowId?: string } }) => unknown) =>selector({configsMap: {- flowType: 'appFlow',+ resourceKind: 'appFlow',flowId: 'flow-1',},}),@@ -75,13 +76,13 @@ describe('LastRun', () => {render(<LastRun- appId="app-1"nodeId="node-1"canSingleRunisRunAfterSingleRun={false}updateNodeRunningStatus={updateNodeRunningStatus}onSingleRunClicked={onSingleRunClicked}/>,+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)expect(screen.getByTestId('loading-icon')).toBeInTheDocument()@@ -91,7 +92,6 @@ describe('LastRun', () => {it('should show a running result panel while a single run is still executing', () => {render(<LastRun- appId="app-1"nodeId="node-1"canSingleRunisRunAfterSingleRun@@ -99,6 +99,7 @@ describe('LastRun', () => {onSingleRunClicked={onSingleRunClicked}runningStatus={NodeRunningStatus.Running}/>,+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)expect(screen.getByTestId('result-panel')).toHaveTextContent('running')@@ -119,13 +120,13 @@ describe('LastRun', () => {render(<LastRun- appId="app-1"nodeId="node-1"canSingleRunisRunAfterSingleRun={false}updateNodeRunningStatus={updateNodeRunningStatus}onSingleRunClicked={onSingleRunClicked}/>,+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)act(() => {@@ -148,7 +149,6 @@ describe('LastRun', () => {render(<LastRun- appId="app-1"nodeId="node-1"canSingleRunisRunAfterSingleRun@@ -157,6 +157,7 @@ describe('LastRun', () => {runningStatus={NodeRunningStatus.Succeeded}isPaused/>,+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Stopped)@@ -181,7 +182,6 @@ describe('LastRun', () => {const { rerender } = render(<LastRun- appId="app-1"nodeId="node-1"canSingleRunisRunAfterSingleRun@@ -189,13 +189,13 @@ describe('LastRun', () => {onSingleRunClicked={onSingleRunClicked}runningStatus={NodeRunningStatus.Stopped}/>,+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)expect(screen.getByTestId('result-panel')).toHaveTextContent(NodeRunningStatus.Stopped)rerender(<LastRun- appId="app-1"nodeId="node-1"canSingleRunisRunAfterSingleRun@@ -219,7 +219,6 @@ describe('LastRun', () => {render(<LastRun- appId="app-1"nodeId="node-1"canSingleRunisRunAfterSingleRun@@ -227,6 +226,7 @@ describe('LastRun', () => {onSingleRunClicked={onSingleRunClicked}runningStatus={NodeRunningStatus.Succeeded}/>,+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)act(() => {@@ -249,14 +249,15 @@ describe('LastRun', () => {})const props = {- appId: 'app-1',nodeId: 'node-1',canSingleRun: true,isRunAfterSingleRun: true,updateNodeRunningStatus,onSingleRunClicked,}- const { rerender } = render(<LastRun {...props} runningStatus={NodeRunningStatus.Running} />)+ const { rerender } = render(<LastRun {...props} runningStatus={NodeRunningStatus.Running} />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })rerender(<LastRun {...props} runningStatus={NodeRunningStatus.Succeeded} />)act(() => {diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/use-last-run.spec.ts b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/use-last-run.spec.tsindex 03e5445de37..11a41afa85e 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/use-last-run.spec.ts+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/__tests__/use-last-run.spec.ts@@ -1,7 +1,6 @@import { act } from '@testing-library/react'import { renderWorkflowHook } from '@/app/components/workflow/__tests__/workflow-test-env'import { BlockEnum } from '@/app/components/workflow/types'-import { FlowType } from '@/types/common'import useLastRun from '../use-last-run'const mockHandleSyncWorkflowDraft = vi.fn()@@ -54,7 +53,7 @@ vi.mock('@/app/components/workflow/nodes/_base/hooks/use-one-step-run', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidLastRun: () => vi.fn(),+ useInvalidateLastRun: () => vi.fn(),}))describe('useLastRun', () => {@@ -66,8 +65,8 @@ describe('useLastRun', () => {const { result } = renderWorkflowHook(() =>useLastRun({id: 'data-source-node',- flowId: 'flow-id',- flowType: FlowType.appFlow,+ resource: { kind: 'app', appId: 'flow-id', mode: 'workflow' },+data: {type: BlockEnum.DataSource,title: 'Data Source',diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/index.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/index.tsxindex 489c9ade710..c9280db598d 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/index.tsx+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/index.tsx@@ -4,18 +4,17 @@ import type { FC } from 'react'import type { ResultPanelProps } from '@/app/components/workflow/run/result-panel'import type { NodeTracing } from '@/types/workflow'import { RiLoader2Line } from '@remixicon/react'+import { useAtomValue } from 'jotai'import * as React from 'react'import { useCallback, useEffect, useState } from 'react'-import { useHooksStore } from '@/app/components/workflow/hooks-store'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import ResultPanel from '@/app/components/workflow/run/result-panel'import { NodeRunningStatus } from '@/app/components/workflow/types'import { isNotFoundError } from '@/service/http-error'import { useLastRun } from '@/service/use-workflow'-import { FlowType } from '@/types/common'import NoData from './no-data'type Props = Readonly<{- appId: stringnodeId: stringcanSingleRun: booleanisRunAfterSingleRun: boolean@@ -29,7 +28,6 @@ type Props = Readonly<{Partial<ResultPanelProps>const LastRun: FC<Props> = ({- appId: _appId,nodeId,canSingleRun,isRunAfterSingleRun,@@ -50,7 +48,7 @@ const LastRun: FC<Props> = ({NodeRunningStatus.NotStart,]- const configsMap = useHooksStore((s) => s.configsMap)+ const resource = useAtomValue(editorResourceAtom)const isOneStepRunSucceed = oneStepRunRunningStatus === NodeRunningStatus.Succeededconst isOneStepRunFailed = oneStepRunRunningStatus === NodeRunningStatus.Failed// hide page and return to page would lost the oneStepRunRunningStatus@@ -65,16 +63,7 @@ const LastRun: FC<Props> = ({isOneStepRunSucceed ||isOneStepRunFailed ||(pageHasHide && hidePageOneStepRunFinished)- const {- data: lastRunResult,- isFetching,- error,- } = useLastRun(- configsMap?.flowType || FlowType.appFlow,- configsMap?.flowId || '',- nodeId,- canRunLastRun,- )+ const { data: lastRunResult, isFetching, error } = useLastRun(resource, nodeId, canRunLastRun)const hasAuthoritativeLastRun = canRunLastRun && !!lastRunResultconst isRunning =!isPaused &&diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.tsindex 68cdff9c16e..72f5e76521f 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts@@ -28,7 +28,7 @@ import { BlockEnum } from '@/app/components/workflow/types'import { isSupportCustomRunForm } from '@/app/components/workflow/utils'import { toast } from '@/app/notifications'import { VALUE_SELECTOR_DELIMITER as DELIMITER } from '@/config'-import { useInvalidLastRun } from '@/service/use-workflow'+import { useInvalidateLastRun } from '@/service/use-workflow'import { useWorkflowRunValidation } from '../../../../../hooks/use-checklist'import useInspectVarsCrud from '../../../../../hooks/use-inspect-vars-crud'import { useNodesSyncDraft } from '../../../../../hooks/use-nodes-sync-draft'@@ -139,7 +139,7 @@ const useLastRun = <T>({ ...oneStepRunParams }: Params<T>) => {)const [isRunAfterSingleRun, setIsRunAfterSingleRun] = useState(false)- const { id, flowId, flowType, data } = oneStepRunParams+ const { id, resource, data } = oneStepRunParamsconst oneStepRunRes = useOneStepRun({...oneStepRunParams,iteratorInputKey: blockType === BlockEnum.Iteration ? `${id}.input_selector` : '',@@ -229,7 +229,7 @@ const useLastRun = <T>({ ...oneStepRunParams }: Params<T>) => {setInitShowLastRunTab(false)}, [initShowLastRunTab, setInitShowLastRunTab])- const invalidLastRun = useInvalidLastRun(flowType, flowId, id)+ const invalidLastRun = useInvalidateLastRun(resource, id)const handleRunWithParams = async (data: Record<string, any>) => {if (blockIfChecklistFailed()) returndiff --git a/web/app/components/workflow/nodes/_base/hooks/__tests__/snippet-input-field-vars.spec.ts b/web/app/components/workflow/nodes/_base/hooks/__tests__/snippet-input-field-vars.spec.tsindex 4d250883b8d..3f043202820 100644--- a/web/app/components/workflow/nodes/_base/hooks/__tests__/snippet-input-field-vars.spec.ts+++ b/web/app/components/workflow/nodes/_base/hooks/__tests__/snippet-input-field-vars.spec.ts@@ -15,17 +15,13 @@ const createNode = (id = 'node-1'): Node =>}) as Nodedescribe('appendSnippetInputFieldVars', () => {- beforeEach(() => {- globalThis.history.pushState({}, '', '/')- })-it('should treat missing snippet input fields as empty on snippet canvases', () => {- globalThis.history.pushState({}, '', '/snippets/snippet-1/orchestrate')const availableNodes = [createNode()]expect(appendSnippetInputFieldVars({availableNodes,+ isSnippetFlow: true,fields: undefined,title: 'Snippet',}),diff --git a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-available-var-list.spec.ts b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-available-var-list.spec.tsindex 547f84779a7..a2c56169e5e 100644--- a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-available-var-list.spec.ts+++ b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-available-var-list.spec.ts@@ -1,7 +1,7 @@+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type { Node, NodeOutPutVar, Var } from '@/app/components/workflow/types'-import { renderHook } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum, VarType } from '@/app/components/workflow/types'-import { FlowType } from '@/types/common'import useAvailableVarList from '../use-available-var-list'const mockGetTreeLeafNodes = vi.hoisted(() => vi.fn())@@ -9,7 +9,7 @@ const mockGetBeforeNodesInSameBranchIncludeParent = vi.hoisted(() => vi.fn())const mockGetNodeById = vi.hoisted(() => vi.fn())const mockGetNodeAvailableVars = vi.hoisted(() => vi.fn())const mockFlowType = vi.hoisted(() => ({- value: undefined as FlowType | undefined,+ value: undefined as EditorResource['kind'] | undefined,}))vi.mock('@/app/components/snippets/draft-store', () => ({@@ -22,7 +22,7 @@ vi.mock('../../../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => true,+useWorkflow: () => ({getTreeLeafNodes: mockGetTreeLeafNodes,getBeforeNodesInSameBranchIncludeParent: mockGetBeforeNodesInSameBranchIncludeParent,@@ -48,10 +48,12 @@ vi.mock('@/app/components/workflow/store', () => ({}))vi.mock('@/app/components/workflow/hooks-store/store', () => ({- useHooksStore: (selector: (state: { configsMap?: { flowType?: FlowType } }) => unknown) =>+ useHooksStore: (+ selector: (state: { configsMap?: { resourceKind?: EditorResource['kind'] } }) => unknown,+ ) =>selector({configsMap: {- flowType: mockFlowType.value,+ resourceKind: mockFlowType.value,},}),}))@@ -114,12 +116,12 @@ describe('useAvailableVarList', () => {})it('filters system variables on snippet canvases', () => {- globalThis.history.pushState({}, '', '/snippets/snippet-1/orchestrate')-- const { result } = renderHook(() =>- useAvailableVarList('node-1', {- filterVar: () => true,- }),+ const { result } = renderHook(+ () =>+ useAvailableVarList('node-1', {+ filterVar: () => true,+ }),+ { resource: { kind: 'snippet', snippetId: 'snippet-1' } },)expect(result.current.availableVars).toEqual([@@ -137,22 +139,24 @@ describe('useAvailableVarList', () => {})it('keeps system variables outside snippet canvases', () => {- const { result } = renderHook(() =>- useAvailableVarList('node-1', {- filterVar: () => true,- }),+ const { result } = renderHook(+ () =>+ useAvailableVarList('node-1', {+ filterVar: () => true,+ }),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)expect(result.current.availableVars).toEqual(outputVarsWithSystemVars)})it('filters system variables when the current flow is a snippet', () => {- mockFlowType.value = FlowType.snippet-- const { result } = renderHook(() =>- useAvailableVarList('node-1', {- filterVar: () => true,- }),+ const { result } = renderHook(+ () =>+ useAvailableVarList('node-1', {+ filterVar: () => true,+ }),+ { resource: { kind: 'snippet', snippetId: 'snippet-1' } },)expect(result.current.availableVars).toEqual([@@ -169,3 +173,10 @@ describe('useAvailableVarList', () => {])})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => true) }+})diff --git a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.ts b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.tsindex 4b30f53ab70..41f003f5e38 100644--- a/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.ts+++ b/web/app/components/workflow/nodes/_base/hooks/__tests__/use-one-step-run.spec.ts@@ -2,9 +2,7 @@ import { ORPCError } from '@orpc/client'import { act, renderHook } from '@testing-library/react'import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'import { toast } from '@/app/notifications'-// oxlint-disable-next-line no-restricted-imports -- Mock the request boundary while preserving the single-run error owner.-import { post } from '@/service/base'-import { FlowType } from '@/types/common'+import { consoleClient } from '@/service/console'import useOneStepRun from '../use-one-step-run'const mockWorkflowState = {@@ -46,7 +44,7 @@ vi.mock('../../../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => false,+useWorkflow: () => ({getBeforeNodesInSameBranch: () => [{@@ -103,7 +101,7 @@ vi.mock('@/service/use-tools', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidLastRun: () => vi.fn(),+ useInvalidateLastRun: () => vi.fn(),}))vi.mock('@/service/workflow', () => ({@@ -113,8 +111,17 @@ vi.mock('@/service/workflow', () => ({singleNodeRun: vi.fn(),}))+vi.mock('@/service/console', () => ({+ consoleClient: {+ apps: {+ byAppId: {+ workflows: { draft: { nodes: { byNodeId: { trigger: { run: { post: vi.fn() } } } } } },+ },+ },+ },+}))+vi.mock('@/service/base', () => ({- post: vi.fn(),ssePost: vi.fn(),}))@@ -188,8 +195,8 @@ const renderUseOneStepRun = (type: BlockEnum = BlockEnum.IfElse) =>renderHook(() =>useOneStepRun({id: 'if-else-node',- flowId: 'app-id',- flowType: FlowType.appFlow,+ resource: { kind: 'app', appId: 'app-id', mode: 'workflow' },+data: {type,title: 'IF/ELSE',@@ -244,6 +251,53 @@ describe('useOneStepRun single-run input vars', () => {])})+ it.each([BlockEnum.TriggerSchedule, BlockEnum.TriggerWebhook, BlockEnum.TriggerPlugin])(+ 'runs %s with the app identity and supports aborting polling requests',+ async (type) => {+ const run = vi.mocked(+ consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.trigger.run.post,+ )+ run.mockResolvedValueOnce({ id: 'execution-1', status: 'succeeded' })+ const { result } = renderUseOneStepRun(type)+ await act(async () => {+ await result.current.handleRun({})+ })+ expect(run.mock.calls[0]?.[0]).toEqual({+ params: { app_id: 'app-id', node_id: 'if-else-node' },+ })+ if (type !== BlockEnum.TriggerSchedule)+ expect(run.mock.calls[0]?.[1]?.signal).toBeInstanceOf(AbortSignal)+ expect(toast.error).not.toHaveBeenCalled()+ },+ )++ it.each([BlockEnum.TriggerWebhook, BlockEnum.TriggerPlugin])(+ 'aborts the pending %s request when listening stops',+ async (type) => {+ const run = vi.mocked(+ consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.trigger.run.post,+ )+ run.mockImplementationOnce(+ (_input, options) =>+ new Promise((_resolve, reject) => {+ options?.signal?.addEventListener(+ 'abort',+ () => reject(new DOMException('Aborted', 'AbortError')),+ { once: true },+ )+ }),+ )+ const { result } = renderUseOneStepRun(type)+ await act(async () => {+ const pendingRun = result.current.handleRun({})+ result.current.handleStop()+ expect(await pendingRun).toBe(false)+ })+ expect(run.mock.calls[0]?.[1]?.signal?.aborted).toBe(true)+ expect(toast.error).not.toHaveBeenCalled()+ },+ )+it('preserves the plugin request error and metadata when reporting a failed run', async () => {const error = new ORPCError('forbidden', {status: 403,@@ -251,7 +305,9 @@ describe('useOneStepRun single-run input vars', () => {data: { reason: 'PLUGIN_ACCESS_DENIED' },cause: { headers: new Headers({ 'X-Request-Id': 'plugin-run-1' }) },})- vi.mocked(post).mockRejectedValueOnce(error)+ vi.mocked(+ consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.trigger.run.post,+ ).mockRejectedValueOnce(error)const reportError = vi.spyOn(console, 'error').mockImplementation(() => {})const { result } = renderUseOneStepRun(BlockEnum.TriggerPlugin)@@ -264,3 +320,10 @@ describe('useOneStepRun single-run input vars', () => {expect(reportError.mock.calls[0]?.[0]).toBe(error)})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})diff --git a/web/app/components/workflow/nodes/_base/hooks/snippet-input-field-vars.ts b/web/app/components/workflow/nodes/_base/hooks/snippet-input-field-vars.tsindex c2163e050b8..4b2a82f653d 100644--- a/web/app/components/workflow/nodes/_base/hooks/snippet-input-field-vars.ts+++ b/web/app/components/workflow/nodes/_base/hooks/snippet-input-field-vars.ts@@ -7,16 +7,7 @@ import { inputVarTypeToVarType } from '../../data-source/utils'const SNIPPET_INPUT_FIELD_NODE_ID = 'start'-export const isSnippetCanvas = () => {- if (typeof globalThis.location === 'undefined') return false-- return /^\/snippets\/[^/]+\/orchestrate/.test(globalThis.location.pathname)-}--export const filterSnippetSystemVars = (- availableVars: NodeOutPutVar[],- isSnippetFlow = isSnippetCanvas(),-) => {+export const filterSnippetSystemVars = (availableVars: NodeOutPutVar[], isSnippetFlow: boolean) => {if (!isSnippetFlow) return availableVarsreturn availableVars@@ -93,16 +84,18 @@ const buildSnippetInputFieldVars = (export const appendSnippetInputFieldVars = ({availableNodes,+ isSnippetFlow,fields,title,}: {availableNodes: Node[]+ isSnippetFlow: booleanfields?: SnippetInputField[]title: string}) => {const inputFields = fields ?? []const shouldAppendSnippetInputFields =- isSnippetCanvas() &&+ isSnippetFlow &&inputFields.length > 0 &&!availableNodes.some((node) => node.data.type === BlockEnum.Start)const snippetInputFieldNode = shouldAppendSnippetInputFieldsdiff --git a/web/app/components/workflow/nodes/_base/hooks/use-available-var-list.ts b/web/app/components/workflow/nodes/_base/hooks/use-available-var-list.tsindex 44eaf4470cb..75c8ceeba0a 100644--- a/web/app/components/workflow/nodes/_base/hooks/use-available-var-list.ts+++ b/web/app/components/workflow/nodes/_base/hooks/use-available-var-list.ts@@ -1,18 +1,17 @@import type { Node, NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'+import { useAtomValue } from 'jotai'import { useTranslation } from 'react-i18next'import { useSnippetDraftStore } from '@/app/components/snippets/draft-store'-import { useHooksStore } from '@/app/components/workflow/hooks-store/store'+import {+ editorResourceKindAtom,+ isChatflowAtom,+} from '@/app/components/workflow/editor-resource/state'import { useStore as useWorkflowStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'-import { FlowType } from '@/types/common'-import { useIsChatMode, useWorkflow } from '../../../hooks/use-workflow'+import { useWorkflow } from '../../../hooks/use-workflow'import { useWorkflowVariables } from '../../../hooks/use-workflow-variables'import { inputVarTypeToVarType } from '../../data-source/utils'-import {- appendSnippetInputFieldVars,- filterSnippetSystemVars,- isSnippetCanvas,-} from './snippet-input-field-vars'+import { appendSnippetInputFieldVars, filterSnippetSystemVars } from './snippet-input-field-vars'import useNodeInfo from './use-node-info'type Params = {@@ -35,13 +34,13 @@ const useAvailableVarList = (const snippetInputFields = useSnippetDraftStore((s) => s.inputFields)const { getTreeLeafNodes, getNodeById, getBeforeNodesInSameBranchIncludeParent } = useWorkflow()const { getNodeAvailableVars } = useWorkflowVariables()- const isChatMode = useIsChatMode()- const isSnippetFlow =- useHooksStore((s) => s.configsMap?.flowType) === FlowType.snippet || isSnippetCanvas()+ const isChatflow = useAtomValue(isChatflowAtom)+ const isSnippetFlow = useAtomValue(editorResourceKindAtom) === 'snippet'const availableNodes =passedInAvailableNodes ||(onlyLeafNodeVar ? getTreeLeafNodes(nodeId) : getBeforeNodesInSameBranchIncludeParent(nodeId))const snippetInputFieldAvailability = appendSnippetInputFieldVars({+ isSnippetFlow,availableNodes,fields: snippetInputFields,title: t(($) => $.panelTitle, { ns: 'snippet' }),@@ -88,7 +87,7 @@ const useAvailableVarList = (...getNodeAvailableVars({parentNode: iterationNode,beforeNodes: availableNodes,- isChatMode,+ isChatflow,filterVar,hideEnv,hideChatVar,diff --git a/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts b/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.tsindex 77443dc0542..58fe56f4123 100644--- a/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts+++ b/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts@@ -1,3 +1,5 @@+import type { DraftWorkflowNodeRunPayload } from '@dify/contracts/api/console/apps/types.gen'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type {CommonNodeType,InputVar,@@ -6,7 +8,6 @@ import type {Var,Variable,} from '@/app/components/workflow/types'-import type { FlowType } from '@/types/common'import type { NodeRunResult, NodeTracing } from '@/types/workflow'import { unionBy } from 'es-toolkit/compat'import { noop } from 'es-toolkit/function'@@ -16,6 +17,7 @@ import { useTranslation } from 'react-i18next'import { useStoreApi } from 'reactflow'import { trackEvent } from '@/app/components/base/amplitude'import { getInputVars as doGetInputVars } from '@/app/components/base/prompt-editor/constants'+import { getEditorResourceId, isChatflow } from '@/app/components/workflow/editor-resource/resource'import {getNodeInfoById,isConversationVar,@@ -49,25 +51,37 @@ import {import { EVENT_WORKFLOW_STOP } from '@/app/components/workflow/variable-inspect/types'import { toast } from '@/app/notifications'import { useEventEmitterContextContext } from '@/context/event-emitter'-import { post, ssePost } from '@/service/base'+import { ssePost } from '@/service/base'+import { consoleClient } from '@/service/console'import {useAllBuiltInTools,useAllCustomTools,useAllMCPTools,useAllWorkflowTools,} from '@/service/use-tools'-import { useInvalidLastRun } from '@/service/use-workflow'-import {- fetchNodeInspectVars,- getIterationSingleNodeRunUrl,- getLoopSingleNodeRunUrl,- singleNodeRun,-} from '@/service/workflow'+import { useInvalidateLastRun } from '@/service/use-workflow'+import { fetchNodeInspectVars, singleNodeRun } from '@/service/workflow'import useInspectVarsCrud from '../../../hooks/use-inspect-vars-crud'import { useNodeDataUpdate } from '../../../hooks/use-node-data-update'-import { useIsChatMode, useWorkflow } from '../../../hooks/use-workflow'+import { useWorkflow } from '../../../hooks/use-workflow'import useMatchSchemaType from '../components/variable/use-match-schema-type'+// Iteration and loop runs use the SSE event callbacks that the JSON client does not expose.+function getContainerNodeRunUrl(+ resource: EditorResource,+ type: 'iteration' | 'loop',+ nodeId: string,+) {+ switch (resource.kind) {+ case 'app':+ return `apps/${resource.appId}/${resource.mode === 'advanced-chat' ? 'advanced-chat/' : ''}workflows/draft/${type}/nodes/${nodeId}/run`+ case 'knowledge-pipeline':+ return `rag/pipelines/${resource.pipelineId}/workflows/draft/${type}/nodes/${nodeId}/run`+ case 'snippet':+ return `snippets/${resource.snippetId}/workflows/draft/${type}/nodes/${nodeId}/run`+ }+}+const { checkValid: checkLLMValid } = LLMDefaultconst { checkValid: checkKnowledgeRetrievalValid } = KnowledgeRetrievalDefaultconst { checkValid: checkIfElseValid } = IfElseDefault@@ -105,8 +119,7 @@ const checkValidFns: Partial<Record<BlockEnum, Function>> = {export type Params<T> = {id: string- flowId: string- flowType: FlowType+ resource: EditorResourcedata: CommonNodeType<T>defaultRunInputData: Record<string, any>moreDataForCheckValid?: any@@ -147,8 +160,7 @@ const varTypeToInputVarType = (const useOneStepRun = <T>({id,- flowId,- flowType,+ resource,data,defaultRunInputData,moreDataForCheckValid,@@ -161,7 +173,8 @@ const useOneStepRun = <T>({const { getBeforeNodesInSameBranch, getBeforeNodesInSameBranchIncludeParent } =useWorkflow() as anyconst conversationVariables = useStore((s) => s.conversationVariables)- const isChatMode = useIsChatMode()+ const isChatflowMode = isChatflow(resource)+ const flowId = getEditorResourceId(resource)const isIteration = data.type === BlockEnum.Iterationconst isLoop = data.type === BlockEnum.Loopconst isStartNode = data.type === BlockEnum.Start@@ -189,7 +202,7 @@ const useOneStepRun = <T>({const allOutputVars = toNodeOutputVars(availableNodes,- isChatMode,+ isChatflowMode,undefined,undefined,conversationVariables,@@ -279,7 +292,7 @@ const useOneStepRun = <T>({},[workflowStore, store],)- const invalidLastRun = useInvalidLastRun(flowType, flowId!, id)+ const invalidLastRun = useInvalidateLastRun(resource, id)const [runResult, doSetRunResult] = useState<NodeRunResult | null>(null)const { appendNodeInspectVars, invalidateSysVarValues, invalidateConversationVarValues } =useInspectVarsCrud()@@ -319,7 +332,7 @@ const useOneStepRun = <T>({}// run fail may also update the inspect vars when the node set the error default output.- const vars = await fetchNodeInspectVars(flowType, flowId!, id)+ const vars = await fetchNodeInspectVars(resource, id)const { getNodes } = store.getState()const nodes = getNodes()appendNodeInspectVars(id, vars, nodes)@@ -333,8 +346,7 @@ const useOneStepRun = <T>({[isRunAfterSingleRun,runningStatus,- flowType,- flowId,+ resource,id,store,appendNodeInspectVars,@@ -428,12 +440,13 @@ const useOneStepRun = <T>({])const runScheduleSingleRun = useCallback(async (): Promise<NodeRunResult | null> => {- const urlPath = `/apps/${flowId}/workflows/draft/nodes/${id}/trigger/run`+ if (resource.kind !== 'app') return nulltry {- const response: any = await post(urlPath, {- body: JSON.stringify({}),- })+ const response: any =+ await consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.trigger.run.post({+ params: { app_id: resource.appId, node_id: id },+ })if (!response) {const message = t(($) => $['common.scheduleTriggerRunFailed'], { ns: 'workflow' })@@ -471,10 +484,10 @@ const useOneStepRun = <T>({toast.error(t(($) => $['common.scheduleTriggerRunFailed'], { ns: 'workflow' }))throw error}- }, [flowId, id, handleNodeDataUpdate, data, t])+ }, [resource, id, handleNodeDataUpdate, data, t])const runWebhookSingleRun = useCallback(async (): Promise<any | null> => {- const urlPath = `/apps/${flowId}/workflows/draft/nodes/${id}/trigger/run`+ if (resource.kind !== 'app') return nullwebhookSingleRunActiveRef.current = trueconst token = ++webhookSingleRunTokenRef.current@@ -484,10 +497,11 @@ const useOneStepRun = <T>({webhookSingleRunAbortRef.current = controllertry {- const response: any = await post(urlPath, {- body: JSON.stringify({}),- signal: controller.signal,- })+ const response: any =+ await consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.trigger.run.post(+ { params: { app_id: resource.appId, node_id: id } },+ { signal: controller.signal },+ )if (!webhookSingleRunActiveRef.current || token !== webhookSingleRunTokenRef.current)return null@@ -562,10 +576,10 @@ const useOneStepRun = <T>({}return null- }, [flowId, id, data, handleNodeDataUpdate, cancelWebhookSingleRun, t])+ }, [resource, id, data, handleNodeDataUpdate, cancelWebhookSingleRun, t])const runPluginSingleRun = useCallback(async (): Promise<any | null> => {- const urlPath = `/apps/${flowId}/workflows/draft/nodes/${id}/trigger/run`+ if (resource.kind !== 'app') return nullpluginSingleRunActiveRef.current = trueconst token = ++pluginSingleRunTokenRef.current@@ -575,17 +589,16 @@ const useOneStepRun = <T>({pluginSingleRunAbortRef.current = controllerlet requestError: unknown- const response: any = await post(urlPath, {- body: JSON.stringify({}),- signal: controller.signal,- })- .catch((error: unknown) => {- requestError = error- return null- })- .finally(() => {- pluginSingleRunAbortRef.current = null- })+ const response: any =+ await consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.trigger.run+ .post({ params: { app_id: resource.appId, node_id: id } }, { signal: controller.signal })+ .catch((error: unknown) => {+ requestError = error+ return null+ })+ .finally(() => {+ pluginSingleRunAbortRef.current = null+ })if (!pluginSingleRunActiveRef.current || token !== pluginSingleRunTokenRef.current)return null@@ -650,7 +663,7 @@ const useOneStepRun = <T>({}return null- }, [flowId, id, data, handleNodeDataUpdate, cancelPluginSingleRun])+ }, [resource, id, data, handleNodeDataUpdate, cancelPluginSingleRun])const checkValidWrap = () => {if (!checkValid) return { isValid: true, errorMessage: '' }@@ -766,25 +779,23 @@ const useOneStepRun = <T>({}} else {const isStartNode = data.type === BlockEnum.Start- const postData: Record<string, any> = {}+ const postData: DraftWorkflowNodeRunPayload = { inputs: submitData }if (isStartNode) {const { '#sys.query#': query, '#sys.files#': files, ...inputs } = submitData- if (isChatMode) postData.conversation_id = ''-postData.inputs = inputspostData.query = querypostData.files = files || []} else {postData.inputs = submitData}- res = (await singleNodeRun(flowType, flowId!, id, postData)) as any+ res = (await singleNodeRun(resource, id, postData)) as any}} else if (isIteration) {setIterationRunResult([])let _iterationResult: NodeTracing[] = []let _runResult: any = nullssePost(- getIterationSingleNodeRunUrl(flowType, isChatMode, flowId!, id),+ getContainerNodeRunUrl(resource, 'iteration', id),{ body: { inputs: submitData } },{onWorkflowStarted: noop,@@ -886,7 +897,7 @@ const useOneStepRun = <T>({let _loopResult: NodeTracing[] = []let _runResult: any = nullssePost(- getLoopSingleNodeRunUrl(flowType, isChatMode, flowId!, id),+ getContainerNodeRunUrl(resource, 'loop', id),{ body: { inputs: submitData } },{onWorkflowStarted: noop,diff --git a/web/app/components/workflow/nodes/_base/node.tsx b/web/app/components/workflow/nodes/_base/node.tsxindex 64d9c214642..b0e037f8368 100644--- a/web/app/components/workflow/nodes/_base/node.tsx+++ b/web/app/components/workflow/nodes/_base/node.tsx@@ -2,12 +2,14 @@ import type { FC, ReactElement } from 'react'import type { NodeProps } from '@/app/components/workflow/types'import { cn } from '@langgenius/dify-ui/cn'import { useSuspenseQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { cloneElement, memo, useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'import { UserAvatarList } from '@/app/components/base/user-avatar-list'import BlockIcon from '@/app/components/workflow/block-icon'import { ToolType } from '@/app/components/workflow/block-selector/types'import { useCollaboration } from '@/app/components/workflow/collaboration/hooks/use-collaboration'+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'import { useHooksStore } from '@/app/components/workflow/hooks-store'import { hasAgentV2OutputRoutes } from '@/app/components/workflow/nodes/agent-v2/types'import { useNodeIterationInteractions } from '@/app/components/workflow/nodes/iteration/use-interactions'@@ -60,9 +62,9 @@ const BaseNode: FC<BaseNodeProps> = ({ id, data, children }) => {...userProfileQueryOptions(),select: (data) => data.profile,})- const appId = useStore((s) => s.appId)+ const appId = useAtomValue(editorAppIdAtom)const canEdit = useHooksStore((s) => s.accessControl.canEdit)- const { nodePanelPresence } = useCollaboration(appId as string, canEdit)+ const { nodePanelPresence } = useCollaboration(appId, canEdit)const controlMode = useStore((s) => s.controlMode)const isContextMenuTarget = useStore((s) => s.contextMenuTarget?.type === 'node' && s.contextMenuTarget.nodeId === id,diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx b/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsxindex 1013152d62e..f788fa77f5f 100644--- a/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx@@ -1,3 +1,4 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import { QueryClient } from '@tanstack/react-query'import { act, waitFor } from '@testing-library/react'import { useSetAtom } from 'jotai'@@ -6,8 +7,6 @@ import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/storeimport { AgentScope } from '@/features/agent-v2/analytics'import { createConsoleQueryClient, seedAppDetail } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import { renderWorkflowHook } from '../../../__tests__/workflow-test-env'import { useWorkflowInlineAgentConfigureSync } from '../agent-soul-config'import { useCreateInlineAgentBinding, useWorkflowInlineAgentDetail } from '../hooks'@@ -168,6 +167,9 @@ vi.mock('@/service/console', async (importOriginal) => {get: actual.consoleQuery.apps.byAppId.get,workflows: {draft: {+ systemVariables: actual.consoleQuery.apps.byAppId.workflows.draft.systemVariables,+ conversationVariables:+ actual.consoleQuery.apps.byAppId.workflows.draft.conversationVariables,nodes: {byNodeId: {agentComposer: {@@ -222,7 +224,7 @@ vi.mock('@/service/console', async (importOriginal) => {}})-const createInlineAgentBindingQueryClient = (appMode: AppModeEnum = AppModeEnum.WORKFLOW) => {+const createInlineAgentBindingQueryClient = (appMode: AppMode = 'workflow') => {const queryClient = createConsoleQueryClient()seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode: appMode }))return queryClient@@ -249,12 +251,9 @@ describe('useWorkflowInlineAgentDetail', () => {() => useWorkflowInlineAgentDetail('node-1', 'snippet-agent'),{queryClient,+ resource: { kind: 'snippet' as const, snippetId: 'snippet-1' },hooksStoreProps: {- configsMap: {- flowId: 'snippet-1',- flowType: FlowType.snippet,- fileSettings: {} as never,- },+ fileSettings: {} as never,},},)@@ -288,12 +287,9 @@ describe('useWorkflowInlineAgentDetail', () => {}),{queryClient,+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},},)@@ -321,12 +317,9 @@ describe('useWorkflowInlineAgentDetail', () => {}),{queryClient,+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},},)@@ -361,12 +354,9 @@ describe('useCreateInlineAgentBinding', () => {const queryClient = createInlineAgentBindingQueryClient()const { result } = renderWorkflowHook(() => useCreateInlineAgentBinding(), {queryClient,+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},})@@ -432,15 +422,12 @@ describe('useCreateInlineAgentBinding', () => {})it('tracks inline agent creation with the chatflow scope', async () => {- const queryClient = createInlineAgentBindingQueryClient(AppModeEnum.ADVANCED_CHAT)+ const queryClient = createInlineAgentBindingQueryClient('advanced-chat')const { result } = renderWorkflowHook(() => useCreateInlineAgentBinding(), {queryClient,+ resource: { kind: 'app' as const, appId: 'chatflow-1', mode: 'advanced-chat' as const },hooksStoreProps: {- configsMap: {- flowId: 'chatflow-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},})@@ -462,12 +449,9 @@ describe('useCreateInlineAgentBinding', () => {const queryClient = createInlineAgentBindingQueryClient()const { result } = renderWorkflowHook(() => useCreateInlineAgentBinding(), {queryClient,+ resource: { kind: 'snippet' as const, snippetId: 'snippet-1' },hooksStoreProps: {- configsMap: {- flowId: 'snippet-1',- flowType: FlowType.snippet,- fileSettings: {} as never,- },+ fileSettings: {} as never,},})@@ -515,12 +499,9 @@ describe('useCreateInlineAgentBinding', () => {const queryClient = createInlineAgentBindingQueryClient()const { result } = renderWorkflowHook(() => useCreateInlineAgentBinding(), {queryClient,+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},})@@ -575,12 +556,9 @@ describe('useCreateInlineAgentBinding', () => {const queryClient = createInlineAgentBindingQueryClient()const { result, unmount } = renderWorkflowHook(() => useCreateInlineAgentBinding(), {queryClient,+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},})@@ -651,12 +629,9 @@ describe('useWorkflowInlineAgentConfigureSync', () => {}),{queryClient,+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},},)@@ -728,12 +703,9 @@ describe('useWorkflowInlineAgentConfigureSync', () => {}),{queryClient,+ resource: { kind: 'snippet' as const, snippetId: 'snippet-1' },hooksStoreProps: {- configsMap: {- flowId: 'snippet-1',- flowType: FlowType.snippet,- fileSettings: {} as never,- },+ fileSettings: {} as never,},},)@@ -802,12 +774,9 @@ describe('useWorkflowInlineAgentConfigureSync', () => {}),{queryClient,+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},},)@@ -866,12 +835,9 @@ describe('useWorkflowInlineAgentConfigureSync', () => {}),{queryClient,+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},},)@@ -910,12 +876,9 @@ describe('useWorkflowInlineAgentConfigureSync', () => {}),{queryClient,+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },hooksStoreProps: {- configsMap: {- flowId: 'app-1',- flowType: FlowType.appFlow,- fileSettings: {} as never,- },+ fileSettings: {} as never,},},)diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsxindex fcf2e7e0776..f476261d0b3 100644--- a/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx@@ -2,12 +2,12 @@ import type { AgentInviteOptionsResponse } from '@dify/contracts/api/console/ageimport type { ReactNode } from 'react'import type { AgentV2NodeType } from '../types'import type { PromptEditorProps } from '@/app/components/base/prompt-editor'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type { NodePanelProps } from '@/app/components/workflow/types'import { act, fireEvent, screen, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum } from '@/app/components/workflow/types'-import { renderWithConsoleQuery as render } from '@/test/console/query-data'-import { FlowType } from '@/types/common'import { AgentV2Panel } from '../panel'vi.mock('../components/agent-output-routes', () => ({ AgentOutputRoutes: () => null }))@@ -57,7 +57,7 @@ const {},mockConfigsMap: {flowId: 'app-1',- flowType: 'appFlow' as FlowType,+ resourceKind: 'appFlow' as EditorResource['kind'],},mockCreateInlineAgentBinding: vi.fn(),mockSetInputs: vi.fn(),@@ -341,7 +341,7 @@ describe('agent/panel', () => {mockStoreState.openInlineAgentPanelNodeId = undefinedmockCopyFromRosterState.isPending = falsemockConfigsMap.flowId = 'app-1'- mockConfigsMap.flowType = FlowType.appFlow+ mockConfigsMap.resourceKind = 'app'mockCopyFromRosterMutate.mockImplementation((_variables,@@ -524,9 +524,11 @@ describe('agent/panel', () => {it('copies a roster agent through the snippet composer API', () => {mockConfigsMap.flowId = 'snippet-1'- mockConfigsMap.flowType = FlowType.snippet+ mockConfigsMap.resourceKind = 'snippet'mockStoreState.appId = undefined as never- render(<AgentV2Panel id="agent-node" data={createData()} panelProps={panelProps} />)+ render(<AgentV2Panel id="agent-node" data={createData()} panelProps={panelProps} />, {+ resource: { kind: 'snippet', snippetId: 'snippet-1' },+ })fireEvent.click(screen.getByRole('button', { name: /^workflowAgent\.nodes\.agent\.roster\.openPanel/ }),diff --git a/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.tsindex b1a07b4197c..e4c7558969d 100644--- a/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts+++ b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts@@ -6,9 +6,9 @@ import type { DefaultModelResponse } from '@/app/components/header/account-settiimport { useMutation, useQueryClient } from '@tanstack/react-query'import { debounce } from 'es-toolkit/compat'import isEqual from 'fast-deep-equal'-import { useStore as useJotaiStore, useSetAtom } from 'jotai'+import { useAtomValue, useStore as useJotaiStore, useSetAtom } from 'jotai'import { useCallback, useEffect, useMemo, useRef } from 'react'-import { useHooksStore } from '@/app/components/workflow/hooks-store'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import {agentSoulConfigToFormState,formStateToAgentSoulConfig,@@ -19,7 +19,6 @@ import {isAgentComposerDirtyAtom,} from '@/features/agent-v2/agent-composer/store'import { consoleQuery } from '@/service/console'-import { FlowType } from '@/types/common'import { useSerialAsyncCallback } from '../../hooks/use-serial-async-callback'const DRAFT_AUTOSAVE_WAIT = 5000@@ -74,7 +73,7 @@ export function useWorkflowInlineAgentConfigureSync({enabled: boolean}) {const queryClient = useQueryClient()- const configsMap = useHooksStore((state) => state.configsMap)+ const resource = useAtomValue(editorResourceAtom)const store = useJotaiStore()const setSavedDraft = useSetAtom(agentComposerSavedDraftAtom)const baseConfigRef = useRef(baseConfig)@@ -108,11 +107,7 @@ export function useWorkflowInlineAgentConfigureSync({const saveComposer = useSerialAsyncCallback(async (configSnapshot: AgentSoulConfig): Promise<WorkflowAgentComposerResponse | undefined> => {- if (- !configsMap?.flowId ||- (configsMap.flowType !== FlowType.appFlow && configsMap.flowType !== FlowType.snippet)- )- return+ if (resource.kind !== 'app' && resource.kind !== 'snippet') returnconst savedDraftKey = JSON.stringify(configSnapshot)const body = {@@ -121,29 +116,29 @@ export function useWorkflowInlineAgentConfigureSync({agent_soul: configSnapshot,}const composerState =- configsMap.flowType === FlowType.snippet+ resource.kind === 'snippet'? await saveSnippetComposer({params: {- snippet_id: configsMap.flowId,+ snippet_id: resource.snippetId,node_id: nodeId,},body,}): await saveAppComposer({params: {- app_id: configsMap.flowId,+ app_id: resource.appId,node_id: nodeId,},body,})- if (configsMap.flowType === FlowType.snippet) {+ if (resource.kind === 'snippet') {queryClient.setQueryData(consoleQuery.snippets.bySnippetId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({input: {params: {- snippet_id: configsMap.flowId,+ snippet_id: resource.snippetId,node_id: nodeId,},},@@ -156,7 +151,7 @@ export function useWorkflowInlineAgentConfigureSync({consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({input: {params: {- app_id: configsMap.flowId,+ app_id: resource.appId,node_id: nodeId,},},diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsxindex 34965ca8289..453732e9627 100644--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx@@ -6,16 +6,11 @@ import type { ReactNode, Ref } from 'react'import type { AgentBuildDraftChangeSummary } from '@/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-changes-context'import { act, fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderEditor as renderWithConsoleQuery } from '@/app/components/workflow/editor-resource/__tests__/render'import { AgentScope } from '@/features/agent-v2/analytics'import { createHttpError } from '@/service/http-error'-import {- createConsoleQueryClient,- renderWithConsoleQuery,- seedAppDetail,-} from '@/test/console/query-data'+import { createConsoleQueryClient, seedAppDetail } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import { WorkflowInlineAgentConfigureWorkspace } from '../agent-orchestrate-panel-content'const mocks = vi.hoisted(() => ({@@ -496,7 +491,7 @@ function createInlineComposerState({const render: typeof renderWithConsoleQuery = (ui, options = {}) => {const queryClient = createConsoleQueryClient()- seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode: AppModeEnum.WORKFLOW }))+ seedAppDetail(queryClient, createAppDetailFixture({ id: 'app-1', mode: 'workflow' as const }))return renderWithConsoleQuery(ui, { queryClient, ...options })}@@ -570,8 +565,7 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {return render(<WorkflowInlineAgentConfigureWorkspaceagentId="agent-1"- flowId="app-1"- flowType={FlowType.appFlow}+ resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}inlineComposerState={props.inlineComposerState ?? createInlineComposerState()}nodeId="node-1"onSaveInlineToRoster={props.onSaveInlineToRoster}@@ -589,8 +583,7 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {render(<WorkflowInlineAgentConfigureWorkspaceagentId="agent-1"- flowId="app-1"- flowType={FlowType.appFlow}+ resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}nodeId="node-1"open/>,@@ -605,8 +598,7 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {render(<WorkflowInlineAgentConfigureWorkspaceagentId="agent-1"- flowId="app-1"- flowType={FlowType.appFlow}+ resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}inlineComposerState={createInlineComposerState()}nodeId="node-1"open={false}@@ -1500,8 +1492,7 @@ describe('WorkflowInlineAgentConfigureWorkspace', () => {rerender(<WorkflowInlineAgentConfigureWorkspaceagentId="agent-1"- flowId="app-1"- flowType={FlowType.appFlow}+ resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}inlineComposerState={createInlineComposerState({ snapshotId: 'snapshot-2' })}nodeId="node-1"opendiff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/save-inline-agent-to-roster-dialog.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/save-inline-agent-to-roster-dialog.spec.tsxindex fb4356bcc1f..70a57db0a3d 100644--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/save-inline-agent-to-roster-dialog.spec.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/save-inline-agent-to-roster-dialog.spec.tsx@@ -1,7 +1,6 @@import type { AgentComposerAgentResponse } from '@dify/contracts/api/console/apps/types.gen'import { render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { FlowType } from '@/types/common'import { SaveInlineAgentToRosterDialog } from '../save-inline-agent-to-roster-dialog'const mutationMock = vi.hoisted(() => ({@@ -88,8 +87,7 @@ const renderDialog = (agent: AgentComposerAgentResponse = inlineAgent) => {render(<SaveInlineAgentToRosterDialog- flowId="app-1"- flowType={FlowType.appFlow}+ resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}initialAgent={agent}nodeId="node-1"open@@ -159,8 +157,7 @@ describe('SaveInlineAgentToRosterDialog', () => {const user = userEvent.setup()render(<SaveInlineAgentToRosterDialog- flowId="snippet-1"- flowType={FlowType.snippet}+ resource={{ kind: 'snippet', snippetId: 'snippet-1' }}initialAgent={inlineAgent}nodeId="node-1"open@@ -295,8 +292,7 @@ describe('SaveInlineAgentToRosterDialog', () => {}const { rerender } = render(<SaveInlineAgentToRosterDialog- flowId="app-1"- flowType={FlowType.appFlow}+ resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}initialAgent={inlineAgent}nodeId="node-1"open@@ -307,8 +303,7 @@ describe('SaveInlineAgentToRosterDialog', () => {rerender(<SaveInlineAgentToRosterDialog- flowId="app-1"- flowType={FlowType.appFlow}+ resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}initialAgent={updatedInlineAgent}nodeId="node-1"open@@ -334,8 +329,7 @@ describe('SaveInlineAgentToRosterDialog', () => {rerender(<SaveInlineAgentToRosterDialog- flowId="app-1"- flowType={FlowType.appFlow}+ resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}initialAgent={updatedInlineAgent}nodeId="node-1"open={false}@@ -349,8 +343,7 @@ describe('SaveInlineAgentToRosterDialog', () => {rerender(<SaveInlineAgentToRosterDialog- flowId="app-1"- flowType={FlowType.appFlow}+ resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}initialAgent={updatedInlineAgent}nodeId="node-1"opendiff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsxindex 0c27bc32a29..1ac4565c976 100644--- a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx@@ -9,6 +9,7 @@ import type {AgentComposerBindingResponse,WorkflowAgentComposerResponse,} from '@dify/contracts/api/console/apps/types.gen'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type { AgentPreviewChatController } from '@/features/agent-v2/agent-detail/configure/components/preview/chat-conversation'import {DropdownMenu,@@ -70,7 +71,6 @@ import {import { useCanCreateAgents } from '@/features/agent-v2/permissions'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { consoleQuery } from '@/service/console'-import { FlowType } from '@/types/common'import { useWorkflowInlineAgentConfigureSync } from '../agent-soul-config'import { InlineAgentLoading } from './inline-agent-loading'@@ -82,8 +82,7 @@ type WorkflowRosterAgentOrchestratePanelContentProps = {type WorkflowInlineAgentConfigureWorkspaceProps = {agentId?: string- flowId?: string- flowType?: FlowType+ resource?: Extract<EditorResource, { kind: 'app' | 'snippet' }>inlineComposerState?: WorkflowAgentComposerResponsenodeId: stringonClose?: () => void@@ -271,8 +270,7 @@ function WorkflowInlineAgentConfigureWorkspaceContent({agentId,agentSoulConfig,buildDraft,- flowId,- flowType,+ resource,inlineComposerState,nodeId,onClose,@@ -297,7 +295,7 @@ function WorkflowInlineAgentConfigureWorkspaceContent({null,)const rightPanelChatControllerRef = useRef<AgentPreviewChatController>(null)- const appId = flowType === FlowType.appFlow ? flowId : undefined+ const appId = resource?.kind === 'app' ? resource.appId : undefinedconst conversationIds = useAtomValue(agentConfigureConversationIdsAtom)const [rightPanelMode, setRightPanelMode] = useAtom(agentConfigureRightPanelModeAtom)const previewEnabled = systemFeatures?.deployment_edition !== 'COMMUNITY'@@ -352,15 +350,15 @@ function WorkflowInlineAgentConfigureWorkspaceContent({}},)- if (!flowId) return+ if (!resource) return- if (flowType === FlowType.snippet) {+ if (resource.kind === 'snippet') {queryClient.setQueryData<WorkflowAgentComposerResponse | undefined>(consoleQuery.snippets.bySnippetId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({input: {params: {- snippet_id: flowId,+ snippet_id: resource.snippetId,node_id: nodeId,},},@@ -379,12 +377,12 @@ function WorkflowInlineAgentConfigureWorkspaceContent({return}- if (flowType === FlowType.appFlow) {+ if (resource.kind === 'app') {queryClient.setQueryData<WorkflowAgentComposerResponse | undefined>(consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({input: {params: {- app_id: flowId,+ app_id: resource.appId,node_id: nodeId,},},diff --git a/web/app/components/workflow/nodes/agent-v2/components/save-inline-agent-to-roster-dialog.tsx b/web/app/components/workflow/nodes/agent-v2/components/save-inline-agent-to-roster-dialog.tsxindex 65f68ad7d00..0d0aa7ff2a8 100644--- a/web/app/components/workflow/nodes/agent-v2/components/save-inline-agent-to-roster-dialog.tsx+++ b/web/app/components/workflow/nodes/agent-v2/components/save-inline-agent-to-roster-dialog.tsx@@ -1,9 +1,11 @@'use client'+import type {AgentComposerAgentResponse,WorkflowAgentComposerResponse,} from '@dify/contracts/api/console/apps/types.gen'import type { Ref } from 'react'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type {AgentFormValues,AgentIconSelection,@@ -24,11 +26,9 @@ import { useTranslation } from 'react-i18next'import { createAgentIconSelection } from '@/features/agent-v2/roster/components/agent-form'import { AgentFormFields } from '@/features/agent-v2/roster/components/agent-form-fields'import { consoleQuery } from '@/service/console'-import { FlowType } from '@/types/common'type SaveInlineAgentToRosterDialogProps = {- flowId: string- flowType: typeof FlowType.appFlow | typeof FlowType.snippet+ resource: Extract<EditorResource, { kind: 'app' | 'snippet' }>initialAgent: AgentComposerAgentResponsenodeId: stringopen: boolean@@ -98,8 +98,7 @@ function SaveInlineAgentToRosterFormSession({}export function SaveInlineAgentToRosterDialog({- flowId,- flowType,+ resource,initialAgent,nodeId,open,@@ -144,11 +143,11 @@ export function SaveInlineAgentToRosterDialog({},}- if (flowType === FlowType.snippet) {+ if (resource.kind === 'snippet') {snippetSaveToRosterMutation.mutate({params: {- snippet_id: flowId,+ snippet_id: resource.snippetId,node_id: nodeId,},body,@@ -158,11 +157,11 @@ export function SaveInlineAgentToRosterDialog({return}- if (flowType === FlowType.appFlow) {+ if (resource.kind === 'app') {appSaveToRosterMutation.mutate({params: {- app_id: flowId,+ app_id: resource.appId,node_id: nodeId,},body,diff --git a/web/app/components/workflow/nodes/agent-v2/hooks.ts b/web/app/components/workflow/nodes/agent-v2/hooks.tsindex 5a9d5139a4e..c4c55a93827 100644--- a/web/app/components/workflow/nodes/agent-v2/hooks.ts+++ b/web/app/components/workflow/nodes/agent-v2/hooks.ts@@ -1,14 +1,14 @@import type { AgentInlineBinding } from '../../block-selector/types'import { skipToken, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useDefaultModel } from '@/app/components/header/account-setting/model-provider-page/hooks'-import { useHooksStore } from '@/app/components/workflow/hooks-store'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import { toast } from '@/app/notifications'import { useInlineAgentScope } from '@/features/agent-v2/analytics'import { consoleQuery } from '@/service/console'-import { FlowType } from '@/types/common'import { trackCreateApp } from '@/utils/create-app-tracking'import { getDefaultAgentSoul } from './agent-soul-config'@@ -46,7 +46,7 @@ export function useWorkflowInlineAgentDetail(pollUntilReady?: boolean},) {- const configsMap = useHooksStore((state) => state.configsMap)+ const resource = useAtomValue(editorResourceAtom)const refetchUntilReady = options?.pollUntilReady? {retry: INLINE_AGENT_CREATION_RETRY_COUNT,@@ -67,10 +67,10 @@ export function useWorkflowInlineAgentDetail(const appComposerQuery = useQuery(consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryOptions({input:- configsMap?.flowId && configsMap.flowType === FlowType.appFlow && nodeId && agentId+ resource.kind === 'app' && nodeId && agentId? {params: {- app_id: configsMap.flowId,+ app_id: resource.appId,node_id: nodeId,},}@@ -82,10 +82,10 @@ export function useWorkflowInlineAgentDetail(consoleQuery.snippets.bySnippetId.workflows.draft.nodes.byNodeId.agentComposer.get.queryOptions({input:- configsMap?.flowId && configsMap.flowType === FlowType.snippet && nodeId && agentId+ resource.kind === 'snippet' && nodeId && agentId? {params: {- snippet_id: configsMap.flowId,+ snippet_id: resource.snippetId,node_id: nodeId,},}@@ -95,12 +95,12 @@ export function useWorkflowInlineAgentDetail(),)- return configsMap?.flowType === FlowType.snippet ? snippetComposerQuery : appComposerQuery+ return resource.kind === 'snippet' ? snippetComposerQuery : appComposerQuery}export function useCreateInlineAgentBinding() {const { t } = useTranslation(['agentV2', 'agentRoster'])- const configsMap = useHooksStore((state) => state.configsMap)+ const resource = useAtomValue(editorResourceAtom)const agentScope = useInlineAgentScope()const { data: defaultModel } = useDefaultModel(ModelTypeEnum.textGeneration)const queryClient = useQueryClient()@@ -114,10 +114,7 @@ export function useCreateInlineAgentBinding() {const createInlineAgentBinding = useCallback(async (nodeId: string, options?: CreateInlineAgentBindingOptions) => {- if (- !configsMap?.flowId ||- (configsMap.flowType !== FlowType.appFlow && configsMap.flowType !== FlowType.snippet)- ) {+ if (resource.kind !== 'app' && resource.kind !== 'snippet') {toast.error(t(($) => $['roster.nodeSelector.createInlineFailed'], { ns: 'agentRoster' }))options?.onError?.()return@@ -136,17 +133,17 @@ export function useCreateInlineAgentBinding() {agent_soul: getDefaultAgentSoul(defaultModel),}const composerState =- configsMap.flowType === FlowType.snippet+ resource.kind === 'snippet'? await mutateSnippetComposerAsync({params: {- snippet_id: configsMap.flowId,+ snippet_id: resource.snippetId,node_id: nodeId,},body,}): await mutateAppComposerAsync({params: {- app_id: configsMap.flowId,+ app_id: resource.appId,node_id: nodeId,},body,@@ -163,13 +160,13 @@ export function useCreateInlineAgentBinding() {return}- if (configsMap.flowType === FlowType.snippet) {+ if (resource.kind === 'snippet') {queryClient.setQueryData(consoleQuery.snippets.bySnippetId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({input: {params: {- snippet_id: configsMap.flowId,+ snippet_id: resource.snippetId,node_id: nodeId,},},@@ -182,7 +179,7 @@ export function useCreateInlineAgentBinding() {consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({input: {params: {- app_id: configsMap.flowId,+ app_id: resource.appId,node_id: nodeId,},},@@ -206,8 +203,7 @@ export function useCreateInlineAgentBinding() {},[agentScope,- configsMap?.flowId,- configsMap?.flowType,+ resource,defaultModel,mutateAppComposerAsync,mutateSnippetComposerAsync,diff --git a/web/app/components/workflow/nodes/agent-v2/panel.tsx b/web/app/components/workflow/nodes/agent-v2/panel.tsxindex d4ad1cf8243..5066ac3a861 100644--- a/web/app/components/workflow/nodes/agent-v2/panel.tsx+++ b/web/app/components/workflow/nodes/agent-v2/panel.tsx@@ -10,6 +10,7 @@ import type { AgentOutputTypeOptionValue } from '@/app/components/base/prompt-edimport { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useMutation } from '@tanstack/react-query'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { createPortal } from 'react-dom'import { useTranslation } from 'react-i18next'@@ -18,10 +19,9 @@ import {extractAgentOutputNames,replaceAgentOutputName,} from '@/app/components/base/prompt-editor/plugins/agent-output-block/utils'-import { useHooksStore } from '@/app/components/workflow/hooks-store'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import { useStore } from '@/app/components/workflow/store'import { consoleQuery } from '@/service/console'-import { FlowType } from '@/types/common'import { useNodeDataUpdate } from '../../hooks/use-node-data-update'import useNodeCrud from '../_base/hooks/use-node-crud'import {@@ -136,7 +136,7 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {const { handleNodeDataUpdate, handleNodeDataUpdateWithSyncDraft } = useNodeDataUpdate()const openInlineAgentPanelNodeId = useStore((state) => state.openInlineAgentPanelNodeId)const setOpenInlineAgentPanelNodeId = useStore((state) => state.setOpenInlineAgentPanelNodeId)- const configsMap = useHooksStore((state) => state.configsMap)+ const resource = useAtomValue(editorResourceAtom)const drawerPortalContainerRef = useRef<HTMLDivElement>(null)const [localDeclaredOutputs, setLocalDeclaredOutputs] = useState<DeclaredOutputConfig[] | null>(null,@@ -190,12 +190,9 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {const isAgentBindingPending =isInlineAgentPending || isInlineAgentWaitingForCreation || isCreatingInlineAgentconst canStartFromScratch = inputs.agent_binding?.binding_type !== 'inline_agent'- const saveToRosterTarget =- configsMap?.flowId &&- (configsMap.flowType === FlowType.appFlow || configsMap.flowType === FlowType.snippet)- ? { flowId: configsMap.flowId, flowType: configsMap.flowType }- : null- const canSaveInlineToRoster = isInlineAgentReady && !!inlineAgent && !!saveToRosterTarget+ const inlineAgentResource =+ resource.kind === 'app' || resource.kind === 'snippet' ? resource : null+ const canSaveInlineToRoster = isInlineAgentReady && !!inlineAgent && !!inlineAgentResourceconst inlineComposerStateForPanel = inlineAgentQuery.dataconst displayedAgent =rosterAgentQuery.data ??@@ -340,7 +337,7 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {)const handleMakeRosterCopy = useCallback(() => {- if (!configsMap?.flowId || !rosterAgentId || isCopyingFromRoster) return+ if (!rosterAgentId || isCopyingFromRoster) returnconst body = {source_agent_id: rosterAgentId,@@ -349,11 +346,11 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {onSuccess: handleRosterCopySuccess,}- if (configsMap.flowType === FlowType.snippet) {+ if (resource.kind === 'snippet') {copyFromRosterSnippet({params: {- snippet_id: configsMap.flowId,+ snippet_id: resource.snippetId,node_id: id,},body,@@ -363,11 +360,11 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {return}- if (configsMap.flowType === FlowType.appFlow) {+ if (resource.kind === 'app') {copyFromRosterApp({params: {- app_id: configsMap.flowId,+ app_id: resource.appId,node_id: id,},body,@@ -376,8 +373,7 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {)}}, [- configsMap?.flowId,- configsMap?.flowType,+ resource,copyFromRosterApp,copyFromRosterSnippet,handleRosterCopySuccess,@@ -673,8 +669,7 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {isInlineAgentReady || isInlineAgentPending ? (<WorkflowInlineAgentConfigureWorkspaceagentId={inlineAgentId ?? undefined}- flowId={configsMap?.flowId}- flowType={configsMap?.flowType}+ resource={inlineAgentResource ?? undefined}inlineComposerState={inlineComposerStateForPanel}nodeId={id}onClose={() => handleAgentPanelOpenChange(false)}@@ -707,10 +702,9 @@ export function AgentV2Panel({ id, data }: NodePanelProps<AgentV2NodeType>) {onSaveInlineToRoster={canSaveInlineToRoster ? handleSaveInlineToRosterOpen : undefined}onStartFromScratch={canStartFromScratch ? handleStartFromScratch : undefined}/>- {saveToRosterTarget && inlineAgent && (+ {inlineAgentResource && inlineAgent && (<SaveInlineAgentToRosterDialog- flowId={saveToRosterTarget.flowId}- flowType={saveToRosterTarget.flowType}+ resource={inlineAgentResource}initialAgent={inlineAgent}nodeId={id}open={isSaveToRosterDialogOpen}diff --git a/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsxindex 3af81888d1b..f4d46ce88ab 100644--- a/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx+++ b/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx@@ -242,7 +242,7 @@ const createConfigResult = (availableNodesWithParent: [],outputSchema: [{ name: 'jsonField', type: 'String', description: 'json output' }],handleMemoryChange: vi.fn(),- isChatMode: true,+ isChatflow: true,...overrides,})diff --git a/web/app/components/workflow/nodes/agent/__tests__/node.spec.tsx b/web/app/components/workflow/nodes/agent/__tests__/node.spec.tsxindex bb7ae7cae3d..4fc1508e9e4 100644--- a/web/app/components/workflow/nodes/agent/__tests__/node.spec.tsx+++ b/web/app/components/workflow/nodes/agent/__tests__/node.spec.tsx@@ -164,7 +164,7 @@ const createConfigResult = (availableNodesWithParent: [],outputSchema: [],handleMemoryChange: vi.fn(),- isChatMode: true,+ isChatflow: true,...overrides,})diff --git a/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsxindex 3f83fb8f5cb..6d02b78c9eb 100644--- a/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsx@@ -215,7 +215,7 @@ const createConfigResult = (},],handleMemoryChange: vi.fn(),- isChatMode: true,+ isChatflow: true,...overrides,})@@ -315,7 +315,7 @@ describe('agent/panel', () => {it('hides memory config when chat mode support is unavailable', () => {mockUseConfig.mockReturnValue(createConfigResult({- isChatMode: false,+ isChatflow: false,currentStrategy: {...createConfigResult().currentStrategy!,features: [],diff --git a/web/app/components/workflow/nodes/agent/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/agent/__tests__/use-config.spec.tsindex 426e05f6778..26dc39ff6eb 100644--- a/web/app/components/workflow/nodes/agent/__tests__/use-config.spec.ts+++ b/web/app/components/workflow/nodes/agent/__tests__/use-config.spec.ts@@ -16,7 +16,6 @@ const { request, setInputs, marketplaceRefetch, marketplaceQuery } = vi.hoisted(vi.mock('@/service/base', () => ({ request }))vi.mock('../../../hooks/use-workflow', () => ({useNodesReadOnly: () => ({ nodesReadOnly: false }),- useIsChatMode: () => true,}))vi.mock('../../_base/hooks/use-node-crud', () => ({default: (_id: string, inputs: AgentNodeType) => ({ inputs, setInputs }),@@ -197,3 +196,10 @@ describe('agent strategy query and configuration', () => {await waitFor(() => expect(setInputs).toHaveBeenCalledWith(inputs))})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => true) }+})diff --git a/web/app/components/workflow/nodes/agent/panel.tsx b/web/app/components/workflow/nodes/agent/panel.tsxindex 3d03c849f3f..891b9e2467b 100644--- a/web/app/components/workflow/nodes/agent/panel.tsx+++ b/web/app/components/workflow/nodes/agent/panel.tsx@@ -22,7 +22,7 @@ const AgentPanel: FC<NodePanelProps<AgentNodeType>> = (props) => {currentStrategy,formData,onFormChange,- isChatMode,+ isChatflow,availableNodesWithParent,availableVars,readOnly,@@ -77,7 +77,7 @@ const AgentPanel: FC<NodePanelProps<AgentNodeType>> = (props) => {</MCPToolAvailabilityProvider></Field><div className="px-4 py-2">- {isChatMode && currentStrategy?.features?.includes('history-messages') && (+ {isChatflow && currentStrategy?.features?.includes('history-messages') && (<><Split /><MemoryConfigdiff --git a/web/app/components/workflow/nodes/agent/use-config.ts b/web/app/components/workflow/nodes/agent/use-config.tsindex b8330be6880..aed6d30a3e6 100644--- a/web/app/components/workflow/nodes/agent/use-config.ts+++ b/web/app/components/workflow/nodes/agent/use-config.ts@@ -3,16 +3,18 @@ import type { AgentNodeType } from './types'import type { ResourceVarInputs } from '@/app/components/workflow/nodes/_base/types'import { skipToken, useQuery } from '@tanstack/react-query'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useEffect, useMemo } from 'react'import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import {generateAgentToolValue,toolParametersToFormSchemas,} from '@/app/components/tools/utils/to-form-schema'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { VarKindType } from '@/app/components/workflow/nodes/_base/types'import { consoleQuery } from '@/service/console'import { useCheckInstalled, useFetchPluginsInMarketPlaceByIds } from '@/service/use-plugins'-import { useIsChatMode, useNodesReadOnly } from '../../hooks/use-workflow'+import { useNodesReadOnly } from '../../hooks/use-workflow'import { VarType } from '../../types'import useAvailableVarList from '../_base/hooks/use-available-var-list'import useNodeCrud from '../_base/hooks/use-node-crud'@@ -239,7 +241,7 @@ const useConfig = (id: string, payload: AgentNodeType) => {},[inputs, setInputs],)- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)return {readOnly,inputs,@@ -256,7 +258,7 @@ const useConfig = (id: string, payload: AgentNodeType) => {availableNodesWithParent,outputSchema,handleMemoryChange,- isChatMode,+ isChatflow,}}diff --git a/web/app/components/workflow/nodes/assigner/__tests__/use-config.spec.tsx b/web/app/components/workflow/nodes/assigner/__tests__/use-config.spec.tsxindex 8a94ecb4f5a..c430647c903 100644--- a/web/app/components/workflow/nodes/assigner/__tests__/use-config.spec.tsx+++ b/web/app/components/workflow/nodes/assigner/__tests__/use-config.spec.tsx@@ -15,7 +15,7 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,useNodesReadOnly: () => ({ nodesReadOnly: false }),- useIsChatMode: () => false,+useWorkflow: () => ({getBeforeNodesInSameBranchIncludeParent: () => [{ id: 'start-node', data: { title: 'Start', type: BlockEnum.Start } },@@ -157,3 +157,10 @@ describe('useConfig', () => {])})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})diff --git a/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/index.spec.tsxindex 9aa5f16d473..253eef8ad4e 100644--- a/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/index.spec.tsx+++ b/web/app/components/workflow/nodes/assigner/components/var-list/__tests__/index.spec.tsx@@ -12,7 +12,7 @@ vi.mock('../../../../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => false,+useWorkflow: () => ({getTreeLeafNodes: () => [],getNodeById: () => undefined,@@ -173,3 +173,10 @@ describe('assigner/var-list', () => {expect(handleChange).toHaveBeenLastCalledWith([])})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})diff --git a/web/app/components/workflow/nodes/assigner/hooks.ts b/web/app/components/workflow/nodes/assigner/hooks.tsindex 9fa942064d4..94a78a3c511 100644--- a/web/app/components/workflow/nodes/assigner/hooks.ts+++ b/web/app/components/workflow/nodes/assigner/hooks.ts@@ -1,8 +1,10 @@import type { Node, Var } from '../../types'import { uniqBy } from 'es-toolkit/compat'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useNodes } from 'reactflow'-import { useIsChatMode, useWorkflow } from '../../hooks/use-workflow'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'+import { useWorkflow } from '../../hooks/use-workflow'import { useWorkflowVariables } from '../../hooks/use-workflow-variables'import { AssignerNodeInputType, WriteMode } from './types'@@ -10,7 +12,7 @@ export const useGetAvailableVars = () => {const nodes: Node[] = useNodes()const { getBeforeNodesInSameBranchIncludeParent } = useWorkflow()const { getNodeAvailableVars } = useWorkflowVariables()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const getAvailableVars = useCallback((nodeId: string, handleId: string, filterVar: (v: Var) => boolean, hideEnv = false) => {const availableNodes: Node[] = []@@ -26,7 +28,7 @@ export const useGetAvailableVars = () => {return getNodeAvailableVars({parentNode,beforeNodes: uniqBy(availableNodes, 'id').filter((node) => node.id !== nodeId),- isChatMode,+ isChatflow,hideEnv,hideChatVar: hideEnv,filterVar,@@ -43,11 +45,11 @@ export const useGetAvailableVars = () => {return getNodeAvailableVars({parentNode,beforeNodes: uniqBy(availableNodes, 'id').filter((node) => node.id !== nodeId),- isChatMode,+ isChatflow,filterVar,})},- [nodes, getBeforeNodesInSameBranchIncludeParent, getNodeAvailableVars, isChatMode],+ [nodes, getBeforeNodesInSameBranchIncludeParent, getNodeAvailableVars, isChatflow],)return getAvailableVarsdiff --git a/web/app/components/workflow/nodes/assigner/use-config.ts b/web/app/components/workflow/nodes/assigner/use-config.tsindex c582fcaefb8..1a16bfaed77 100644--- a/web/app/components/workflow/nodes/assigner/use-config.ts+++ b/web/app/components/workflow/nodes/assigner/use-config.ts@@ -1,9 +1,11 @@import type { ValueSelector, Var } from '../../types'import type { AssignerNodeOperation, AssignerNodeType } from './types'+import { useAtomValue } from 'jotai'import { useCallback, useMemo } from 'react'import { useStoreApi } from 'reactflow'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'+import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'import { useWorkflowVariables } from '../../hooks/use-workflow-variables'import { useGetAvailableVars } from './hooks'import { WriteMode, writeModeTypesNum } from './types'@@ -20,7 +22,7 @@ import { convertV1ToV2 } from './utils'const useConfig = (id: string, rawPayload: AssignerNodeType) => {const payload = useMemo(() => convertV1ToV2(rawPayload), [rawPayload])const { nodesReadOnly: readOnly } = useNodesReadOnly()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const getAvailableVars = useGetAvailableVars()const store = useStoreApi()@@ -50,11 +52,11 @@ const useConfig = (id: string, rawPayload: AssignerNodeType) => {parentNode: isInIteration ? iterationNode : null,valueSelector: valueSelector || [],availableNodes,- isChatMode,+ isChatflow,isConstant: false,})},- [getCurrentVariableType, isInIteration, iterationNode, availableNodes, isChatMode],+ [getCurrentVariableType, isInIteration, iterationNode, availableNodes, isChatflow],)const handleOperationListChanges = useCallback(diff --git a/web/app/components/workflow/nodes/code/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/code/__tests__/use-config.spec.tsindex 3f1dc0a4c0e..6201046f21a 100644--- a/web/app/components/workflow/nodes/code/__tests__/use-config.spec.ts+++ b/web/app/components/workflow/nodes/code/__tests__/use-config.spec.ts@@ -1,6 +1,7 @@import type { CodeNodeType, OutputVar } from '../types'import type { Var, Variable } from '@/app/components/workflow/types'-import { act, renderHook, waitFor } from '@testing-library/react'+import { act, waitFor } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'import { useStore } from '@/app/components/workflow/store'import { BlockEnum, VarType } from '@/app/components/workflow/types'@@ -162,7 +163,9 @@ describe('code/use-config', () => {outputs: {},})- const { result } = renderHook(() => useConfig('code-node', currentInputs))+ const { result } = renderHook(() => useConfig('code-node', currentInputs), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await waitFor(() => {expect(mockSetInputs).toHaveBeenCalledWith(@@ -185,61 +188,67 @@ describe('code/use-config', () => {expect(result.current.filterVar({ type: VarType.secret } as Var)).toBe(true)})- it('fetches app and pipeline defaults, switches language, and updates code and output vars together', async () => {- workflowStoreState.appId = 'app-1'- workflowStoreState.pipelineId = 'pipeline-1'-- const { result } = renderHook(() => useConfig('code-node', currentInputs))-- await waitFor(() => {- expect(mockFetchNodeDefault).toHaveBeenCalledWith('app-1', BlockEnum.Code, {- code_language: CodeLanguage.javascript,- })- expect(mockFetchNodeDefault).toHaveBeenCalledWith('app-1', BlockEnum.Code, {- code_language: CodeLanguage.python3,+ it.each(['app', 'knowledge-pipeline'] as const)(+ 'loads %s defaults and updates code with its variables',+ async (kind) => {+ workflowStoreState.appId = 'app-1'+ workflowStoreState.pipelineId = 'pipeline-1'++ const { result } = renderHook(() => useConfig('code-node', currentInputs), {+ resource:+ kind === 'app'+ ? { kind, appId: 'app-1', mode: 'workflow' }+ : { kind, pipelineId: 'pipeline-1' },})- expect(mockFetchPipelineNodeDefault).toHaveBeenCalledWith('pipeline-1', BlockEnum.Code, {- code_language: CodeLanguage.javascript,++ const fetchDefaults = kind === 'app' ? mockFetchNodeDefault : mockFetchPipelineNodeDefault+ const otherFetch = kind === 'app' ? mockFetchPipelineNodeDefault : mockFetchNodeDefault+ const resourceId = kind === 'app' ? 'app-1' : 'pipeline-1'+ await waitFor(() => {+ expect(fetchDefaults).toHaveBeenCalledWith(resourceId, BlockEnum.Code, {+ code_language: CodeLanguage.javascript,+ })+ expect(fetchDefaults).toHaveBeenCalledWith(resourceId, BlockEnum.Code, {+ code_language: CodeLanguage.python3,+ })})- expect(mockFetchPipelineNodeDefault).toHaveBeenCalledWith('pipeline-1', BlockEnum.Code, {- code_language: CodeLanguage.python3,+ expect(otherFetch).not.toHaveBeenCalled()++ mockSetInputs.mockClear()++ act(() => {+ result.current.handleCodeLanguageChange(CodeLanguage.python3)+ result.current.handleCodeChange('function main({ bar }) { return { result: bar } }')+ result.current.handleCodeAndVarsChange(+ 'function main({ amount }) { return { total: amount } }',+ [createVariable('amount', VarType.number)],+ createOutputs('total', VarType.number),+ )})- })-- mockSetInputs.mockClear()- act(() => {- result.current.handleCodeLanguageChange(CodeLanguage.python3)- result.current.handleCodeChange('function main({ bar }) { return { result: bar } }')- result.current.handleCodeAndVarsChange(- 'function main({ amount }) { return { total: amount } }',- [createVariable('amount', VarType.number)],- createOutputs('total', VarType.number),+ expect(mockSetInputs).toHaveBeenCalledWith(+ expect.objectContaining({+ code_language: CodeLanguage.python3,+ code: pythonConfig.code,+ variables: pythonConfig.variables,+ outputs: pythonConfig.outputs,+ }),)- })-- expect(mockSetInputs).toHaveBeenCalledWith(- expect.objectContaining({- code_language: CodeLanguage.python3,- code: pythonConfig.code,- variables: pythonConfig.variables,- outputs: pythonConfig.outputs,- }),- )- expect(mockSetInputs).toHaveBeenCalledWith(- expect.objectContaining({- code: 'function main({ bar }) { return { result: bar } }',- }),- )- expect(mockSetInputs).toHaveBeenCalledWith(- expect.objectContaining({- code: 'function main({ amount }) { return { total: amount } }',- variables: [expect.objectContaining({ variable: 'amount' })],- outputs: createOutputs('total', VarType.number),- }),- )- expect(result.current.outputKeyOrders).toEqual(['total'])- })+ expect(mockSetInputs).toHaveBeenCalledWith(+ expect.objectContaining({+ code: 'function main({ bar }) { return { result: bar } }',+ }),+ )+ expect(mockSetInputs).toHaveBeenCalledWith(+ expect.objectContaining({+ code: 'function main({ amount }) { return { total: amount } }',+ variables: [expect.objectContaining({ variable: 'amount' })],+ outputs: createOutputs('total', VarType.number),+ }),+ )+ expect(result.current.outputKeyOrders).toEqual(['total'])+ },+ )it('syncs javascript and python function signatures and keeps json code unchanged', () => {currentInputs = createData({@@ -248,7 +257,9 @@ describe('code/use-config', () => {variables: [createVariable('foo'), createVariable('bar')],})- const { result, rerender } = renderHook(() => useConfig('code-node', currentInputs))+ const { result, rerender } = renderHook(() => useConfig('code-node', currentInputs), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSyncFunctionSignature()@@ -320,7 +331,9 @@ describe('code/use-config', () => {workflowStoreState.appId = undefinedworkflowStoreState.pipelineId = undefined- const { result } = renderHook(() => useConfig('code-node', currentInputs))+ const { result } = renderHook(() => useConfig('code-node', currentInputs), {+ resource: { kind: 'snippet', snippetId: 'snippet-1' },+ })await waitFor(() => {expect(result.current.outputKeyOrders).toEqual(['summary', 'count'])diff --git a/web/app/components/workflow/nodes/code/use-config.ts b/web/app/components/workflow/nodes/code/use-config.tsindex fd6187a3849..ff8c325affc 100644--- a/web/app/components/workflow/nodes/code/use-config.ts+++ b/web/app/components/workflow/nodes/code/use-config.ts@@ -1,7 +1,12 @@import type { Var, Variable } from '../../types'import type { CodeNodeType, OutputVar } from './types'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useEffect, useState } from 'react'+import {+ editorAppIdAtom,+ editorPipelineIdAtom,+} from '@/app/components/workflow/editor-resource/state'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'import { fetchNodeDefault, fetchPipelineNodeDefault } from '@/service/workflow'import { useNodesReadOnly } from '../../hooks/use-workflow'@@ -14,8 +19,8 @@ import { CodeLanguage } from './types'const useConfig = (id: string, payload: CodeNodeType) => {const { nodesReadOnly: readOnly } = useNodesReadOnly()- const appId = useStore((s) => s.appId)- const pipelineId = useStore((s) => s.pipelineId)+ const appId = useAtomValue(editorAppIdAtom)+ const pipelineId = useAtomValue(editorPipelineIdAtom)const [allLanguageDefault, setAllLanguageDefault] = useState<Record<CodeLanguage,diff --git a/web/app/components/workflow/nodes/data-source/__tests__/before-run-form.spec.tsx b/web/app/components/workflow/nodes/data-source/__tests__/before-run-form.spec.tsxindex 732dfca9b34..b2bf919ef94 100644--- a/web/app/components/workflow/nodes/data-source/__tests__/before-run-form.spec.tsx+++ b/web/app/components/workflow/nodes/data-source/__tests__/before-run-form.spec.tsx@@ -3,7 +3,6 @@ import type { CustomRunFormProps, DataSourceNodeType } from '../types'import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { DatasourceType } from '@/models/pipeline'-import { FlowType } from '@/types/common'import { BlockEnum } from '../../../types'import BeforeRunForm from '../before-run-form'import useBeforeRunForm from '../hooks/use-before-run-form'@@ -120,8 +119,8 @@ const createData = (overrides: Partial<DataSourceNodeType> = {}): DataSourceNodeconst createProps = (overrides: Partial<CustomRunFormProps> = {}): CustomRunFormProps => ({nodeId: 'data-source-node',- flowId: 'flow-id',- flowType: FlowType.ragPipeline,+ resource: { kind: 'knowledge-pipeline', pipelineId: 'flow-id' },+payload: createData(),setRunResult: vi.fn(),setIsRunAfterSingleRun: vi.fn(),diff --git a/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-before-run-form.branches.spec.tsx b/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-before-run-form.branches.spec.tsxindex bb05f8dc2a3..04485b7e498 100644--- a/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-before-run-form.branches.spec.tsx+++ b/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-before-run-form.branches.spec.tsx@@ -9,9 +9,8 @@ import {import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'import { DatasourceType } from '@/models/pipeline'import { useDatasourceSingleRun } from '@/service/use-pipeline'-import { useInvalidLastRun } from '@/service/use-workflow'+import { useInvalidateLastRun } from '@/service/use-workflow'import { fetchNodeInspectVars } from '@/service/workflow'-import { FlowType } from '@/types/common'import { useNodeDataUpdate } from '../../../../hooks/use-node-data-update'import { useNodesSyncDraft } from '../../../../hooks/use-nodes-sync-draft'import useBeforeRunForm from '../use-before-run-form'@@ -82,7 +81,7 @@ vi.mock('@/service/use-pipeline', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidLastRun: vi.fn(),+ useInvalidateLastRun: vi.fn(),}))vi.mock('@/service/workflow', () => ({@@ -98,7 +97,7 @@ const mockUseStoreApi = vi.mocked(useStoreApi)const mockUseNodeDataUpdateHook = vi.mocked(useNodeDataUpdate)const mockUseNodesSyncDraftHook = vi.mocked(useNodesSyncDraft)const mockUseDatasourceSingleRunHook = vi.mocked(useDatasourceSingleRun)-const mockUseInvalidLastRunHook = vi.mocked(useInvalidLastRun)+const mockUseInvalidLastRunHook = vi.mocked(useInvalidateLastRun)const mockFetchNodeInspectVarsFn = vi.mocked(fetchNodeInspectVars)const mockUseDataSourceStoreHook = vi.mocked(useDataSourceStore)const mockUseDataSourceStoreWithSelectorHook = vi.mocked(useDataSourceStoreWithSelector)@@ -120,8 +119,8 @@ const createData = (overrides: Partial<DataSourceNodeType> = {}): DataSourceNodeconst createProps = (overrides: Partial<CustomRunFormProps> = {}): CustomRunFormProps => ({nodeId: 'data-source-node',- flowId: 'flow-id',- flowType: FlowType.ragPipeline,+ resource: { kind: 'knowledge-pipeline', pipelineId: 'flow-id' },+payload: createData(),setRunResult: vi.fn(),setIsRunAfterSingleRun: vi.fn(),diff --git a/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-before-run-form.spec.tsx b/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-before-run-form.spec.tsxindex 9c73404978a..7c4f76df6c4 100644--- a/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-before-run-form.spec.tsx+++ b/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-before-run-form.spec.tsx@@ -1,18 +1,18 @@import type { CustomRunFormProps, DataSourceNodeType } from '../../types'import type { NodeRunResult, VarInInspect } from '@/types/workflow'-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'import { useStoreApi } from 'reactflow'import {useDataSourceStore,useDataSourceStoreWithSelector,} from '@/app/components/datasets/documents/create-from-pipeline/data-source/store'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'import { DatasourceType } from '@/models/pipeline'import { useDatasourceSingleRun } from '@/service/use-pipeline'-import { useInvalidLastRun } from '@/service/use-workflow'+import { useInvalidateLastRun } from '@/service/use-workflow'import { fetchNodeInspectVars } from '@/service/workflow'import { TransferMethod } from '@/types/app'-import { FlowType } from '@/types/common'import { useNodeDataUpdate } from '../../../../hooks/use-node-data-update'import { useNodesSyncDraft } from '../../../../hooks/use-nodes-sync-draft'import useBeforeRunForm from '../use-before-run-form'@@ -83,7 +83,7 @@ vi.mock('@/service/use-pipeline', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidLastRun: vi.fn(),+ useInvalidateLastRun: vi.fn(),}))vi.mock('@/service/workflow', () => ({@@ -99,7 +99,7 @@ const mockUseStoreApi = vi.mocked(useStoreApi)const mockUseNodeDataUpdateHook = vi.mocked(useNodeDataUpdate)const mockUseNodesSyncDraftHook = vi.mocked(useNodesSyncDraft)const mockUseDatasourceSingleRunHook = vi.mocked(useDatasourceSingleRun)-const mockUseInvalidLastRunHook = vi.mocked(useInvalidLastRun)+const mockUseInvalidLastRunHook = vi.mocked(useInvalidateLastRun)const mockFetchNodeInspectVarsFn = vi.mocked(fetchNodeInspectVars)const mockUseDataSourceStoreHook = vi.mocked(useDataSourceStore)const mockUseDataSourceStoreWithSelectorHook = vi.mocked(useDataSourceStoreWithSelector)@@ -121,8 +121,8 @@ const createData = (overrides: Partial<DataSourceNodeType> = {}): DataSourceNodeconst createProps = (overrides: Partial<CustomRunFormProps> = {}): CustomRunFormProps => ({nodeId: 'data-source-node',- flowId: 'flow-id',- flowType: FlowType.ragPipeline,+ resource: { kind: 'knowledge-pipeline', pipelineId: 'flow-id' },+payload: createData(),setRunResult: vi.fn(),setIsRunAfterSingleRun: vi.fn(),@@ -205,6 +205,7 @@ describe('data-source/hooks/use-before-run-form', () => {const { result, rerender } = renderHook(({ payload }) => useBeforeRunForm(createProps({ payload })),{+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },initialProps: {payload: createData(),},@@ -257,7 +258,9 @@ describe('data-source/hooks/use-before-run-form', () => {})const props = createProps()- const { result } = renderHook(() => useBeforeRunForm(props))+ const { result } = renderHook(() => useBeforeRunForm(props), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {result.current.handleRunWithSyncDraft()@@ -284,8 +287,7 @@ describe('data-source/hooks/use-before-run-form', () => {expect.any(Object),)expect(mockFetchNodeInspectVars).toHaveBeenCalledWith(- FlowType.ragPipeline,- 'flow-id',+ { kind: 'knowledge-pipeline', pipelineId: 'flow-id' },'data-source-node',)expect(props.appendNodeInspectVars).toHaveBeenCalledWith(@@ -324,14 +326,16 @@ describe('data-source/hooks/use-before-run-form', () => {return Promise.resolve(undefined)})- const { result } = renderHook(() =>- useBeforeRunForm(- createProps({- payload: createData({- provider_type: DatasourceType.onlineDrive,+ const { result } = renderHook(+ () =>+ useBeforeRunForm(+ createProps({+ payload: createData({+ provider_type: DatasourceType.onlineDrive,+ }),}),- }),- ),+ ),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)await act(async () => {diff --git a/web/app/components/workflow/nodes/data-source/hooks/use-before-run-form.ts b/web/app/components/workflow/nodes/data-source/hooks/use-before-run-form.tsindex 9489071ff44..94aa4782c65 100644--- a/web/app/components/workflow/nodes/data-source/hooks/use-before-run-form.ts+++ b/web/app/components/workflow/nodes/data-source/hooks/use-before-run-form.ts@@ -9,18 +9,16 @@ import {} from '@/app/components/datasets/documents/create-from-pipeline/data-source/store'import { DatasourceType } from '@/models/pipeline'import { useDatasourceSingleRun } from '@/service/use-pipeline'-import { useInvalidLastRun } from '@/service/use-workflow'+import { useInvalidateLastRun } from '@/service/use-workflow'import { fetchNodeInspectVars } from '@/service/workflow'import { TransferMethod } from '@/types/app'-import { FlowType } from '@/types/common'import { useNodeDataUpdate } from '../../../hooks/use-node-data-update'import { useNodesSyncDraft } from '../../../hooks/use-nodes-sync-draft'import { NodeRunningStatus } from '../../../types'const useBeforeRunForm = ({nodeId,- flowId,- flowType,+ resource,payload,setRunResult,isPaused,@@ -29,6 +27,9 @@ const useBeforeRunForm = ({onSuccess,appendNodeInspectVars,}: CustomRunFormProps) => {+ if (resource.kind !== 'knowledge-pipeline')+ throw new Error('Data source runs require a knowledge pipeline')+ const flowId = resource.pipelineIdconst store = useStoreApi()const dataSourceStore = useDataSourceStore()const isPausedRef = useRef(isPaused)@@ -80,7 +81,7 @@ const useBeforeRunForm = ({})}- const invalidLastRun = useInvalidLastRun(flowType, flowId, nodeId)+ const invalidLastRun = useInvalidateLastRun(resource, nodeId)const updateRunResult = async (data: NodeRunResult) => {const isPaused = isPausedRef.current@@ -95,7 +96,7 @@ const useBeforeRunForm = ({}// run fail may also update the inspect vars when the node set the error default output.- const vars = await fetchNodeInspectVars(FlowType.ragPipeline, flowId, nodeId)+ const vars = await fetchNodeInspectVars(resource, nodeId)const { getNodes } = store.getState()const nodes = getNodes()appendNodeInspectVars(nodeId, vars, nodes)diff --git a/web/app/components/workflow/nodes/data-source/panel.tsx b/web/app/components/workflow/nodes/data-source/panel.tsxindex bd6db16ea46..72a344528d8 100644--- a/web/app/components/workflow/nodes/data-source/panel.tsx+++ b/web/app/components/workflow/nodes/data-source/panel.tsx@@ -1,9 +1,11 @@import type { FC } from 'react'import type { DataSourceNodeType } from './types'import type { NodePanelProps } from '@/app/components/workflow/types'+import { useAtomValue } from 'jotai'import { memo, useMemo } from 'react'import { useTranslation } from 'react-i18next'import TagInput from '@/app/components/base/tag-input'+import { editorResourceKindAtom } from '@/app/components/workflow/editor-resource/state'import { BoxGroupField } from '@/app/components/workflow/nodes/_base/components/layout'import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/components/output-vars'import StructureOutputItem from '@/app/components/workflow/nodes/_base/components/variable/object-child-tree-panel/show'@@ -20,7 +22,7 @@ import { useConfig } from './hooks/use-config'import { DataSourceClassification } from './types'const Panel: FC<NodePanelProps<DataSourceNodeType>> = ({ id, data }) => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const { nodesReadOnly } = useNodesReadOnly()const dataSourceList = useStore((s) => s.dataSourceList)const { provider_type, fileExtensions = [], datasource_parameters } = data@@ -36,7 +38,7 @@ const Panel: FC<NodePanelProps<DataSourceNodeType>> = ({ id, data }) => {[currentDataSourceItem],)- const pipelineId = useStore((s) => s.pipelineId)+ const resourceKind = useAtomValue(editorResourceKindAtom)const setShowInputFieldPanel = useStore((s) => s.setShowInputFieldPanel)const { schemaTypeDefinitions } = useMatchSchemaType()return (@@ -61,7 +63,7 @@ const Panel: FC<NodePanelProps<DataSourceNodeType>> = ({ id, data }) => {staticSchemavalue={datasource_parameters}onChange={handleParametersChange}- showManageInputField={!!pipelineId}+ showManageInputField={resourceKind === 'knowledge-pipeline'}onManageInputField={() => setShowInputFieldPanel?.(true)}/>)}diff --git a/web/app/components/workflow/nodes/data-source/types.ts b/web/app/components/workflow/nodes/data-source/types.tsindex 9ec61d41090..1bc32181bfb 100644--- a/web/app/components/workflow/nodes/data-source/types.ts+++ b/web/app/components/workflow/nodes/data-source/types.ts@@ -1,8 +1,8 @@import type { DatasourceProviderType } from '@dify/contracts/api/console/workspaces/types.gen'import type { Dispatch, SetStateAction } from 'react'import type { ResourceVarInputs } from '../_base/types'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type { CommonNodeType, Node } from '@/app/components/workflow/types'-import type { FlowType } from '@/types/common'import type { NodeRunResult, VarInInspect } from '@/types/workflow'export const DataSourceClassification = {@@ -23,8 +23,7 @@ export type DataSourceNodeType = CommonNodeType & {export type CustomRunFormProps = {nodeId: string- flowId: string- flowType: FlowType+ resource: EditorResourcepayload: CommonNodeTypesetRunResult: Dispatch<SetStateAction<NodeRunResult | null>>setIsRunAfterSingleRun: Dispatch<SetStateAction<boolean>>diff --git a/web/app/components/workflow/nodes/document-extractor/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/document-extractor/__tests__/use-config.spec.tsindex e181164fa73..1cfd66ff442 100644--- a/web/app/components/workflow/nodes/document-extractor/__tests__/use-config.spec.ts+++ b/web/app/components/workflow/nodes/document-extractor/__tests__/use-config.spec.ts@@ -3,14 +3,14 @@ import { renderHook } from '@testing-library/react'import { useStoreApi } from 'reactflow'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'import { BlockEnum, VarType } from '@/app/components/workflow/types'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../../hooks/use-workflow'+import { useNodesReadOnly, useWorkflow } from '../../../hooks/use-workflow'import { useWorkflowVariables } from '../../../hooks/use-workflow-variables'import useConfig from '../use-config'const mockUseStoreApi = vi.mocked(useStoreApi)const mockUseNodesReadOnly = vi.mocked(useNodesReadOnly)const mockUseNodeCrud = vi.mocked(useNodeCrud)-const mockUseIsChatMode = vi.mocked(useIsChatMode)+const mockUseIsChatMode = vi.hoisted(() => vi.fn())const mockUseWorkflow = vi.mocked(useWorkflow)const mockUseWorkflowVariables = vi.mocked(useWorkflowVariables)@@ -27,7 +27,7 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: vi.fn(),+useNodesReadOnly: vi.fn(),useWorkflow: vi.fn(),}@@ -109,3 +109,10 @@ describe('document-extractor/use-config', () => {expect(result.current.filterVar({ type: VarType.string } as never)).toBe(false)})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/nodes/document-extractor/use-config.ts b/web/app/components/workflow/nodes/document-extractor/use-config.tsindex a54a310f132..63ea033ef8d 100644--- a/web/app/components/workflow/nodes/document-extractor/use-config.ts+++ b/web/app/components/workflow/nodes/document-extractor/use-config.ts@@ -1,10 +1,12 @@import type { ValueSelector, Var } from '../../types'import type { DocExtractorNodeType } from './types'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useMemo } from 'react'import { useStoreApi } from 'reactflow'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'+import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'import { useWorkflowVariables } from '../../hooks/use-workflow-variables'import { VarType } from '../../types'@@ -16,7 +18,7 @@ const useConfig = (id: string, payload: DocExtractorNodeType) => {return varPayload.type === VarType.file || varPayload.type === VarType.arrayFile}, [])- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const store = useStoreApi()const { getBeforeNodesInSameBranch } = useWorkflow()@@ -39,12 +41,12 @@ const useConfig = (id: string, payload: DocExtractorNodeType) => {parentNode: isInIteration ? iterationNode : loopNode,valueSelector: variable || [],availableNodes,- isChatMode,+ isChatflow,isConstant: false,})return varType},- [getCurrentVariableType, isInIteration, availableNodes, isChatMode, iterationNode, loopNode],+ [getCurrentVariableType, isInIteration, availableNodes, isChatflow, iterationNode, loopNode],)const handleVarChanges = useCallback(diff --git a/web/app/components/workflow/nodes/end/__tests__/node.spec.tsx b/web/app/components/workflow/nodes/end/__tests__/node.spec.tsxindex 87c1050eda2..02a9b94e00a 100644--- a/web/app/components/workflow/nodes/end/__tests__/node.spec.tsx+++ b/web/app/components/workflow/nodes/end/__tests__/node.spec.tsx@@ -3,7 +3,7 @@ import { screen } from '@testing-library/react'import { createNode, createStartNode } from '@/app/components/workflow/__tests__/fixtures'import { renderNodeComponent } from '@/app/components/workflow/__tests__/workflow-test-env'import { BlockEnum } from '@/app/components/workflow/types'-import { useIsChatMode, useWorkflow } from '../../../hooks/use-workflow'+import { useWorkflow } from '../../../hooks/use-workflow'import { useWorkflowVariables } from '../../../hooks/use-workflow-variables'import Node from '../node'@@ -13,7 +13,6 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,useWorkflow: vi.fn(),- useIsChatMode: vi.fn(),}})@@ -28,7 +27,7 @@ vi.mock('../../../hooks/use-workflow-variables', async (importOriginal) => {const mockUseWorkflow = vi.mocked(useWorkflow)const mockUseWorkflowVariables = vi.mocked(useWorkflowVariables)-const mockUseIsChatMode = vi.mocked(useIsChatMode)+const mockUseIsChatMode = vi.hoisted(() => vi.fn())const createNodeData = (overrides: Partial<EndNodeType> = {}): EndNodeType => ({title: 'End',@@ -109,3 +108,10 @@ describe('EndNode', () => {})})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/nodes/end/node.tsx b/web/app/components/workflow/nodes/end/node.tsxindex cc93492ce15..c0ca2c06455 100644--- a/web/app/components/workflow/nodes/end/node.tsx+++ b/web/app/components/workflow/nodes/end/node.tsx@@ -1,17 +1,19 @@import type { FC } from 'react'import type { EndNodeType } from './types'import type { NodeProps, Variable } from '@/app/components/workflow/types'+import { useAtomValue } from 'jotai'import * as React from 'react'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { VariableLabelInNode } from '@/app/components/workflow/nodes/_base/components/variable/variable-label'import { BlockEnum } from '@/app/components/workflow/types'-import { useIsChatMode, useWorkflow } from '../../hooks/use-workflow'+import { useWorkflow } from '../../hooks/use-workflow'import { useWorkflowVariables } from '../../hooks/use-workflow-variables'const Node: FC<NodeProps<EndNodeType>> = ({ id, data }) => {const { getBeforeNodesInSameBranch } = useWorkflow()const availableNodes = getBeforeNodesInSameBranch(id)const { getCurrentVariableType } = useWorkflowVariables()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const startNode = availableNodes.find((node: any) => {return node.data.type === BlockEnum.Start@@ -35,7 +37,7 @@ const Node: FC<NodeProps<EndNodeType>> = ({ id, data }) => {const varType = getCurrentVariableType({valueSelector: value_selector,availableNodes,- isChatMode,+ isChatflow,})return (diff --git a/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsx b/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsxindex 0c98414f2e4..c90092a6918 100644--- a/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsx+++ b/web/app/components/workflow/nodes/human-input/__tests__/human-input.spec.tsx@@ -80,7 +80,6 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {getNodesReadOnly: () => false,nodesReadOnly: false,}),- useIsChatMode: () => false,}})@@ -650,3 +649,10 @@ describe('DSL Import with Human Input Node', () => {})})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsxindex 4d660cca00a..1f5942e235d 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/__tests__/test-email-sender.spec.tsx@@ -10,6 +10,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'+import { EditorResourceScope } from '@/app/components/workflow/editor-resource/provider'import { HooksStoreContext } from '@/app/components/workflow/hooks-store/provider'import { createHooksStore } from '@/app/components/workflow/hooks-store/store'import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'@@ -19,11 +20,6 @@ import { seedAccountProfileQuery } from '@/test/console/account-profile'import { render } from '@/test/console/render'import EmailSenderModal from '../test-email-sender'-vi.mock('@/next/navigation', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/next/navigation')>()),- useParams: () => ({ appId: 'app-1' }),-}))-vi.mock('@/app/notifications', async (importOriginal) => ({...(await importOriginal()),toast: {@@ -73,7 +69,9 @@ const renderWithProviders = (ui: ReactNode) => {return render(<QueryClientProvider client={queryClient}>- <HooksStoreContext.Provider value={hooksStore}>{ui}</HooksStoreContext.Provider>+ <EditorResourceScope resource={{ kind: 'app', appId: 'app-1', mode: 'workflow' }}>+ <HooksStoreContext.Provider value={hooksStore}>{ui}</HooksStoreContext.Provider>+ </EditorResourceScope></QueryClientProvider>,)}diff --git a/web/app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsx b/web/app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsxindex cfb44e60f14..575a1b18413 100644--- a/web/app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsx+++ b/web/app/components/workflow/nodes/human-input/components/delivery-method/test-email-sender.tsx@@ -12,6 +12,7 @@ import { useAtomValue } from 'jotai'import { memo, useCallback, useMemo, useState } from 'react'import { Trans, useTranslation } from 'react-i18next'import { getInputVars as doGetInputVars } from '@/app/components/base/prompt-editor/constants'+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'import FormItem from '@/app/components/workflow/nodes/_base/components/before-run-form/form-item'import { formatValue } from '@/app/components/workflow/nodes/_base/components/before-run-form/helpers'import {@@ -24,7 +25,6 @@ import { InputVarType, VarType } from '@/app/components/workflow/types'import { toast } from '@/app/notifications'import { currentWorkspaceAtom } from '@/context/workspace-state'import { userProfileQueryOptions } from '@/features/account-profile/client'-import { useParams } from '@/next/navigation'import { useMembers } from '@/service/use-common'import { useTestEmailSender } from '@/service/use-workflow'import { getHumanInputFormDependencySelectors, isOutput } from '../../utils'@@ -135,7 +135,7 @@ const EmailSenderContent = ({select: (data) => data.profile.email,})const currentWorkspace = useAtomValue(currentWorkspaceAtom)- const { appId } = useParams<{ appId?: string }>()+ const appId = useAtomValue(editorAppIdAtom)const { mutateAsync: testEmailSender } = useTestEmailSender()const debugEnabled = !!config?.debug_mode@@ -222,7 +222,7 @@ const EmailSenderContent = ({}, [generatedInputs, inputs])const handleConfirm = useCallback(async () => {- if (!confirmChecked) return+ if (!confirmChecked || !appId) returnconst { formattedValues, parseErrorJsonField } = formatEmailSenderInputs(generatedInputs,inputs,@@ -236,7 +236,7 @@ const EmailSenderContent = ({setSendingEmail(true)try {await testEmailSender({- appID: appId || '',+ appID: appId,nodeID: nodeId,deliveryID: deliveryId,inputs: formattedValues,diff --git a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.tsindex 7ce96ce9c7b..8fefdcf0fed 100644--- a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts+++ b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts@@ -1,17 +1,15 @@import type { HumanInputNodeType } from '../../types'+import type { WorkflowAppMode } from '@/app/components/apps/app-type'import type { FileEntity } from '@/app/components/base/file-uploader/types'import type { InputVar } from '@/app/components/workflow/types'import type { HumanInputFormData } from '@/types/workflow'import { act } from '@testing-library/react'+import { renderEditorHook as renderHookWithConsoleQuery } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'-import {- createConsoleQueryClient,- renderHookWithConsoleQuery,- seedAppDetail,-} from '@/test/console/query-data'+import { createConsoleQueryClient, seedAppDetail } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'import { withSelectorKey } from '@/test/i18n-mock'-import { AppModeEnum, TransferMethod } from '@/types/app'+import { TransferMethod } from '@/types/app'import useSingleRunFormParams from '../use-single-run-form-params'const mockUseTranslation = vi.hoisted(() => vi.fn())@@ -92,12 +90,19 @@ describe('human-input/hooks/use-single-run-form-params', () => {const mockSetRunInputData = vi.fn()const getInputVars = vi.fn()let currentInputs = createPayload()- let appDetail: { id: string; mode: AppModeEnum } | undefined+ let appDetail: { id: string; mode: WorkflowAppMode } | undefinedconst renderHook = <Result>(callback: () => Result) => {const queryClient = createConsoleQueryClient()if (appDetail) seedAppDetail(queryClient, createAppDetailFixture(appDetail))- return renderHookWithConsoleQuery(callback, { queryClient })+ return renderHookWithConsoleQuery(callback, {+ queryClient,+ resource: {+ kind: 'app',+ appId: appDetail?.id ?? 'app-1',+ mode: appDetail?.mode ?? 'workflow',+ },+ })}beforeEach(() => {@@ -105,7 +110,7 @@ describe('human-input/hooks/use-single-run-form-params', () => {currentInputs = createPayload()appDetail = {id: 'app-1',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,}mockUseTranslation.mockReturnValue({@@ -352,13 +357,13 @@ describe('human-input/hooks/use-single-run-form-params', () => {expect(result.current.showGeneratedForm).toBe(false)})- it('should use the advanced-chat endpoint and skip remote fetches when app detail is missing', async () => {+ it('should use the advanced-chat endpoint for chatflow form previews', async () => {appDetail = {id: 'app-2',- mode: AppModeEnum.ADVANCED_CHAT,+ mode: 'advanced-chat' as const,}- const { result, rerender } = renderHook(() =>+ const { result } = renderHook(() =>useSingleRunFormParams({id: 'node-9',payload: currentInputs,@@ -379,14 +384,6 @@ describe('human-input/hooks/use-single-run-form-params', () => {},)- appDetail = undefined- rerender()-- await act(async () => {- const data = await result.current.handleFetchFormContent({ topic: 'skip' })- expect(data).toBeNull()- })-expect(mockFetchHumanInputNodeStepRunForm).toHaveBeenCalledTimes(1)})})diff --git a/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts b/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.tsindex b99fb570e87..736c2ba169e 100644--- a/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts+++ b/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts@@ -3,14 +3,12 @@ import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answeimport type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'import type { InputVar } from '@/app/components/workflow/types'import type { HumanInputFormData } from '@/types/workflow'-import { skipToken, useQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { getProcessedHumanInputFormInputs } from '@/app/components/base/chat/chat/answer/human-input-content/utils'-import { useParams } from '@/next/navigation'-import { consoleQuery } from '@/service/console'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import { fetchHumanInputNodeStepRunForm, submitHumanInputNodeStepRunForm } from '@/service/workflow'-import { AppModeEnum } from '@/types/app'import useNodeCrud from '../../_base/hooks/use-node-crud'import { getHumanInputFormDependencySelectors, isOutput } from '../utils'@@ -70,14 +68,9 @@ const useSingleRunFormParams = ({.filter((arr) => arr.length > 0)}- const { appId } = useParams<{ appId?: string }>()- const { data: appMode } = useQuery(- consoleQuery.apps.byAppId.get.queryOptions({- input: appId ? { params: { app_id: appId } } : skipToken,- select: (appDetail) => appDetail.mode,- }),- )- const isWorkflowMode = appMode === AppModeEnum.WORKFLOW+ const resource = useAtomValue(editorResourceAtom)+ const appId = resource.kind === 'app' ? resource.appId : undefined+ const isWorkflowMode = resource.kind === 'app' && resource.mode === 'workflow'const fetchURL = useMemo(() => {if (!appId) return ''if (!isWorkflowMode) {diff --git a/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsxindex 912cd0334a7..26f374a43f1 100644--- a/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsx+++ b/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsx@@ -1,10 +1,13 @@import type { Var } from '../../../types'import type { IfElseNodeType } from '../types'import type { PanelProps } from '@/types/workflow'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import {+ renderEditor as render,+ renderEditor as renderWithConsoleQuery,+} from '@/app/components/workflow/editor-resource/__tests__/render'import { VarKindType } from '@/app/components/workflow/nodes/_base/types'-import { renderWithConsoleQuery } from '@/test/console/query-data'import { BlockEnum, VarType } from '../../../types'import ConditionAdd from '../components/condition-add'import ConditionFilesListValue from '../components/condition-files-list-value'@@ -219,7 +222,9 @@ describe('if-else path', () => {const user = userEvent.setup()const onSelectVariable = vi.fn()- render(<ConditionAdd caseId="case-1" variables={[]} onSelectVariable={onSelectVariable} />)+ render(<ConditionAdd caseId="case-1" variables={[]} onSelectVariable={onSelectVariable} />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await user.click(screen.getByRole('button', { name: /workflowLogic.nodes.ifElse.addCondition/i }),@@ -253,6 +258,7 @@ describe('if-else path', () => {unit="%"/></div>,+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)await user.click(screen.getByRole('button', { name: /contains/i }))@@ -341,6 +347,7 @@ describe('if-else path', () => {}}/></div>,+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)expect(screen.getByText('node-1.answer')).toBeInTheDocument()@@ -386,6 +393,7 @@ describe('if-else path', () => {],})}/>,+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)expect(screen.getByText('IF')).toBeInTheDocument()@@ -412,7 +420,9 @@ describe('if-else path', () => {}),)- render(<Panel id="if-else-node" data={inputs} panelProps={panelProps} />)+ render(<Panel id="if-else-node" data={inputs} panelProps={panelProps} />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await user.click(screen.getByRole('button', { name: /elif/i }))diff --git a/web/app/components/workflow/nodes/if-else/components/condition-list/condition-input.tsx b/web/app/components/workflow/nodes/if-else/components/condition-list/condition-input.tsxindex 3ae9be328b8..abf5c19a653 100644--- a/web/app/components/workflow/nodes/if-else/components/condition-list/condition-input.tsx+++ b/web/app/components/workflow/nodes/if-else/components/condition-list/condition-input.tsx@@ -1,6 +1,8 @@import type { Node, NodeOutPutVar } from '@/app/components/workflow/types'+import { useAtomValue } from 'jotai'import { useTranslation } from 'react-i18next'import PromptEditor from '@/app/components/base/prompt-editor'+import { editorResourceKindAtom } from '@/app/components/workflow/editor-resource/state'import { useStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'@@ -20,7 +22,7 @@ const ConditionInput = ({}: ConditionInputProps) => {const { t } = useTranslation(['workflow', 'workflowLogic'])const controlPromptEditorRerenderKey = useStore((s) => s.controlPromptEditorRerenderKey)- const pipelineId = useStore((s) => s.pipelineId)+ const resourceKind = useAtomValue(editorResourceKindAtom)const setShowInputFieldPanel = useStore((s) => s.setShowInputFieldPanel)return (@@ -48,7 +50,7 @@ const ConditionInput = ({}return acc}, {} as any),- showManageInputField: !!pipelineId,+ showManageInputField: resourceKind === 'knowledge-pipeline',onManageInputField: () => setShowInputFieldPanel?.(true),}}onChange={onChange}diff --git a/web/app/components/workflow/nodes/if-else/components/condition-list/condition-item.tsx b/web/app/components/workflow/nodes/if-else/components/condition-list/condition-item.tsxindex 666db4f05f3..93f55a1a3a2 100644--- a/web/app/components/workflow/nodes/if-else/components/condition-list/condition-item.tsx+++ b/web/app/components/workflow/nodes/if-else/components/condition-list/condition-item.tsx@@ -23,8 +23,10 @@ import {} from '@langgenius/dify-ui/select'import { RiDeleteBinLine } from '@remixicon/react'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { getVarType } from '@/app/components/workflow/nodes/_base/components/variable/utils'import BoolValue from '@/app/components/workflow/panel/chat-variable-panel/components/bool-value'import { useWorkflowStore } from '@/app/components/workflow/store'@@ -35,7 +37,6 @@ import {useAllMCPTools,useAllWorkflowTools,} from '@/service/use-tools'-import { useIsChatMode } from '../../../../hooks/use-workflow'import useMatchSchemaType from '../../../_base/components/variable/use-match-schema-type'import { FILE_TYPE_OPTIONS, SUB_VARIABLES, TRANSFER_METHOD } from '../../../constants'import { ComparisonOperator } from '../../types'@@ -101,7 +102,7 @@ const ConditionItem = ({]const { t } = useTranslation(['common', 'workflow', 'workflowLogic'])- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const [isHovered, setIsHovered] = useState(false)const [open, setOpen] = useState(false)@@ -257,7 +258,7 @@ const ConditionItem = ({valueSelector,conversationVariables,availableNodes,- isChatMode,+ isChatflow,allPluginInfoList: {buildInTools: buildInTools || [],customTools: customTools || [],@@ -285,7 +286,7 @@ const ConditionItem = ({condition,doUpdateCondition,availableNodes,- isChatMode,+ isChatflow,schemaTypeDefinitions,buildInTools,customTools,diff --git a/web/app/components/workflow/nodes/if-else/use-is-var-file-attribute.ts b/web/app/components/workflow/nodes/if-else/use-is-var-file-attribute.tsindex 635ef55b51e..f3cde2d122f 100644--- a/web/app/components/workflow/nodes/if-else/use-is-var-file-attribute.ts+++ b/web/app/components/workflow/nodes/if-else/use-is-var-file-attribute.ts@@ -1,7 +1,9 @@import type { ValueSelector } from '../../types'+import { useAtomValue } from 'jotai'import { useMemo } from 'react'import { useStoreApi } from 'reactflow'-import { useIsChatMode, useWorkflow } from '../../hooks/use-workflow'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'+import { useWorkflow } from '../../hooks/use-workflow'import { useWorkflowVariables } from '../../hooks/use-workflow-variables'import { VarType } from '../../types'@@ -11,7 +13,7 @@ type Params = {isInLoop: boolean}const useIsVarFileAttribute = ({ nodeId, isInIteration, isInLoop }: Params) => {- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const store = useStoreApi()const { getBeforeNodesInSameBranch } = useWorkflow()const { getNodes } = store.getState()@@ -31,7 +33,7 @@ const useIsVarFileAttribute = ({ nodeId, isInIteration, isInLoop }: Params) => {parentNode: isInIteration ? iterationNode : loopNode,valueSelector: parentVariable,availableNodes,- isChatMode,+ isChatflow,isConstant: false,})return varType === VarType.filediff --git a/web/app/components/workflow/nodes/iteration-start/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/iteration-start/__tests__/index.spec.tsxindex dbfef5c8d13..53d3552c3fb 100644--- a/web/app/components/workflow/nodes/iteration-start/__tests__/index.spec.tsx+++ b/web/app/components/workflow/nodes/iteration-start/__tests__/index.spec.tsx@@ -6,7 +6,7 @@ import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__import { BlockEnum } from '@/app/components/workflow/types'import { useAvailableBlocks } from '../../../hooks/use-available-blocks'import { useNodesInteractions } from '../../../hooks/use-nodes-interactions'-import { useIsChatMode, useNodesReadOnly } from '../../../hooks/use-workflow'+import { useNodesReadOnly } from '../../../hooks/use-workflow'import IterationStartNode, { IterationStartNodeDumb } from '../index'vi.mock('../../../hooks/use-available-blocks', async (importOriginal) => {@@ -33,14 +33,13 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,useNodesReadOnly: vi.fn(),- useIsChatMode: vi.fn(),}})const mockUseAvailableBlocks = vi.mocked(useAvailableBlocks)const mockUseNodesInteractions = vi.mocked(useNodesInteractions)const mockUseNodesReadOnly = vi.mocked(useNodesReadOnly)-const mockUseIsChatMode = vi.mocked(useIsChatMode)+const mockUseIsChatMode = vi.hoisted(() => vi.fn())const createAvailableBlocksResult = (): ReturnType<typeof useAvailableBlocks> => ({getAvailableBlocks: vi.fn(() => ({@@ -106,3 +105,10 @@ describe('IterationStartNode', () => {})})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/nodes/iteration/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/iteration/__tests__/use-config.spec.tsindex 564ed804d75..711bda51f3e 100644--- a/web/app/components/workflow/nodes/iteration/__tests__/use-config.spec.ts+++ b/web/app/components/workflow/nodes/iteration/__tests__/use-config.spec.ts@@ -28,7 +28,7 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,useNodesReadOnly: () => mockUseNodesReadOnly(),- useIsChatMode: () => mockUseIsChatMode(),+useWorkflow: () => mockUseWorkflow(),}})@@ -264,3 +264,10 @@ describe('iteration/use-config', () => {expect(mockDeleteNodeInspectorVars).toHaveBeenCalledWith('iteration-node')})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/nodes/iteration/use-config.ts b/web/app/components/workflow/nodes/iteration/use-config.tsindex 4aa1d471c26..f2198127f5b 100644--- a/web/app/components/workflow/nodes/iteration/use-config.ts+++ b/web/app/components/workflow/nodes/iteration/use-config.ts@@ -3,7 +3,9 @@ import type { IterationNodeType } from './types'import type { VarKindType } from '@/app/components/workflow/nodes/_base/types'import { isEqual } from 'es-toolkit/predicate'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import {useAllBuiltInTools,useAllCustomTools,@@ -11,7 +13,7 @@ import {useAllWorkflowTools,} from '@/service/use-tools'import useInspectVarsCrud from '../../hooks/use-inspect-vars-crud'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'+import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'import { useStore } from '../../store'import { VarType } from '../../types'import { toNodeOutputVars } from '../_base/components/variable/utils'@@ -25,7 +27,7 @@ type SelectOption = {const useConfig = (id: string, payload: IterationNodeType) => {const { deleteNodeInspectorVars } = useInspectVarsCrud()const { nodesReadOnly: readOnly } = useNodesReadOnly()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const { inputs, setInputs } = useNodeCrud<IterationNodeType>(id, payload)@@ -70,7 +72,7 @@ const useConfig = (id: string, payload: IterationNodeType) => {}const childrenNodeVars = toNodeOutputVars(iterationChildrenNodes,- isChatMode,+ isChatflow,undefined,[],[],diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/use-config.spec.tsindex 3f97777611b..fc992727f04 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/use-config.spec.ts+++ b/web/app/components/workflow/nodes/knowledge-retrieval/__tests__/use-config.spec.ts@@ -14,8 +14,8 @@ import { BlockEnum, VarType } from '@/app/components/workflow/types'import { DATASET_DEFAULT } from '@/config'import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'import { fetchDatasets } from '@/service/datasets'-import { AppModeEnum, RETRIEVE_METHOD, RETRIEVE_TYPE } from '@/types/app'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../../hooks/use-workflow'+import { RETRIEVE_METHOD, RETRIEVE_TYPE } from '@/types/app'+import { useNodesReadOnly, useWorkflow } from '../../../hooks/use-workflow'import {ComparisonOperator,LogicalOperator,@@ -39,7 +39,7 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,useNodesReadOnly: vi.fn(),- useIsChatMode: vi.fn(),+useWorkflow: vi.fn(),}})@@ -68,7 +68,7 @@ vi.mock('@/service/datasets', () => ({}))const mockUseNodesReadOnly = vi.mocked(useNodesReadOnly)-const mockUseIsChatMode = vi.mocked(useIsChatMode)+const mockUseIsChatMode = vi.hoisted(() => vi.fn())const mockUseWorkflow = vi.mocked(useWorkflow)const mockUseModelListAndDefaultModelAndCurrentProviderAndModel = vi.mocked(useModelListAndDefaultModelAndCurrentProviderAndModel,@@ -222,7 +222,7 @@ describe('knowledge-retrieval/use-config', () => {currentModel: {model: 'rerank-model',model_properties: {- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,},},} as unknown as ReturnType<typeof useModelListAndDefaultModelAndCurrentProviderAndModel>@@ -235,7 +235,7 @@ describe('knowledge-retrieval/use-config', () => {currentModel: {model: 'gpt-4o-mini',model_properties: {- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,},},} as unknown as ReturnType<typeof useModelListAndDefaultModelAndCurrentProviderAndModel>@@ -371,7 +371,7 @@ describe('knowledge-retrieval/use-config', () => {result.current.handleModelChanged({provider: 'anthropic',modelId: 'claude-sonnet',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})result.current.handleCompletionParamsChange({ temperature: 0.2 })result.current.handleCompletionParamsChange({ temperature: 0.2 })@@ -504,7 +504,7 @@ describe('knowledge-retrieval/use-config', () => {result.current.handleMetadataModelChange({provider: 'openai',modelId: 'gpt-4.1-mini',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})result.current.handleMetadataCompletionParamsChange({ top_p: 0.3 })})@@ -517,7 +517,7 @@ describe('knowledge-retrieval/use-config', () => {expect(result.current.inputs.metadata_model_config).toEqual({provider: 'openai',name: 'gpt-4.1-mini',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { top_p: 0.3 },})})@@ -529,3 +529,10 @@ describe('knowledge-retrieval/use-config', () => {expect(result.current.filterFileVar({ type: VarType.string } as never)).toBe(false)})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/hooks/__tests__/use-knowledge-metadata-config.spec.ts b/web/app/components/workflow/nodes/knowledge-retrieval/hooks/__tests__/use-knowledge-metadata-config.spec.tsindex 5fa22f43148..d4920ed834d 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/hooks/__tests__/use-knowledge-metadata-config.spec.ts+++ b/web/app/components/workflow/nodes/knowledge-retrieval/hooks/__tests__/use-knowledge-metadata-config.spec.ts@@ -3,7 +3,6 @@ import type { KnowledgeRetrievalNodeType, MetadataFilteringCondition } from '../import { act, renderHook } from '@testing-library/react'import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'import { BlockEnum, VarType } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import {ComparisonOperator,LogicalOperator,@@ -132,7 +131,7 @@ describe('use-knowledge-metadata-config', () => {result.current.handleMetadataModelChange({provider: 'openai',modelId: 'gpt-4.1-mini',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})result.current.handleMetadataCompletionParamsChange({ top_p: 0.3 })})@@ -142,7 +141,7 @@ describe('use-knowledge-metadata-config', () => {metadata_model_config: {provider: 'openai',name: 'gpt-4.1-mini',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { top_p: 0.3 },},}),@@ -202,7 +201,7 @@ describe('use-knowledge-metadata-config', () => {metadata_model_config: {provider: 'openai',name: 'gpt-4.1-mini',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.7 },},})@@ -247,7 +246,7 @@ describe('use-knowledge-metadata-config', () => {metadata_model_config: {provider: 'openai',name: 'gpt-4.1-mini',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.9 },},})@@ -274,7 +273,7 @@ describe('use-knowledge-metadata-config', () => {expect(inputRef.current.metadata_model_config).toEqual({provider: 'anthropic',name: 'claude-sonnet',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.9 },})})diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/hooks/__tests__/use-knowledge-model-config.spec.ts b/web/app/components/workflow/nodes/knowledge-retrieval/hooks/__tests__/use-knowledge-model-config.spec.tsindex 1bb107d9b21..abb34e81dc8 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/hooks/__tests__/use-knowledge-model-config.spec.ts+++ b/web/app/components/workflow/nodes/knowledge-retrieval/hooks/__tests__/use-knowledge-model-config.spec.ts@@ -5,7 +5,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'import { BlockEnum } from '@/app/components/workflow/types'import { DATASET_DEFAULT } from '@/config'import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'-import { AppModeEnum, RETRIEVE_METHOD, RETRIEVE_TYPE } from '@/types/app'+import { RETRIEVE_METHOD, RETRIEVE_TYPE } from '@/types/app'import useKnowledgeModelConfig from '../use-knowledge-model-config'const createDataset = (overrides: Partial<DataSet> = {}): DataSet => ({@@ -169,7 +169,7 @@ describe('use-knowledge-model-config', () => {model: {provider: 'anthropic',name: 'claude-sonnet',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},},@@ -221,7 +221,7 @@ describe('use-knowledge-model-config', () => {currentModel: {model: 'gpt-4o-mini',model_properties: {- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,},},fallbackRerankModel,@@ -236,7 +236,7 @@ describe('use-knowledge-model-config', () => {model: {provider: 'openai',name: 'gpt-4o-mini',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},},@@ -308,7 +308,7 @@ describe('use-knowledge-model-config', () => {model: {provider: 'openai',name: 'gpt-4o-mini',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},},@@ -322,7 +322,7 @@ describe('use-knowledge-model-config', () => {model: {provider: 'openai',name: 'gpt-4o-mini',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},},@@ -348,7 +348,7 @@ describe('use-knowledge-model-config', () => {currentModel: {model: 'gpt-4o-mini',model_properties: {- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,},},fallbackRerankModel,diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/hooks/use-knowledge-metadata-config.ts b/web/app/components/workflow/nodes/knowledge-retrieval/hooks/use-knowledge-metadata-config.tsindex 84b087cf9f5..c0db631fce4 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/hooks/use-knowledge-metadata-config.ts+++ b/web/app/components/workflow/nodes/knowledge-retrieval/hooks/use-knowledge-metadata-config.ts@@ -13,7 +13,6 @@ import { useCallback } from 'react'import { v4 as uuid4 } from 'uuid'import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'import { VarType } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import { ComparisonOperator, LogicalOperator, MetadataFilteringVariableType } from '../types'type Params = {@@ -115,7 +114,7 @@ const useKnowledgeMetadataConfig = ({ id, inputRef, setInputs }: Params) => {draft.metadata_model_config = {provider: model.provider,name: model.modelId,- mode: model.mode || AppModeEnum.CHAT,+ mode: model.mode || 'chat',completion_params: draft.metadata_model_config?.completion_params || { temperature: 0.7 },}})diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/hooks/use-knowledge-model-config.ts b/web/app/components/workflow/nodes/knowledge-retrieval/hooks/use-knowledge-model-config.tsindex 343396a5530..46ec719dffa 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/hooks/use-knowledge-model-config.ts+++ b/web/app/components/workflow/nodes/knowledge-retrieval/hooks/use-knowledge-model-config.ts@@ -6,7 +6,7 @@ import { isEqual } from 'es-toolkit/predicate'import { produce } from 'immer'import { useCallback, useEffect } from 'react'import { DATASET_DEFAULT } from '@/config'-import { AppModeEnum, RETRIEVE_TYPE } from '@/types/app'+import { RETRIEVE_TYPE } from '@/types/app'import { getMultipleRetrievalConfig } from '../utils'type ModelIdentity = {@@ -67,7 +67,7 @@ const useKnowledgeModelConfig = ({const draftModel = draft.single_retrieval_config!.modeldraftModel.provider = model.providerdraftModel.name = model.modelId- draftModel.mode = model.mode || AppModeEnum.CHAT+ draftModel.mode = model.mode || 'chat'})setInputs(nextInputs)},@@ -120,7 +120,7 @@ const useKnowledgeModelConfig = ({draft.single_retrieval_config = createSingleRetrievalConfig({provider: currentProvider.provider,name: currentModel.model,- mode: currentModel.model_properties?.mode || AppModeEnum.CHAT,+ mode: currentModel.model_properties?.mode || 'chat',completion_params: {},})}@@ -168,7 +168,7 @@ const useKnowledgeModelConfig = ({draft.single_retrieval_config = createSingleRetrievalConfig({provider: currentProvider?.provider || '',name: currentModel?.model || '',- mode: currentModel?.model_properties?.mode || AppModeEnum.CHAT,+ mode: currentModel?.model_properties?.mode || 'chat',completion_params: {},})}diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/use-config.ts b/web/app/components/workflow/nodes/knowledge-retrieval/use-config.tsindex c3d824e9000..37c14190938 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/use-config.ts+++ b/web/app/components/workflow/nodes/knowledge-retrieval/use-config.ts@@ -1,15 +1,17 @@import type { ValueSelector } from '../../types'import type { KnowledgeRetrievalNodeType } from './types'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useEffect, useMemo } from 'react'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import {useCurrentProviderAndModel,useModelListAndDefaultModelAndCurrentProviderAndModel,} from '@/app/components/header/account-setting/model-provider-page/hooks'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'import { useDatasetsDetailStore } from '../../datasets-detail-store/store'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'+import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'import { BlockEnum } from '../../types'import useKnowledgeDatasetSelection from './hooks/use-knowledge-dataset-selection'import useKnowledgeInputManager from './hooks/use-knowledge-input-manager'@@ -18,7 +20,7 @@ import useKnowledgeModelConfig from './hooks/use-knowledge-model-config'const useConfig = (id: string, payload: KnowledgeRetrievalNodeType) => {const { nodesReadOnly: readOnly } = useNodesReadOnly()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const { getBeforeNodesInSameBranch } = useWorkflow()const startNode = getBeforeNodesInSameBranch(id).find((node) => node.data.type === BlockEnum.Start,@@ -93,7 +95,7 @@ const useConfig = (id: string, payload: KnowledgeRetrievalNodeType) => {useEffect(() => {const currentInputs = inputRef.currentlet nextQueryVariableSelector: ValueSelector = currentInputs.query_variable_selector- if (isChatMode && currentInputs.query_variable_selector.length === 0 && startNodeId)+ if (isChatflow && currentInputs.query_variable_selector.length === 0 && startNodeId)nextQueryVariableSelector = [startNodeId, 'sys.query']setInputs(@@ -101,7 +103,7 @@ const useConfig = (id: string, payload: KnowledgeRetrievalNodeType) => {draft.query_variable_selector = nextQueryVariableSelector}),)- }, [inputRef, isChatMode, setInputs, startNodeId])+ }, [inputRef, isChatflow, setInputs, startNodeId])const metadataConfig = useKnowledgeMetadataConfig({id,diff --git a/web/app/components/workflow/nodes/list-operator/__tests__/use-config.spec.tsx b/web/app/components/workflow/nodes/list-operator/__tests__/use-config.spec.tsxindex 3c96c472cd6..3e3e61da60f 100644--- a/web/app/components/workflow/nodes/list-operator/__tests__/use-config.spec.tsx+++ b/web/app/components/workflow/nodes/list-operator/__tests__/use-config.spec.tsx@@ -1,5 +1,5 @@import type { ListFilterNodeType } from '../types'-import { renderHook } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum, VarType } from '@/app/components/workflow/types'import { createNodeCrudModuleMock } from '../../__tests__/use-config-test-utils'import { ComparisonOperator } from '../../if-else/types'@@ -32,7 +32,7 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,useNodesReadOnly: () => ({ nodesReadOnly: mockNodesReadOnly }),- useIsChatMode: () => mockIsChatMode,+useWorkflow: () => ({getBeforeNodesInSameBranch: (...args: unknown[]) => mockGetBeforeNodesInSameBranch(...args),}),@@ -106,7 +106,9 @@ describe('list-operator/use-config', () => {})it('should expose derived state and update inputs through the helper pipeline', () => {- const { result } = renderHook(() => useConfig('list-node', createPayload()))+ const { result } = renderHook(() => useConfig('list-node', createPayload()), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })expect(result.current.readOnly).toBe(false)expect(result.current.varType).toBe(VarType.arrayFile)@@ -207,24 +209,28 @@ describe('list-operator/use-config', () => {{ id: 'loop-parent' },])- const { result: iterationResult } = renderHook(() =>- useConfig(- 'list-node',- createPayload({- isInIteration: true,- variable: ['iteration', 'files'],- }),- ),+ const { result: iterationResult } = renderHook(+ () =>+ useConfig(+ 'list-node',+ createPayload({+ isInIteration: true,+ variable: ['iteration', 'files'],+ }),+ ),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)- const { result: loopResult } = renderHook(() =>- useConfig(- 'loop-node',- createPayload({- isInLoop: true,- isInIteration: false,- variable: ['loop', 'names'],- }),- ),+ const { result: loopResult } = renderHook(+ () =>+ useConfig(+ 'loop-node',+ createPayload({+ isInLoop: true,+ isInIteration: false,+ variable: ['loop', 'names'],+ }),+ ),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)iterationResult.current.handleVarChanges(['iteration', 'files'])@@ -234,7 +240,7 @@ describe('list-operator/use-config', () => {expect(mockGetCurrentVariableType).toHaveBeenCalledWith(expect.objectContaining({parentNode: expect.objectContaining({ id: 'iteration-parent' }),- isChatMode: true,+ isChatflow: true,}),)expect(mockGetCurrentVariableType).toHaveBeenCalledWith(@@ -253,3 +259,10 @@ describe('list-operator/use-config', () => {)})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockIsChatMode) }+})diff --git a/web/app/components/workflow/nodes/list-operator/use-config.ts b/web/app/components/workflow/nodes/list-operator/use-config.tsindex f76bc047de8..f3353ce7102 100644--- a/web/app/components/workflow/nodes/list-operator/use-config.ts+++ b/web/app/components/workflow/nodes/list-operator/use-config.ts@@ -1,9 +1,11 @@import type { ValueSelector, Var } from '../../types'import type { Condition, Limit, ListFilterNodeType, OrderBy } from './types'+import { useAtomValue } from 'jotai'import { useCallback, useMemo } from 'react'import { useStoreApi } from 'reactflow'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'+import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'import { useWorkflowVariables } from '../../hooks/use-workflow-variables'import {canFilterVariable,@@ -23,7 +25,7 @@ import {const useConfig = (id: string, payload: ListFilterNodeType) => {const { nodesReadOnly: readOnly } = useNodesReadOnly()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const store = useStoreApi()const { getBeforeNodesInSameBranch } = useWorkflow()@@ -50,7 +52,7 @@ const useConfig = (id: string, payload: ListFilterNodeType) => {parentNode: isInIteration ? iterationNode : loopNode,valueSelector: variable || inputs.variable || [],availableNodes,- isChatMode,+ isChatflow,isConstant: false,})const itemVarType = getItemVarType(varType)@@ -60,7 +62,7 @@ const useConfig = (id: string, payload: ListFilterNodeType) => {availableNodes,getCurrentVariableType,inputs.variable,- isChatMode,+ isChatflow,isInIteration,iterationNode,loopNode,diff --git a/web/app/components/workflow/nodes/llm/__tests__/default.spec.ts b/web/app/components/workflow/nodes/llm/__tests__/default.spec.tsindex 66d681bb02a..493115a6b1c 100644--- a/web/app/components/workflow/nodes/llm/__tests__/default.spec.ts+++ b/web/app/components/workflow/nodes/llm/__tests__/default.spec.ts@@ -1,7 +1,5 @@import type { LLMNodeType } from '../types'import { withSelectorKey } from '@/test/i18n-mock'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import { EditionType, PromptRole } from '../../../types'import nodeDefault from '../default'@@ -13,7 +11,7 @@ const createPayload = (overrides: Partial<LLMNodeType> = {}): LLMNodeType =>model: {...nodeDefault.defaultValue.model,provider: 'langgenius/openai/gpt-4.1',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,},prompt_template: [{@@ -33,7 +31,7 @@ describe('llm default node validation', () => {...nodeDefault.defaultValue.model,provider: '',name: 'gpt-4.1',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {temperature: 0.7,},@@ -66,7 +64,7 @@ describe('llm default node validation', () => {value: {provider: 'langgenius/anthropic/anthropic',name: 'claude-sonnet',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,},description: '',},@@ -113,7 +111,7 @@ describe('llm default node validation', () => {value: {provider: 'langgenius/anthropic/anthropic',name: 'claude-sonnet',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,},description: '',},@@ -137,7 +135,7 @@ describe('llm default node validation', () => {},}),t,- { flowType: FlowType.appFlow },+ { resourceKind: 'app' },)expect(result.isValid).toBe(false)@@ -156,7 +154,7 @@ describe('llm default node validation', () => {},}),t,- { flowType: FlowType.snippet },+ { resourceKind: 'snippet' },)expect(result.isValid).toBe(true)diff --git a/web/app/components/workflow/nodes/llm/__tests__/node.spec.tsx b/web/app/components/workflow/nodes/llm/__tests__/node.spec.tsxindex 9d44b155feb..3f195f154c0 100644--- a/web/app/components/workflow/nodes/llm/__tests__/node.spec.tsx+++ b/web/app/components/workflow/nodes/llm/__tests__/node.spec.tsx@@ -2,7 +2,6 @@ import type { LLMNodeType } from '../types'import { render, screen } from '@testing-library/react'import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'import { BlockEnum } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import Node from '../node'vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({@@ -24,7 +23,7 @@ const createData = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},} as LLMNodeType['model'],prompt_template: [],@@ -60,7 +59,7 @@ describe('llm/node', () => {model: {provider: '',name: '',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},} as LLMNodeType['model'],})}@@ -75,7 +74,7 @@ describe('llm/node', () => {model: {provider: 'anthropic',name: 'claude-sonnet',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},model_selector: ['env', 'for_summarize'],diff --git a/web/app/components/workflow/nodes/llm/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/llm/__tests__/panel.spec.tsxindex 70c6e011e12..398ef53545e 100644--- a/web/app/components/workflow/nodes/llm/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/llm/__tests__/panel.spec.tsx@@ -1,6 +1,7 @@import type { ModelProviderSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen'import type { LLMNodeType } from '../types'import type { ModelParameterModalProps } from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type { PanelProps } from '@/types/workflow'import { QueryClientProvider } from '@tanstack/react-query'import { screen, waitFor } from '@testing-library/react'@@ -8,8 +9,6 @@ import userEvent from '@testing-library/user-event'import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'import { consoleQuery } from '@/service/console'import { createConsoleQueryWrapper } from '@/test/console/query-data'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'import { BlockEnum } from '../../../types'import Panel from '../panel'@@ -99,7 +98,7 @@ const baseNodeData: LLMNodeType = {model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},prompt_template: [],@@ -121,7 +120,7 @@ const buildUseConfigResult = (overrides?: Partial<MockUseConfigReturn>) => ({environmentVariables: [],isEnvironmentModelSource: false,isChatModel: true,- isChatMode: true,+ isChatflow: true,isCompletionModel: false,shouldShowContextTip: false,isVisionModel: false,@@ -163,7 +162,7 @@ const renderPanelElement = (data?: Partial<LLMNodeType>) => (</QueryClientProvider>)-const renderPanel = (data?: Partial<LLMNodeType>, flowType?: FlowType) => {+const renderPanel = (data?: Partial<LLMNodeType>, resourceKind?: EditorResource['kind']) => {panelQueryClient = createConsoleQueryWrapper().queryClientpanelQueryClient.setQueryData(consoleQuery.workspaces.current.modelProviders.summary.get.queryKey(),@@ -178,9 +177,12 @@ const renderPanel = (data?: Partial<LLMNodeType>, flowType?: FlowType) => {},)return renderWorkflowFlowComponent(renderPanelElement(data), {- hooksStoreProps: flowType- ? { configsMap: { flowId: 'test-flow', flowType, fileSettings: {} } }- : {},+ resource:+ resourceKind === 'snippet'+ ? { kind: 'snippet', snippetId: 'test-snippet' }+ : resourceKind === 'knowledge-pipeline'+ ? { kind: 'knowledge-pipeline', pipelineId: 'test-pipeline' }+ : { kind: 'app', appId: 'test-app', mode: 'workflow' },})}@@ -244,7 +246,7 @@ describe('LLM Panel', () => {})it('does not offer an environment model source in snippet flows', () => {- renderPanel(undefined, FlowType.snippet)+ renderPanel(undefined, 'snippet')expect(screen.queryByRole('radio', { name: 'workflow.nodes.common.typeSwitch.variable' }),@@ -265,7 +267,7 @@ describe('LLM Panel', () => {}),)- renderPanel({ model_selector: ['env', 'shared_model'] }, FlowType.snippet)+ renderPanel({ model_selector: ['env', 'shared_model'] }, 'snippet')await user.click(screen.getByRole('radio', { name: 'workflow.nodes.common.typeSwitch.input' }))expect(handleModelSourceChange).toHaveBeenCalledWith(false)@@ -289,7 +291,7 @@ describe('LLM Panel', () => {value: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,},description: '',},@@ -345,7 +347,7 @@ describe('LLM Panel', () => {id: 'env-llm',name: 'for_summarize',value_type: 'llm',- value: { provider: 'openai', name: 'gpt-4o', mode: AppModeEnum.CHAT },+ value: { provider: 'openai', name: 'gpt-4o', mode: 'chat' as const },description: '',},],diff --git a/web/app/components/workflow/nodes/llm/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/llm/__tests__/use-config.spec.tsindex d7d3080f045..0bba3420aeb 100644--- a/web/app/components/workflow/nodes/llm/__tests__/use-config.spec.ts+++ b/web/app/components/workflow/nodes/llm/__tests__/use-config.spec.ts@@ -5,10 +5,10 @@ import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/comimport useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'import { useStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'-import { AppModeEnum, Resolution } from '@/types/app'+import { Resolution } from '@/types/app'import useConfigVision from '../../../hooks/use-config-vision'import useInspectVarsCrud from '../../../hooks/use-inspect-vars-crud'-import { useIsChatMode, useNodesReadOnly } from '../../../hooks/use-workflow'+import { useNodesReadOnly } from '../../../hooks/use-workflow'import useAvailableVarList from '../../_base/hooks/use-available-var-list'import useLLMInputManager from '../hooks/use-llm-input-manager'import useLLMPromptConfig from '../hooks/use-llm-prompt-config'@@ -21,7 +21,6 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,useNodesReadOnly: vi.fn(),- useIsChatMode: vi.fn(),}})@@ -69,7 +68,7 @@ vi.mock('../hooks/use-llm-structured-output-config', () => ({}))const mockUseNodesReadOnly = vi.mocked(useNodesReadOnly)-const mockUseIsChatMode = vi.mocked(useIsChatMode)+const mockUseIsChatMode = vi.hoisted(() => vi.fn())const mockUseNodeCrud = vi.mocked(useNodeCrud)const mockUseInspectVarsCrud = vi.mocked(useInspectVarsCrud)const mockUseModelListAndDefaultModelAndCurrentProviderAndModel = vi.mocked(@@ -89,7 +88,7 @@ const createPayload = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {temperature: 0.7,},@@ -216,7 +215,7 @@ describe('llm/use-config', () => {const { result } = renderHook(() => useConfig('llm-node', inputRef.current))expect(result.current.readOnly).toBe(false)- expect(result.current.isChatMode).toBe(true)+ expect(result.current.isChatflow).toBe(true)expect(result.current.isChatModel).toBe(true)expect(result.current.isCompletionModel).toBe(false)expect(result.current.availableVars).toEqual([@@ -251,7 +250,7 @@ describe('llm/use-config', () => {{provider: 'openai',modelId: 'gpt-4.1',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,},{ temperature: 0.3 },)@@ -283,7 +282,7 @@ describe('llm/use-config', () => {model: expect.objectContaining({provider: 'openai',name: 'gpt-4.1',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.3 },}),}),@@ -296,7 +295,7 @@ describe('llm/use-config', () => {model: {provider: '',name: '',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,completion_params: {},},})@@ -311,7 +310,7 @@ describe('llm/use-config', () => {currentModel: {model: 'claude-sonnet',model_properties: {- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,},},} as unknown as ReturnType<typeof useModelListAndDefaultModelAndCurrentProviderAndModel>)@@ -331,7 +330,7 @@ describe('llm/use-config', () => {model: expect.objectContaining({provider: 'anthropic',name: 'claude-sonnet',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,}),}),)@@ -345,7 +344,7 @@ describe('llm/use-config', () => {model: {provider: 'cached-provider',name: 'cached-model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.2 },},})@@ -363,7 +362,7 @@ describe('llm/use-config', () => {value: {provider: 'shared-provider',name: 'shared-model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.8 },},description: '',@@ -378,7 +377,7 @@ describe('llm/use-config', () => {expect(result.current.model).toEqual({provider: 'shared-provider',name: 'shared-model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.8 },})expect(result.current.isEnvironmentModelSource).toBe(true)@@ -404,7 +403,7 @@ describe('llm/use-config', () => {value: {provider: 'shared-provider',name: 'shared-completion-model',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,completion_params: { top_p: 0.9 },},description: '',@@ -439,7 +438,7 @@ describe('llm/use-config', () => {model: expect.objectContaining({provider: 'shared-provider',name: 'shared-completion-model',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,completion_params: { top_p: 0.9 },}),}),@@ -457,7 +456,7 @@ describe('llm/use-config', () => {model: {provider: 'cached-provider',name: 'cached-model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.4 },},})@@ -475,7 +474,7 @@ describe('llm/use-config', () => {value: {provider: 'latest-provider',name: 'latest-model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.8 },},description: '',@@ -496,7 +495,7 @@ describe('llm/use-config', () => {model: {provider: 'latest-provider',name: 'latest-model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.8 },},model_selector: undefined,@@ -506,3 +505,10 @@ describe('llm/use-config', () => {expect(updatedInputs).toHaveProperty('model_selector', undefined)})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/nodes/llm/__tests__/use-single-run-form-params.spec.ts b/web/app/components/workflow/nodes/llm/__tests__/use-single-run-form-params.spec.tsindex 38c02d712f2..da3c5945ff2 100644--- a/web/app/components/workflow/nodes/llm/__tests__/use-single-run-form-params.spec.ts+++ b/web/app/components/workflow/nodes/llm/__tests__/use-single-run-form-params.spec.ts@@ -1,6 +1,7 @@import type { LLMNodeType } from '../types'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type { InputVar, Variable } from '@/app/components/workflow/types'-import { renderHook } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import {BlockEnum,EditionType,@@ -8,8 +9,6 @@ import {PromptRole,VarType,} from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import useConfigVision from '../../../hooks/use-config-vision'import useAvailableVarList from '../../_base/hooks/use-available-var-list'import useNodeCrud from '../../_base/hooks/use-node-crud'@@ -35,19 +34,20 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => true,}})const mockFlowType = vi.hoisted(() => ({- value: undefined as FlowType | undefined,+ value: undefined as EditorResource['kind'] | undefined,}))vi.mock('@/app/components/workflow/hooks-store/store', () => ({- useHooksStore: (selector: (state: { configsMap?: { flowType?: FlowType } }) => unknown) =>+ useHooksStore: (+ selector: (state: { configsMap?: { resourceKind?: EditorResource['kind'] } }) => unknown,+ ) =>selector({configsMap: {- flowType: mockFlowType.value,+ resourceKind: mockFlowType.value,},}),}))@@ -63,7 +63,7 @@ const createData = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},} as LLMNodeType['model'],prompt_template: [@@ -117,7 +117,6 @@ describe('llm/use-single-run-form-params', () => {})it('filters system variables from single-run inputs in snippet flows', () => {- mockFlowType.value = FlowType.snippetconst getInputVars = vi.fn(() => [createInputVar('#start.query#'),createInputVar('#sys.query#'),@@ -128,33 +127,35 @@ describe('llm/use-single-run-form-params', () => {createInputVar('#start.extra#'),])- const { result } = renderHook(() =>- useSingleRunFormParams({- id: 'llm-node',- payload: createData({- prompt_template: [- {- edition_type: EditionType.jinja2,- role: PromptRole.user,- text: '{{ query }}',- },- ],- prompt_config: {- jinja2_variables: [+ const { result } = renderHook(+ () =>+ useSingleRunFormParams({+ id: 'llm-node',+ payload: createData({+ prompt_template: [{- variable: 'extra',- value_selector: ['start', 'extra'],- value_type: VarType.string,+ edition_type: EditionType.jinja2,+ role: PromptRole.user,+ text: '{{ query }}',},],- },+ prompt_config: {+ jinja2_variables: [+ {+ variable: 'extra',+ value_selector: ['start', 'extra'],+ value_type: VarType.string,+ },+ ],+ },+ }),+ runInputData: {},+ runInputDataRef: { current: {} },+ getInputVars,+ setRunInputData: vi.fn(),+ toVarInputs,}),- runInputData: {},- runInputDataRef: { current: {} },- getInputVars,- setRunInputData: vi.fn(),- toVarInputs,- }),+ { resource: { kind: 'snippet', snippetId: 'snippet-1' } },)expect(result.current.forms[0]!.inputs).toEqual([@@ -167,3 +168,10 @@ describe('llm/use-single-run-form-params', () => {])})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => true) }+})diff --git a/web/app/components/workflow/nodes/llm/__tests__/utils.spec.ts b/web/app/components/workflow/nodes/llm/__tests__/utils.spec.tsindex 89bea169235..23797383438 100644--- a/web/app/components/workflow/nodes/llm/__tests__/utils.spec.ts+++ b/web/app/components/workflow/nodes/llm/__tests__/utils.spec.ts@@ -3,7 +3,6 @@ import type {ModelConfig,ValueSelector,} from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import {getLLMEnvironmentModel,getLLMModelIssue,@@ -62,7 +61,7 @@ describe('llm utils', () => {const model: ModelConfig = {provider: 'direct-provider',name: 'direct-model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.3 },}const environmentVariables: EnvironmentVariable[] = [@@ -73,7 +72,7 @@ describe('llm utils', () => {value: {provider: 'shared-provider',name: 'shared-model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.8 },},description: '',@@ -84,7 +83,7 @@ describe('llm utils', () => {expect(resolveLLMNodeModel(model, ['env', 'for_summarize'], environmentVariables)).toEqual({provider: 'shared-provider',name: 'shared-model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.8 },})})@@ -96,7 +95,7 @@ describe('llm utils', () => {value: {provider: 'shared-provider',name: 'shared-model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,},},] as EnvironmentVariable[]@@ -106,7 +105,7 @@ describe('llm utils', () => {).toEqual({provider: 'shared-provider',name: 'shared-model',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: { temperature: 0.3 },})})@@ -118,7 +117,7 @@ describe('llm utils', () => {value: {provider: 'shared-provider',name: 'shared-completion-model',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,completion_params: { temperature: 0.8 },},},@@ -127,7 +126,7 @@ describe('llm utils', () => {expect(getLLMEnvironmentModel(['env', 'for_summarize'], completionModelVariables)).toEqual({provider: 'shared-provider',name: 'shared-completion-model',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,completion_params: { temperature: 0.8 },})})@@ -139,7 +138,7 @@ describe('llm utils', () => {value: {provider: 'shared-provider',name: 'shared-model',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,},},] as EnvironmentVariable[]diff --git a/web/app/components/workflow/nodes/llm/components/__tests__/config-prompt.spec.tsx b/web/app/components/workflow/nodes/llm/components/__tests__/config-prompt.spec.tsxindex 16532c96e5d..cff77549493 100644--- a/web/app/components/workflow/nodes/llm/components/__tests__/config-prompt.spec.tsx+++ b/web/app/components/workflow/nodes/llm/components/__tests__/config-prompt.spec.tsx@@ -94,7 +94,7 @@ function RemoteModelChangeFixture({ onChange }: { onChange: (inputs: LLMNodeTypeinputRef: inputManager.inputRef,setInputs: inputManager.setInputs,isChatModel,- isChatMode: true,+ isChatflow: true,})return (diff --git a/web/app/components/workflow/nodes/llm/components/__tests__/panel-memory-section.spec.tsx b/web/app/components/workflow/nodes/llm/components/__tests__/panel-memory-section.spec.tsxindex 347d11a4b88..e053c3a2f5d 100644--- a/web/app/components/workflow/nodes/llm/components/__tests__/panel-memory-section.spec.tsx+++ b/web/app/components/workflow/nodes/llm/components/__tests__/panel-memory-section.spec.tsx@@ -1,8 +1,6 @@import type { LLMNodeType } from '../../types'import type { Memory, Node, NodeOutPutVar } from '@/app/components/workflow/types'import { render, screen } from '@testing-library/react'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import PanelMemorySection from '../panel-memory-section'const mockEditor = vi.hoisted(() => vi.fn())@@ -46,7 +44,7 @@ const createInputs = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},} as LLMNodeType['model'],prompt_template: [],@@ -69,7 +67,7 @@ const createInputs = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({const baseProps = {readOnly: false,- isChatMode: true,+ isChatflow: true,isChatModel: true,isCompletionModel: false,inputs: createInputs(),@@ -128,7 +126,7 @@ describe('llm/panel-memory-section', () => {render(<PanelMemorySection{...baseProps}- flowType={FlowType.snippet}+ resourceKind={'snippet'}inputs={createInputs({memory: {window: {@@ -146,7 +144,7 @@ describe('llm/panel-memory-section', () => {})it('does not default snippet memory prompts to system variables', () => {- render(<PanelMemorySection {...baseProps} flowType={FlowType.snippet} />)+ render(<PanelMemorySection {...baseProps} resourceKind={'snippet'} />)expect(screen.getByTestId('editor')).toHaveTextContent('')expect(mockEditor).toHaveBeenCalledWith(@@ -167,7 +165,7 @@ describe('llm/panel-memory-section', () => {render(<PanelMemorySection{...baseProps}- isChatMode={false}+ isChatflow={false}isChatModel={false}isCompletionModel={true}/>,diff --git a/web/app/components/workflow/nodes/llm/components/__tests__/panel-output-section.spec.tsx b/web/app/components/workflow/nodes/llm/components/__tests__/panel-output-section.spec.tsxindex 7ddd1aec12b..2e9c6c92d6b 100644--- a/web/app/components/workflow/nodes/llm/components/__tests__/panel-output-section.spec.tsx+++ b/web/app/components/workflow/nodes/llm/components/__tests__/panel-output-section.spec.tsx@@ -2,7 +2,6 @@ import type { ReactNode } from 'react'import type { LLMNodeType, StructuredOutput } from '../../types'import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { AppModeEnum } from '@/types/app'import { Type } from '../../types'import PanelOutputSection from '../panel-output-section'@@ -51,7 +50,7 @@ const createInputs = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},} as LLMNodeType['model'],prompt_template: [],diff --git a/web/app/components/workflow/nodes/llm/components/__tests__/prompt-generator-btn.spec.tsx b/web/app/components/workflow/nodes/llm/components/__tests__/prompt-generator-btn.spec.tsxindex b91a0c1c835..feb6e3dc647 100644--- a/web/app/components/workflow/nodes/llm/components/__tests__/prompt-generator-btn.spec.tsx+++ b/web/app/components/workflow/nodes/llm/components/__tests__/prompt-generator-btn.spec.tsx@@ -1,5 +1,6 @@-import { render, screen } from '@testing-library/react'+import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import PromptGeneratorBtn from '../prompt-generator-btn'vi.mock('@/app/components/app/configuration/config/automatic/get-automatic-res', () => ({@@ -14,7 +15,9 @@ vi.mock('@/app/components/workflow/hooks-store', () => ({describe('PromptGeneratorBtn', () => {it('should open the prompt generator from the named action', async () => {const user = userEvent.setup()- render(<PromptGeneratorBtn nodeId="node-1" />)+ render(<PromptGeneratorBtn nodeId="node-1" />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await user.click(screen.getByRole('button', { name: 'appDebug.operation.automatic' }))diff --git a/web/app/components/workflow/nodes/llm/components/panel-memory-section.tsx b/web/app/components/workflow/nodes/llm/components/panel-memory-section.tsxindex 43e022a41b3..522db629ab7 100644--- a/web/app/components/workflow/nodes/llm/components/panel-memory-section.tsx+++ b/web/app/components/workflow/nodes/llm/components/panel-memory-section.tsx@@ -1,16 +1,16 @@import type { FC } from 'react'import type { LLMNodeType } from '../types'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type { Memory, Node, NodeOutPutVar } from '@/app/components/workflow/types'import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'import * as React from 'react'import { useTranslation } from 'react-i18next'import MemoryConfig from '@/app/components/workflow/nodes/_base/components/memory-config'import Editor from '@/app/components/workflow/nodes/_base/components/prompt/editor'-import { FlowType } from '@/types/common'type Props = Readonly<{readOnly: boolean- isChatMode: boolean+ isChatflow: booleanisChatModel: booleanisCompletionModel: booleaninputs: LLMNodeType@@ -21,7 +21,7 @@ type Props = Readonly<{}availableVars: NodeOutPutVar[]availableNodesWithParent: Node[]- flowType?: FlowType+ resourceKind?: EditorResource['kind']handleSyeQueryChange: (query: string) => voidhandleMemoryChange: (memory?: Memory) => void}>@@ -44,14 +44,14 @@ const SNIPPET_DEFAULT_MEMORY: Memory = {const PanelMemorySection: FC<Props> = ({readOnly,- isChatMode,+ isChatflow,isChatModel,isCompletionModel,inputs,hasSetBlockStatus,availableVars,availableNodesWithParent,- flowType,+ resourceKind,handleSyeQueryChange,handleMemoryChange,}) => {@@ -59,11 +59,11 @@ const PanelMemorySection: FC<Props> = ({const memoryLabelId = React.useId()const { t } = useTranslation(['workflow', 'workflowModels'])- const isSnippetFlow = flowType === FlowType.snippet+ const isSnippetFlow = resourceKind === 'snippet'const shouldCheckSysQuery = !isSnippetFlowconst defaultMemory = isSnippetFlow ? SNIPPET_DEFAULT_MEMORY : DEFAULT_MEMORY- if (!isChatMode) return null+ if (!isChatflow) return nullreturn (<>diff --git a/web/app/components/workflow/nodes/llm/components/prompt-generator-btn.tsx b/web/app/components/workflow/nodes/llm/components/prompt-generator-btn.tsxindex 4ac2e357dbe..cb20742f7d7 100644--- a/web/app/components/workflow/nodes/llm/components/prompt-generator-btn.tsx+++ b/web/app/components/workflow/nodes/llm/components/prompt-generator-btn.tsx@@ -1,15 +1,17 @@'use client'+import type { FC } from 'react'import type { ModelConfig } from '@/app/components/workflow/types'import type { GenRes } from '@/service/debug'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useAtomValue } from 'jotai'import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import GetAutomaticResModal from '@/app/components/app/configuration/config/automatic/get-automatic-res'-import { AppModeEnum } from '@/types/app'-import { useHooksStore } from '../../../hooks-store'+import { getEditorResourceId } from '@/app/components/workflow/editor-resource/resource'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'type Props = Readonly<{className?: string@@ -36,7 +38,8 @@ const PromptGeneratorBtn: FC<Props> = ({},[onGenerated],)- const configsMap = useHooksStore((s) => s.configsMap)+ const resource = useAtomValue(editorResourceAtom)+ const resourceId = getEditorResourceId(resource)return (<div className={cn(className)}><IconButton@@ -48,11 +51,11 @@ const PromptGeneratorBtn: FC<Props> = ({</IconButton>{showAutomatic && (<GetAutomaticResModal- mode={AppModeEnum.CHAT}+ modelMode="chat"isShow={showAutomatic}onClose={() => setShowAutomatic(false)}onFinished={handleAutomaticRes}- flowId={configsMap?.flowId || ''}+ flowId={resourceId || ''}nodeId={nodeId}editorId={editorId}currentPrompt={currentPrompt}diff --git a/web/app/components/workflow/nodes/llm/default.ts b/web/app/components/workflow/nodes/llm/default.tsindex dec0beef655..72ce31006ac 100644--- a/web/app/components/workflow/nodes/llm/default.ts+++ b/web/app/components/workflow/nodes/llm/default.ts@@ -1,10 +1,9 @@import type { TFunction } from 'i18next'import type { EnvironmentVariable, NodeDefault, PromptItem } from '../../types'import type { LLMNodeType } from './types'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import { genNodeMetaData } from '@/app/components/workflow/utils'// import { RETRIEVAL_OUTPUT_STRUCT } from '../../constants'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import { BlockEnum, EditionType, PromptRole } from '../../types'import {getLLMModelIssue,@@ -45,7 +44,7 @@ const nodeDefault: NodeDefault<LLMNodeType> = {model: {provider: '',name: '',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {temperature: 0.7,},@@ -72,12 +71,12 @@ const nodeDefault: NodeDefault<LLMNodeType> = {payload: LLMNodeType,t: TFunction<['workflow']>,moreDataForCheckValid?: {- flowType?: FlowType+ resourceKind?: EditorResource['kind']environmentVariables?: EnvironmentVariable[]},) {let errorMessages = ''- const isSnippetFlow = moreDataForCheckValid?.flowType === FlowType.snippet+ const isSnippetFlow = moreDataForCheckValid?.resourceKind === 'snippet'const hasValidModelSelector =payload.model_selector === undefined ||!isEnvironmentModelSource(payload.model_selector) ||@@ -100,7 +99,7 @@ const nodeDefault: NodeDefault<LLMNodeType> = {})if (!errorMessages && !payload.memory) {- const isChatModel = model?.mode === AppModeEnum.CHAT+ const isChatModel = model?.mode === 'chat'const isPromptEmpty = isChatModel? !(payload.prompt_template as PromptItem[]).some((t) => {if (t.edition_type === EditionType.jinja2) return t.jinja2_text !== ''@@ -118,7 +117,7 @@ const nodeDefault: NodeDefault<LLMNodeType> = {}if (!errorMessages && !!payload.memory) {- const isChatModel = model?.mode === AppModeEnum.CHAT+ const isChatModel = model?.mode === 'chat'// payload.memory.query_prompt_template not pass is default: {{#sys.query#}}if (!isSnippetFlow &&@@ -130,7 +129,7 @@ const nodeDefault: NodeDefault<LLMNodeType> = {}if (!errorMessages) {- const isChatModel = model?.mode === AppModeEnum.CHAT+ const isChatModel = model?.mode === 'chat'const isShowVars = (() => {if (isChatModel)return (payload.prompt_template as PromptItem[]).some(diff --git a/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-input-manager.spec.ts b/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-input-manager.spec.tsindex 85d184012e5..2777752a353 100644--- a/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-input-manager.spec.ts+++ b/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-input-manager.spec.ts@@ -2,7 +2,6 @@ import type { LLMNodeType } from '../../types'import type { LLMDefaultConfig } from '../use-llm-input-manager'import { act, renderHook, waitFor } from '@testing-library/react'import { BlockEnum, EditionType, PromptRole } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import useLLMInputManager from '../use-llm-input-manager'const createPayload = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({@@ -12,7 +11,7 @@ const createPayload = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},prompt_template: [@@ -110,7 +109,7 @@ describe('use-llm-input-manager', () => {model: {provider: 'openai',name: 'gpt-4o-mini',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,completion_params: {},},}),@@ -124,7 +123,7 @@ describe('use-llm-input-manager', () => {model: {provider: 'openai',name: 'gpt-4o-mini',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,completion_params: {},},})@@ -139,7 +138,7 @@ describe('use-llm-input-manager', () => {model: {provider: 'openai',name: 'gpt-4o-mini',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,completion_params: {},},prompt_template: draftPayload.prompt_template,diff --git a/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-prompt-config.spec.ts b/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-prompt-config.spec.tsindex d0dd204c4a3..66d7009c98d 100644--- a/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-prompt-config.spec.ts+++ b/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-prompt-config.spec.ts@@ -7,7 +7,6 @@ import {QUERY_PLACEHOLDER_TEXT,} from '@/app/components/base/prompt-editor/constants'import { BlockEnum, EditionType, PromptRole, VarType } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import useLLMPromptConfig from '../use-llm-prompt-config'const createPayload = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({@@ -17,7 +16,7 @@ const createPayload = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},prompt_template: [@@ -67,7 +66,7 @@ describe('use-llm-prompt-config', () => {useLLMPromptConfig({inputs: missingConfigRef.current,inputRef: missingConfigRef,- isChatMode: true,+ isChatflow: true,isChatModel: true,setInputs: handleMissingConfigInputs,}),@@ -109,7 +108,7 @@ describe('use-llm-prompt-config', () => {useLLMPromptConfig({inputs: missingVariablesRef.current,inputRef: missingVariablesRef,- isChatMode: true,+ isChatflow: true,isChatModel: true,setInputs: handleMissingVariablesInputs,}),@@ -163,7 +162,7 @@ describe('use-llm-prompt-config', () => {useLLMPromptConfig({inputs: inputRef.current,inputRef,- isChatMode: true,+ isChatflow: true,isChatModel: true,setInputs: createSetInputs(inputRef),}),@@ -211,7 +210,7 @@ describe('use-llm-prompt-config', () => {useLLMPromptConfig({inputs: inputRef.current,inputRef,- isChatMode: true,+ isChatflow: true,isChatModel: true,setInputs: handleSetInputs,}),@@ -317,7 +316,7 @@ describe('use-llm-prompt-config', () => {model: {provider: 'openai',name: 'gpt-4o-mini',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,completion_params: {},},prompt_template: {@@ -333,7 +332,7 @@ describe('use-llm-prompt-config', () => {useLLMPromptConfig({inputs: basicInputRef.current,inputRef: basicInputRef,- isChatMode: true,+ isChatflow: true,isChatModel: false,setInputs: handleSetInputs,}),@@ -364,7 +363,7 @@ describe('use-llm-prompt-config', () => {model: {provider: 'openai',name: 'gpt-4o-mini',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,completion_params: {},},prompt_template: {@@ -381,7 +380,7 @@ describe('use-llm-prompt-config', () => {useLLMPromptConfig({inputs: jinjaInputRef.current,inputRef: jinjaInputRef,- isChatMode: false,+ isChatflow: false,isChatModel: false,setInputs: handleJinjaInputs,}),diff --git a/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-structured-output-config.spec.ts b/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-structured-output-config.spec.tsindex 6c3a680730a..7fc596a1176 100644--- a/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-structured-output-config.spec.ts+++ b/web/app/components/workflow/nodes/llm/hooks/__tests__/use-llm-structured-output-config.spec.ts@@ -4,7 +4,6 @@ import type { LLMNodeType } from '../../types'import { act, renderHook } from '@testing-library/react'import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { BlockEnum } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import { Type } from '../../types'import useLLMStructuredOutputConfig from '../use-llm-structured-output-config'@@ -19,7 +18,7 @@ const createPayload = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},prompt_template: [],diff --git a/web/app/components/workflow/nodes/llm/hooks/use-llm-prompt-config.ts b/web/app/components/workflow/nodes/llm/hooks/use-llm-prompt-config.tsindex 25ae8d7c126..83138f44d61 100644--- a/web/app/components/workflow/nodes/llm/hooks/use-llm-prompt-config.ts+++ b/web/app/components/workflow/nodes/llm/hooks/use-llm-prompt-config.ts@@ -20,7 +20,7 @@ import { EditionType, VarType } from '@/app/components/workflow/types'type Params = {inputs: LLMNodeTypeinputRef: MutableRefObject<LLMNodeType>- isChatMode: boolean+ isChatflow: booleanisChatModel: booleansetInputs: (inputs: LLMNodeType) => void}@@ -84,14 +84,14 @@ const filterMemoryPromptVar = (varPayload: Var) => {return memoryPromptVariableTypes.includes(varPayload.type)}-const useLLMPromptConfig = ({ inputs, inputRef, isChatMode, isChatModel, setInputs }: Params) => {+const useLLMPromptConfig = ({ inputs, inputRef, isChatflow, isChatModel, setInputs }: Params) => {const hasSetBlockStatus = useMemo(() => {const promptTemplate = inputs.prompt_templateconst hasSetContext = isChatModel? (promptTemplate as PromptItem[]).some((item) => checkHasContextBlock(item.text)): checkHasContextBlock((promptTemplate as PromptItem).text)- if (!isChatMode) {+ if (!isChatflow) {return {history: false,query: false,@@ -112,7 +112,7 @@ const useLLMPromptConfig = ({ inputs, inputRef, isChatMode, isChatModel, setInpuquery: checkHasQueryBlock((promptTemplate as PromptItem).text),context: hasSetContext,}- }, [inputs.prompt_template, isChatMode, isChatModel])+ }, [inputs.prompt_template, isChatflow, isChatModel])const shouldShowContextTip = !hasSetBlockStatus.context && inputs.context.enableddiff --git a/web/app/components/workflow/nodes/llm/panel.tsx b/web/app/components/workflow/nodes/llm/panel.tsxindex eb3253d1e59..63514608187 100644--- a/web/app/components/workflow/nodes/llm/panel.tsx+++ b/web/app/components/workflow/nodes/llm/panel.tsx@@ -10,11 +10,12 @@ import {SelectTrigger,} from '@langgenius/dify-ui/select'import { useQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import * as React from 'react'import { useCallback, useLayoutEffect, useRef } from 'react'import { useTranslation } from 'react-i18next'import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'-import { useHooksStore } from '@/app/components/workflow/hooks-store/store'+import { editorResourceKindAtom } from '@/app/components/workflow/editor-resource/state'import Field from '@/app/components/workflow/nodes/_base/components/field'import FormInputTypeSwitch from '@/app/components/workflow/nodes/_base/components/form-input-type-switch'import Split from '@/app/components/workflow/nodes/_base/components/split'@@ -22,7 +23,6 @@ import VarList from '@/app/components/workflow/nodes/_base/components/variable/vimport { VarKindType } from '@/app/components/workflow/nodes/_base/types'import { toast } from '@/app/notifications'import { consoleQuery } from '@/service/console'-import { FlowType } from '@/types/common'import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'import { extractPluginId } from '../../utils/plugin'import ConfigVision from '../_base/components/config-vision'@@ -47,7 +47,7 @@ const getModelSelectionKey = (const Panel: FC<NodePanelProps<LLMNodeType>> = ({ id, data }) => {const { t } = useTranslation(['common', 'workflow', 'modelProvider', 'workflowModels'])- const flowType = useHooksStore((s) => s.configsMap?.flowType)+ const resourceKind = useAtomValue(editorResourceKindAtom)const {readOnly,inputs,@@ -55,7 +55,7 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({ id, data }) => {environmentVariables,isEnvironmentModelSource,isChatModel,- isChatMode,+ isChatflow,isCompletionModel,shouldShowContextTip,isVisionModel,@@ -213,7 +213,7 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({ id, data }) => {requiredwarningDot={hasModelWarning}operations={- flowType === FlowType.snippet && !isEnvironmentModelSource ? undefined : (+ resourceKind === 'snippet' && !isEnvironmentModelSource ? undefined : (<FormInputTypeSwitchvalue={isEnvironmentModelSource ? VarKindType.variable : VarKindType.constant}readonly={readOnly}@@ -299,7 +299,7 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({ id, data }) => {nodeId={id}filterVar={isShowVars ? filterJinja2InputVar : filterInputVar}isChatModel={isChatModel}- isChatApp={isChatMode}+ isChatApp={isChatflow}isShowContextpayload={inputs.prompt_template}onChange={handlePromptChange}@@ -338,19 +338,19 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({ id, data }) => {</Field>)}- {isChatMode && (+ {isChatflow && (<><Split /><PanelMemorySectionreadOnly={readOnly}- isChatMode={isChatMode}+ isChatflow={isChatflow}isChatModel={isChatModel}isCompletionModel={isCompletionModel}inputs={inputs}hasSetBlockStatus={hasSetBlockStatus}availableVars={availableVars}availableNodesWithParent={availableNodesWithParent}- flowType={flowType}+ resourceKind={resourceKind}handleSyeQueryChange={handleSyeQueryChange}handleMemoryChange={handleMemoryChange}/>diff --git a/web/app/components/workflow/nodes/llm/use-config.ts b/web/app/components/workflow/nodes/llm/use-config.tsindex 901a9449a81..f5493f3798f 100644--- a/web/app/components/workflow/nodes/llm/use-config.ts+++ b/web/app/components/workflow/nodes/llm/use-config.ts@@ -2,14 +2,15 @@ import type { LLMDefaultConfig } from './hooks/use-llm-input-manager'import type { LLMNodeType } from './types'import type { EnvironmentVariable, ValueSelector } from '@/app/components/workflow/types'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useEffect, useState } from 'react'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'-import { AppModeEnum } from '@/types/app'import useConfigVision from '../../hooks/use-config-vision'import useInspectVarsCrud from '../../hooks/use-inspect-vars-crud'-import { useIsChatMode, useNodesReadOnly } from '../../hooks/use-workflow'+import { useNodesReadOnly } from '../../hooks/use-workflow'import { useStore } from '../../store'import useAvailableVarList from '../_base/hooks/use-available-var-list'import useLLMInputManager from './hooks/use-llm-input-manager'@@ -25,7 +26,7 @@ const EMPTY_ENVIRONMENT_VARIABLES: EnvironmentVariable[] = []const useConfig = (id: string, payload: LLMNodeType) => {const { nodesReadOnly: readOnly } = useNodesReadOnly()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const defaultConfig = useStore((s) => s.nodesDefaultConfigs)?.[payload.type] as| LLMDefaultConfig@@ -45,8 +46,8 @@ const useConfig = (id: string, payload: LLMNodeType) => {name: '',}const modelMode = model.mode- const isChatModel = modelMode === AppModeEnum.CHAT- const isCompletionModel = !isChatModel+ const isChatModel = modelMode === 'chat'+ const isCompletionModel = modelMode === 'completion'const { inputRef, setInputs, appendDefaultPromptConfig } = useLLMInputManager({inputs,@@ -91,7 +92,7 @@ const useConfig = (id: string, payload: LLMNodeType) => {draft.model_selector = modelSelectorconst isModeChange = model.mode !== inputRef.current.model.modeif (isModeChange && defaultConfig && Object.keys(defaultConfig).length > 0)- appendDefaultPromptConfig(draft, defaultConfig, model.mode === AppModeEnum.CHAT)+ appendDefaultPromptConfig(draft, defaultConfig, model.mode === 'chat')})setInputs(nextInputs)setModelChanged(true)@@ -194,7 +195,7 @@ const useConfig = (id: string, payload: LLMNodeType) => {const promptConfig = useLLMPromptConfig({inputs,inputRef,- isChatMode,+ isChatflow,isChatModel,setInputs,})@@ -214,7 +215,7 @@ const useConfig = (id: string, payload: LLMNodeType) => {return {readOnly,- isChatMode,+ isChatflow,inputs,model,environmentVariables,diff --git a/web/app/components/workflow/nodes/llm/use-single-run-form-params.ts b/web/app/components/workflow/nodes/llm/use-single-run-form-params.tsindex 49dab948f3d..4c3f19251d7 100644--- a/web/app/components/workflow/nodes/llm/use-single-run-form-params.ts+++ b/web/app/components/workflow/nodes/llm/use-single-run-form-params.ts@@ -3,14 +3,15 @@ import type { LLMNodeType } from './types'import type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'import type { InputVar, PromptItem, Var, Variable } from '@/app/components/workflow/types'import { noop } from 'es-toolkit/function'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'-import { useHooksStore } from '@/app/components/workflow/hooks-store/store'+import {+ editorResourceKindAtom,+ isChatflowAtom,+} from '@/app/components/workflow/editor-resource/state'import { InputVarType, VarType } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import useConfigVision from '../../hooks/use-config-vision'-import { useIsChatMode } from '../../hooks/use-workflow'import { EditionType } from '../../types'import useAvailableVarList from '../_base/hooks/use-available-var-list'import useNodeCrud from '../_base/hooks/use-node-crud'@@ -42,9 +43,9 @@ const useSingleRunFormParams = ({const { t } = useTranslation(['workflowModels'])const { inputs } = useNodeCrud<LLMNodeType>(id, payload)const getVarInputs = getInputVars- const isChatMode = useIsChatMode()- const flowType = useHooksStore((s) => s.configsMap?.flowType)- const isSnippetFlow = flowType === FlowType.snippet+ const isChatflow = useAtomValue(isChatflowAtom)+ const resourceKind = useAtomValue(editorResourceKindAtom)+ const isSnippetFlow = resourceKind === 'snippet'const contexts = runInputData['#context#']const setContexts = useCallback(@@ -71,7 +72,7 @@ const useSingleRunFormParams = ({// modelconst model = inputs.modelconst modelMode = inputs.model?.mode- const isChatModel = modelMode === AppModeEnum.CHAT+ const isChatModel = modelMode === 'chat'const { isVisionModel } = useConfigVision(model, {payload: inputs.vision,onChange: noop,@@ -113,9 +114,9 @@ const useSingleRunFormParams = ({.filter((item) => item.edition_type !== EditionType.jinja2).map((item) => item.text): [(inputs.prompt_template as PromptItem).text]- if (!isSnippetFlow && isChatMode && isChatModel && !!inputs.memory) arr.push('{{#sys.query#}}')+ if (!isSnippetFlow && isChatflow && isChatModel && !!inputs.memory) arr.push('{{#sys.query#}}')- if (isChatMode && isChatModel && !!inputs.memory) arr.push(inputs.memory.query_prompt_template)+ if (isChatflow && isChatModel && !!inputs.memory) arr.push(inputs.memory.query_prompt_template)return arr})()diff --git a/web/app/components/workflow/nodes/loop-start/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/loop-start/__tests__/index.spec.tsxindex 25506393cc7..05edd3d07ba 100644--- a/web/app/components/workflow/nodes/loop-start/__tests__/index.spec.tsx+++ b/web/app/components/workflow/nodes/loop-start/__tests__/index.spec.tsx@@ -6,7 +6,7 @@ import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__import { BlockEnum } from '@/app/components/workflow/types'import { useAvailableBlocks } from '../../../hooks/use-available-blocks'import { useNodesInteractions } from '../../../hooks/use-nodes-interactions'-import { useIsChatMode, useNodesReadOnly } from '../../../hooks/use-workflow'+import { useNodesReadOnly } from '../../../hooks/use-workflow'import LoopStartNode, { LoopStartNodeDumb } from '../index'vi.mock('../../../hooks/use-available-blocks', async (importOriginal) => {@@ -33,14 +33,13 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,useNodesReadOnly: vi.fn(),- useIsChatMode: vi.fn(),}})const mockUseAvailableBlocks = vi.mocked(useAvailableBlocks)const mockUseNodesInteractions = vi.mocked(useNodesInteractions)const mockUseNodesReadOnly = vi.mocked(useNodesReadOnly)-const mockUseIsChatMode = vi.mocked(useIsChatMode)+const mockUseIsChatMode = vi.hoisted(() => vi.fn())const createAvailableBlocksResult = (): ReturnType<typeof useAvailableBlocks> => ({getAvailableBlocks: vi.fn(() => ({@@ -106,3 +105,10 @@ describe('LoopStartNode', () => {})})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/nodes/loop/__tests__/use-config.spec.tsx b/web/app/components/workflow/nodes/loop/__tests__/use-config.spec.tsxindex 84261702a96..883480d4d7a 100644--- a/web/app/components/workflow/nodes/loop/__tests__/use-config.spec.tsx+++ b/web/app/components/workflow/nodes/loop/__tests__/use-config.spec.tsx@@ -40,7 +40,7 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,useNodesReadOnly: () => ({ nodesReadOnly: false }),- useIsChatMode: () => false,+useWorkflow: () => ({getLoopNodeChildren: (...args: unknown[]) => mockGetLoopNodeChildren(...args),}),@@ -255,3 +255,10 @@ describe('useConfig', () => {)})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => false) }+})diff --git a/web/app/components/workflow/nodes/loop/components/condition-list/condition-input.tsx b/web/app/components/workflow/nodes/loop/components/condition-list/condition-input.tsxindex 28a40023a11..14da06f1298 100644--- a/web/app/components/workflow/nodes/loop/components/condition-list/condition-input.tsx+++ b/web/app/components/workflow/nodes/loop/components/condition-list/condition-input.tsx@@ -1,6 +1,8 @@import type { Node } from '@/app/components/workflow/types'+import { useAtomValue } from 'jotai'import { useTranslation } from 'react-i18next'import PromptEditor from '@/app/components/base/prompt-editor'+import { editorResourceKindAtom } from '@/app/components/workflow/editor-resource/state'import { useStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'@@ -13,7 +15,7 @@ type ConditionInputProps = {const ConditionInput = ({ value, onChange, disabled, availableNodes }: ConditionInputProps) => {const { t } = useTranslation(['workflow', 'workflowLogic'])const controlPromptEditorRerenderKey = useStore((s) => s.controlPromptEditorRerenderKey)- const pipelineId = useStore((s) => s.pipelineId)+ const resourceKind = useAtomValue(editorResourceKindAtom)const setShowInputFieldPanel = useStore((s) => s.setShowInputFieldPanel)return (@@ -38,7 +40,7 @@ const ConditionInput = ({ value, onChange, disabled, availableNodes }: Condition}return acc}, {} as any),- showManageInputField: !!pipelineId,+ showManageInputField: resourceKind === 'knowledge-pipeline',onManageInputField: () => setShowInputFieldPanel?.(true),}}onChange={onChange}diff --git a/web/app/components/workflow/nodes/loop/use-config.ts b/web/app/components/workflow/nodes/loop/use-config.tsindex 118e3095053..55f91a1fb21 100644--- a/web/app/components/workflow/nodes/loop/use-config.ts+++ b/web/app/components/workflow/nodes/loop/use-config.ts@@ -9,7 +9,9 @@ import type {HandleUpdateSubVariableCondition,LoopNodeType,} from './types'+import { useAtomValue } from 'jotai'import { useCallback, useEffect, useRef } from 'react'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { useStore } from '@/app/components/workflow/store'import {useAllBuiltInTools,@@ -17,7 +19,7 @@ import {useAllMCPTools,useAllWorkflowTools,} from '@/service/use-tools'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'+import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'import { toNodeOutputVars } from '../_base/components/variable/utils'import useNodeCrud from '../_base/hooks/use-node-crud'import {@@ -40,7 +42,7 @@ import useIsVarFileAttribute from './use-is-var-file-attribute'const useConfig = (id: string, payload: LoopNodeType) => {const { nodesReadOnly: readOnly } = useNodesReadOnly()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const conversationVariables = useStore((s) => s.conversationVariables)const { inputs, setInputs } = useNodeCrud<LoopNodeType>(id, payload)@@ -75,7 +77,7 @@ const useConfig = (id: string, payload: LoopNodeType) => {}const childrenNodeVars = toNodeOutputVars(loopChildrenNodes,- isChatMode,+ isChatflow,undefined,[],conversationVariables,diff --git a/web/app/components/workflow/nodes/loop/use-is-var-file-attribute.ts b/web/app/components/workflow/nodes/loop/use-is-var-file-attribute.tsindex c868e95db9d..56397467f97 100644--- a/web/app/components/workflow/nodes/loop/use-is-var-file-attribute.ts+++ b/web/app/components/workflow/nodes/loop/use-is-var-file-attribute.ts@@ -1,6 +1,8 @@import type { ValueSelector } from '../../types'+import { useAtomValue } from 'jotai'import { useMemo } from 'react'-import { useIsChatMode, useWorkflow } from '../../hooks/use-workflow'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'+import { useWorkflow } from '../../hooks/use-workflow'import { useWorkflowVariables } from '../../hooks/use-workflow-variables'import { VarType } from '../../types'@@ -8,7 +10,7 @@ type Params = {nodeId: string}const useIsVarFileAttribute = ({ nodeId }: Params) => {- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const { getBeforeNodesInSameBranch } = useWorkflow()const availableNodes = useMemo(() => {return getBeforeNodesInSameBranch(nodeId)@@ -20,7 +22,7 @@ const useIsVarFileAttribute = ({ nodeId }: Params) => {const varType = getCurrentVariableType({valueSelector: parentVariable,availableNodes,- isChatMode,+ isChatflow,isConstant: false,})return varType === VarType.filediff --git a/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsxindex 2f1079cb31d..bcbb4324e0d 100644--- a/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx+++ b/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx@@ -7,7 +7,6 @@ import userEvent from '@testing-library/user-event'import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'import { ChangeType } from '@/app/components/workflow/types'import { toast } from '@/app/notifications'-import { AppModeEnum } from '@/types/app'import { BlockEnum } from '../../../types'import { ExtractParameterList } from '../components/extract-parameter/list'import { ParameterDialog } from '../components/extract-parameter/update'@@ -59,7 +58,7 @@ vi.mock(setModel({provider: 'anthropic',modelId: 'claude-3-7-sonnet',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})}>@@ -247,7 +246,7 @@ const createData = (model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},query: ['node-1', 'query'],@@ -266,7 +265,7 @@ const createConfigResult = (readOnly: false,handleInputVarChange: vi.fn(),filterVar: (_varPayload: Var) => true,- isChatMode: true,+ isChatflow: true,inputs: createData(),isChatModel: true,isCompletionModel: false,@@ -571,7 +570,7 @@ describe('parameter-extractor path', () => {model: {provider: '',name: '',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},})}@@ -634,7 +633,7 @@ describe('parameter-extractor path', () => {expect(handleModelChanged).toHaveBeenCalledWith({provider: 'anthropic',modelId: 'claude-3-7-sonnet',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})expect(handleCompletionParamsChange).toHaveBeenCalledWith({ temperature: 0.2 })expect(handleInputVarChange).toHaveBeenCalledWith(['node-1', 'query'])diff --git a/web/app/components/workflow/nodes/parameter-extractor/__tests__/node.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/__tests__/node.spec.tsxindex fb924bc8bd8..c25ae240402 100644--- a/web/app/components/workflow/nodes/parameter-extractor/__tests__/node.spec.tsx+++ b/web/app/components/workflow/nodes/parameter-extractor/__tests__/node.spec.tsx@@ -2,7 +2,6 @@ import type { ParameterExtractorNodeType } from '../types'import { render, screen } from '@testing-library/react'import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'import { BlockEnum } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import Node from '../node'import { ReasoningModeType } from '../types'@@ -27,7 +26,7 @@ const createData = (model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},} as ParameterExtractorNodeType['model'],query: ['node-1', 'query'],@@ -62,7 +61,7 @@ describe('parameter-extractor/node', () => {model: {provider: '',name: '',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},} as ParameterExtractorNodeType['model'],})}diff --git a/web/app/components/workflow/nodes/parameter-extractor/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/__tests__/panel.spec.tsxindex 0ca37bf0d30..79dcf6065e4 100644--- a/web/app/components/workflow/nodes/parameter-extractor/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/parameter-extractor/__tests__/panel.spec.tsx@@ -3,7 +3,6 @@ import type { PanelProps } from '@/types/workflow'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { BlockEnum } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'import Panel from '../panel'import { ParamType, ReasoningModeType } from '../types'import useConfig from '../use-config'@@ -26,7 +25,7 @@ vi.mock(setModel({provider: 'anthropic',modelId: 'claude-3-7-sonnet',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})}>@@ -137,7 +136,7 @@ const createData = (model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},} as ParameterExtractorNodeType['model'],query: ['node-1', 'query'],@@ -177,7 +176,7 @@ describe('parameter-extractor/panel', () => {readOnly: false,handleInputVarChange,filterVar: vi.fn(() => true),- isChatMode: true,+ isChatflow: true,inputs: createData(),isChatModel: true,isCompletionModel: false,@@ -236,7 +235,7 @@ describe('parameter-extractor/panel', () => {expect(handleModelChanged).toHaveBeenCalledWith({provider: 'anthropic',modelId: 'claude-3-7-sonnet',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})expect(handleCompletionParamsChange).toHaveBeenCalledWith({ temperature: 0.2 })expect(handleInputVarChange).toHaveBeenCalledWith(['node-1', 'query'])diff --git a/web/app/components/workflow/nodes/parameter-extractor/__tests__/use-single-run-form-params.spec.ts b/web/app/components/workflow/nodes/parameter-extractor/__tests__/use-single-run-form-params.spec.tsindex d731a1d67d9..cd9f5963b6e 100644--- a/web/app/components/workflow/nodes/parameter-extractor/__tests__/use-single-run-form-params.spec.ts+++ b/web/app/components/workflow/nodes/parameter-extractor/__tests__/use-single-run-form-params.spec.ts@@ -2,7 +2,7 @@ import type { ParameterExtractorNodeType } from '../types'import type { InputVar } from '@/app/components/workflow/types'import { renderHook } from '@testing-library/react'import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'-import { AppModeEnum, Resolution } from '@/types/app'+import { Resolution } from '@/types/app'import useConfigVision from '../../../hooks/use-config-vision'import useAvailableVarList from '../../_base/hooks/use-available-var-list'import useNodeCrud from '../../_base/hooks/use-node-crud'@@ -37,7 +37,7 @@ const createData = (model: {provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},} as ParameterExtractorNodeType['model'],query: ['node-1', 'query'],diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/import-from-tool.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/import-from-tool.spec.tsxindex a65eb3e3ba2..a04b388f3c7 100644--- a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/import-from-tool.spec.tsx+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/import-from-tool.spec.tsx@@ -70,10 +70,11 @@ const createToolParameter = (overrides: Partial<ToolParameter> = {}): ToolParame})const renderImportFromTool = (ui: React.ReactElement) => {- const { wrapper: ConsoleQueryWrapper } = createConsoleQueryWrapper({+ const { queryClient } = createConsoleQueryWrapper({systemFeatures: { enable_marketplace: false },})- return renderWorkflowComponent(<ConsoleQueryWrapper>{ui}</ConsoleQueryWrapper>, {+ return renderWorkflowComponent(ui, {+ queryClient,hooksStoreProps: {availableNodesMetaData: { nodes: [] },},diff --git a/web/app/components/workflow/nodes/parameter-extractor/default.ts b/web/app/components/workflow/nodes/parameter-extractor/default.tsindex 9f26cec1c3e..8f891367c38 100644--- a/web/app/components/workflow/nodes/parameter-extractor/default.ts+++ b/web/app/components/workflow/nodes/parameter-extractor/default.ts@@ -4,7 +4,6 @@ import type { ParameterExtractorNodeType } from './types'import { BlockClassification } from '@/app/components/workflow/block-selector/types'import { BlockEnum } from '@/app/components/workflow/types'import { genNodeMetaData } from '@/app/components/workflow/utils'-import { AppModeEnum } from '@/types/app'import { ReasoningModeType } from './types'const i18nPrefix = ''@@ -21,7 +20,7 @@ const nodeDefault: NodeDefault<ParameterExtractorNodeType> = {model: {provider: '',name: '',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {temperature: 0.7,},diff --git a/web/app/components/workflow/nodes/parameter-extractor/panel.tsx b/web/app/components/workflow/nodes/parameter-extractor/panel.tsxindex 92a1f4cd04a..1cfbb1f4004 100644--- a/web/app/components/workflow/nodes/parameter-extractor/panel.tsx+++ b/web/app/components/workflow/nodes/parameter-extractor/panel.tsx@@ -34,7 +34,7 @@ const Panel: FC<NodePanelProps<ParameterExtractorNodeType>> = ({ id, data }) =>handleInputVarChange,filterVar,isChatModel,- isChatMode,+ isChatflow,isCompletionModel,handleModelChanged,handleImportFromTool,@@ -134,7 +134,7 @@ const Panel: FC<NodePanelProps<ParameterExtractorNodeType>> = ({ id, data }) =>onChange={handleInstructionChange}readOnly={readOnly}isChatModel={isChatModel}- isChatApp={isChatMode}+ isChatApp={isChatflow}isShowContext={false}hasSetBlockStatus={hasSetBlockStatus}nodesOutputVars={availableVars}@@ -144,7 +144,7 @@ const Panel: FC<NodePanelProps<ParameterExtractorNodeType>> = ({ id, data }) =><FieldCollapse title={t(($) => $[`${i18nPrefix}.advancedSetting`], { ns: 'workflowModels' })}><>{/* Memory */}- {isChatMode && (+ {isChatflow && (<div className="mt-4"><MemoryConfigreadonly={readOnly}diff --git a/web/app/components/workflow/nodes/parameter-extractor/use-config.ts b/web/app/components/workflow/nodes/parameter-extractor/use-config.tsindex 1779edfc9b0..5a3e3db1a75 100644--- a/web/app/components/workflow/nodes/parameter-extractor/use-config.ts+++ b/web/app/components/workflow/nodes/parameter-extractor/use-config.ts@@ -1,6 +1,7 @@import type { Memory, MoreInfo, ValueSelector, Var } from '../../types'import type { Param, ParameterExtractorNodeType, ReasoningModeType } from './types'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useEffect, useRef, useState } from 'react'import { checkHasQueryBlock } from '@/app/components/base/prompt-editor/constants'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'@@ -8,13 +9,13 @@ import {useModelListAndDefaultModelAndCurrentProviderAndModel,useTextGenerationCurrentProviderAndModelAndModelList,} from '@/app/components/header/account-setting/model-provider-page/hooks'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'-import { AppModeEnum } from '@/types/app'import { supportFunctionCall } from '@/utils/tool-call'import useConfigVision from '../../hooks/use-config-vision'import useInspectVarsCrud from '../../hooks/use-inspect-vars-crud'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'+import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'import { useStore } from '../../store'import { ChangeType, VarType } from '../../types'@@ -22,7 +23,7 @@ const useConfig = (id: string, payload: ParameterExtractorNodeType) => {const { deleteNodeInspectorVars, renameInspectVarName } = useInspectVarsCrud()const { nodesReadOnly: readOnly } = useNodesReadOnly()const { handleOutVarRenameChange } = useWorkflow()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const defaultConfig = useStore((s) => s.nodesDefaultConfigs)?.[payload.type]@@ -109,14 +110,14 @@ const useConfig = (id: string, payload: ParameterExtractorNodeType) => {const model = inputs.model || {provider: '',name: '',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {temperature: 0.7,},}const modelMode = inputs.model?.mode- const isChatModel = modelMode === AppModeEnum.CHAT- const isCompletionModel = !isChatModel+ const isChatModel = modelMode === 'chat'+ const isCompletionModel = modelMode === 'completion'const {isVisionModel,@@ -159,7 +160,7 @@ const useConfig = (id: string, payload: ParameterExtractorNodeType) => {draft.model.mode = model.mode!const isModeChange = model.mode !== inputRef.current.model?.modeif (isModeChange && defaultConfig && Object.keys(defaultConfig).length > 0)- appendDefaultPromptConfig(draft, defaultConfig, model.mode === AppModeEnum.CHAT)+ appendDefaultPromptConfig(draft, defaultConfig, model.mode === 'chat')})setInputs(newInputs)setModelChanged(true)@@ -224,7 +225,7 @@ const useConfig = (id: string, payload: ParameterExtractorNodeType) => {const hasSetBlockStatus = {history: false,- query: isChatMode ? checkHasQueryBlock(inputs.instruction) : false,+ query: isChatflow ? checkHasQueryBlock(inputs.instruction) : false,context: false,}@@ -262,7 +263,7 @@ const useConfig = (id: string, payload: ParameterExtractorNodeType) => {readOnly,handleInputVarChange,filterVar,- isChatMode,+ isChatflow,inputs,isChatModel,isCompletionModel,diff --git a/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsxindex 6d4237a992c..80c2e24b48d 100644--- a/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx+++ b/web/app/components/workflow/nodes/question-classifier/__tests__/integration.spec.tsx@@ -181,7 +181,7 @@ const createConfigResult = (readOnly: false,inputs: createData(),handleModelChanged: vi.fn(),- isChatMode: true,+ isChatflow: true,isChatModel: true,handleCompletionParamsChange: vi.fn(),handleQueryVarChange: vi.fn(),diff --git a/web/app/components/workflow/nodes/question-classifier/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/question-classifier/__tests__/panel.spec.tsxindex 9d8024a9d87..da7421aebc6 100644--- a/web/app/components/workflow/nodes/question-classifier/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/question-classifier/__tests__/panel.spec.tsx@@ -120,7 +120,7 @@ describe('question-classifier/panel', () => {readOnly: false,inputs: createData(),handleModelChanged,- isChatMode: true,+ isChatflow: true,isChatModel: true,handleCompletionParamsChange,handleQueryVarChange,diff --git a/web/app/components/workflow/nodes/question-classifier/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/question-classifier/__tests__/use-config.spec.tsindex c27d5c336ed..aa2f7590658 100644--- a/web/app/components/workflow/nodes/question-classifier/__tests__/use-config.spec.ts+++ b/web/app/components/workflow/nodes/question-classifier/__tests__/use-config.spec.ts@@ -1,14 +1,14 @@import type { QuestionClassifierNodeType } from '../types'-import { act, renderHook, waitFor } from '@testing-library/react'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'+import { act, waitFor } from '@testing-library/react'import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'import { useStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import useConfigVision from '../../../hooks/use-config-vision'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../../hooks/use-workflow'+import { useNodesReadOnly, useWorkflow } from '../../../hooks/use-workflow'import useConfig from '../use-config'vi.mock('../../../hooks/use-workflow', async (importOriginal) => {@@ -17,7 +17,7 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,useNodesReadOnly: vi.fn(),- useIsChatMode: vi.fn(),+useWorkflow: vi.fn(),}})@@ -40,14 +40,16 @@ vi.mock('@/app/components/workflow/store', () => ({}))const mockFlowType = vi.hoisted(() => ({- value: undefined as FlowType | undefined,+ value: undefined as EditorResource['kind'] | undefined,}))vi.mock('@/app/components/workflow/hooks-store/store', () => ({- useHooksStore: (selector: (state: { configsMap?: { flowType?: FlowType } }) => unknown) =>+ useHooksStore: (+ selector: (state: { configsMap?: { resourceKind?: EditorResource['kind'] } }) => unknown,+ ) =>selector({configsMap: {- flowType: mockFlowType.value,+ resourceKind: mockFlowType.value,},}),}))@@ -63,7 +65,7 @@ vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', ()}))const mockUseNodesReadOnly = vi.mocked(useNodesReadOnly)-const mockUseIsChatMode = vi.mocked(useIsChatMode)+const mockUseIsChatMode = vi.hoisted(() => vi.fn())const mockUseWorkflow = vi.mocked(useWorkflow)const mockUseNodeCrud = vi.mocked(useNodeCrud)const mockUseModelListAndDefaultModelAndCurrentProviderAndModel = vi.mocked(@@ -82,7 +84,7 @@ const createPayload = (model: {provider: '',name: '',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {},},classes: [{ id: 'topic-1', name: 'Billing questions', label: 'CLASS 1' }],@@ -141,13 +143,15 @@ describe('question-classifier/use-config', () => {})it('preserves the selected model when the vision follow-up updates after model selection', async () => {- const { result } = renderHook(() => useConfig('question-classifier-node', createPayload()))+ const { result } = renderHook(() => useConfig('question-classifier-node', createPayload()), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleModelChanged({provider: 'openai',modelId: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})})@@ -157,7 +161,7 @@ describe('question-classifier/use-config', () => {model: expect.objectContaining({provider: 'openai',name: 'gpt-4o',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,}),vision: {enabled: false,@@ -168,7 +172,6 @@ describe('question-classifier/use-config', () => {})it('does not default the query selector to sys.query in snippet flows', async () => {- mockFlowType.value = FlowType.snippetmockUseWorkflow.mockReturnValue({getBeforeNodesInSameBranch: vi.fn(() => [{@@ -198,13 +201,15 @@ describe('question-classifier/use-config', () => {setInputs,})- renderHook(() =>- useConfig(- 'question-classifier-node',- createPayload({- query_variable_selector: [],- }),- ),+ renderHook(+ () =>+ useConfig(+ 'question-classifier-node',+ createPayload({+ query_variable_selector: [],+ }),+ ),+ { resource: { kind: 'snippet', snippetId: 'snippet-1' } },)await waitFor(() => {@@ -212,3 +217,10 @@ describe('question-classifier/use-config', () => {})})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/nodes/question-classifier/default.ts b/web/app/components/workflow/nodes/question-classifier/default.tsindex e4f9b54c2df..d1c39809182 100644--- a/web/app/components/workflow/nodes/question-classifier/default.ts+++ b/web/app/components/workflow/nodes/question-classifier/default.ts@@ -4,7 +4,6 @@ import type { QuestionClassifierNodeType } from './types'import { BlockClassification } from '@/app/components/workflow/block-selector/types'import { BlockEnum } from '@/app/components/workflow/types'import { genNodeMetaData } from '@/app/components/workflow/utils'-import { AppModeEnum } from '@/types/app'const i18nPrefix = ''@@ -20,7 +19,7 @@ const nodeDefault: NodeDefault<QuestionClassifierNodeType> = {model: {provider: '',name: '',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,completion_params: {temperature: 0.7,},diff --git a/web/app/components/workflow/nodes/question-classifier/panel.tsx b/web/app/components/workflow/nodes/question-classifier/panel.tsxindex 0bc32e22128..7134cd14bbd 100644--- a/web/app/components/workflow/nodes/question-classifier/panel.tsx+++ b/web/app/components/workflow/nodes/question-classifier/panel.tsx@@ -23,7 +23,7 @@ const Panel: FC<NodePanelProps<QuestionClassifierNodeType>> = ({ id, data }) =>readOnly,inputs,handleModelChanged,- isChatMode,+ isChatflow,isChatModel,handleCompletionParamsChange,handleQueryVarChange,@@ -94,13 +94,13 @@ const Panel: FC<NodePanelProps<QuestionClassifierNodeType>> = ({ id, data }) =></div><FieldCollapse title={t(($) => $[`${i18nPrefix}.advancedSetting`], { ns: 'workflowModels' })}><AdvancedSetting- hideMemorySetting={!isChatMode}+ hideMemorySetting={!isChatflow}instruction={inputs.instruction}onInstructionChange={handleInstructionChange}memory={inputs.memory}onMemoryChange={handleMemoryChange}readonly={readOnly}- isChatApp={isChatMode}+ isChatApp={isChatflow}isChatModel={isChatModel}hasSetBlockStatus={hasSetBlockStatus}nodesOutputVars={availableVars}diff --git a/web/app/components/workflow/nodes/question-classifier/use-config.ts b/web/app/components/workflow/nodes/question-classifier/use-config.tsindex 90f7d9c8857..cffc120dbec 100644--- a/web/app/components/workflow/nodes/question-classifier/use-config.ts+++ b/web/app/components/workflow/nodes/question-classifier/use-config.ts@@ -2,17 +2,19 @@ import type { Memory, ValueSelector, Var } from '../../types'import type { QuestionClassifierNodeType } from './types'import type { Topic } from '@/app/components/workflow/nodes/_base/components/branch-list/types'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { startTransition, useCallback, useEffect, useRef } from 'react'import { useUpdateNodeInternals } from 'reactflow'import { checkHasQueryBlock } from '@/app/components/base/prompt-editor/constants'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'-import { useHooksStore } from '@/app/components/workflow/hooks-store/store'+import {+ editorResourceKindAtom,+ isChatflowAtom,+} from '@/app/components/workflow/editor-resource/state'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'-import { AppModeEnum } from '@/types/app'-import { FlowType } from '@/types/common'import useConfigVision from '../../hooks/use-config-vision'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'+import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'import { useStore } from '../../store'import { BlockEnum, VarType } from '../../types'import useAvailableVarList from '../_base/hooks/use-available-var-list'@@ -20,9 +22,9 @@ import useAvailableVarList from '../_base/hooks/use-available-var-list'const useConfig = (id: string, payload: QuestionClassifierNodeType) => {const updateNodeInternals = useUpdateNodeInternals()const { nodesReadOnly: readOnly } = useNodesReadOnly()- const isChatMode = useIsChatMode()- const flowType = useHooksStore((s) => s.configsMap?.flowType)- const isSnippetFlow = flowType === FlowType.snippet+ const isChatflow = useAtomValue(isChatflowAtom)+ const resourceKind = useAtomValue(editorResourceKindAtom)+ const isSnippetFlow = resourceKind === 'snippet'const defaultConfig = useStore((s) => s.nodesDefaultConfigs)?.[payload.type]const { getBeforeNodesInSameBranch } = useWorkflow()const startNode = getBeforeNodesInSameBranch(id).find(@@ -49,7 +51,7 @@ const useConfig = (id: string, payload: QuestionClassifierNodeType) => {const model = inputs.modelconst modelMode = inputs.model?.mode- const isChatModel = modelMode === AppModeEnum.CHAT+ const isChatModel = modelMode === 'chat'const handleVisionChange = useCallback((newPayload: QuestionClassifierNodeType['vision']) => {@@ -144,7 +146,7 @@ const useConfig = (id: string, payload: QuestionClassifierNodeType) => {if (!isSnippetFlow &&draft.query_variable_selector.length === 0 &&- isChatMode &&+ isChatflow &&startNodeId) {draft.query_variable_selector = [startNodeId, 'sys.query']@@ -165,7 +167,7 @@ const useConfig = (id: string, payload: QuestionClassifierNodeType) => {startTransition(() => {setInputs(nextInputs)})- }, [defaultConfig, isChatMode, isSnippetFlow, setInputs, startNodeId])+ }, [defaultConfig, isChatflow, isSnippetFlow, setInputs, startNodeId])const handleClassesChange = useCallback((newClasses: Topic[]) => {@@ -205,7 +207,7 @@ const useConfig = (id: string, payload: QuestionClassifierNodeType) => {const hasSetBlockStatus = {history: false,- query: isChatMode ? checkHasQueryBlock(inputs.instruction) : false,+ query: isChatflow ? checkHasQueryBlock(inputs.instruction) : false,context: false,}@@ -257,7 +259,7 @@ const useConfig = (id: string, payload: QuestionClassifierNodeType) => {readOnly,inputs,handleModelChanged,- isChatMode,+ isChatflow,isChatModel,handleCompletionParamsChange,handleQueryVarChange,diff --git a/web/app/components/workflow/nodes/start/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/start/__tests__/panel.spec.tsxindex a65474e6ea9..811b1363178 100644--- a/web/app/components/workflow/nodes/start/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/start/__tests__/panel.spec.tsx@@ -69,7 +69,7 @@ describe('StartPanel', () => {handleAddVariable.mockReturnValue(true)mockUseConfig.mockReturnValue({readOnly: false,- isChatMode: true,+ isChatflow: true,inputs: createData(),isShowAddVarModal: false,showAddVarModal,@@ -99,7 +99,7 @@ describe('StartPanel', () => {it('should render the add modal and hide it after a successful confirm', () => {mockUseConfig.mockReturnValue({readOnly: false,- isChatMode: false,+ isChatflow: false,inputs: createData(),isShowAddVarModal: true,showAddVarModal,@@ -131,7 +131,7 @@ describe('StartPanel', () => {handleAddVariable.mockReturnValue(false)mockUseConfig.mockReturnValue({readOnly: false,- isChatMode: false,+ isChatflow: false,inputs: createData({variables: [{diff --git a/web/app/components/workflow/nodes/start/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/start/__tests__/use-config.spec.tsindex 4854693d88a..6a3e921f1b4 100644--- a/web/app/components/workflow/nodes/start/__tests__/use-config.spec.ts+++ b/web/app/components/workflow/nodes/start/__tests__/use-config.spec.ts@@ -24,7 +24,6 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {...actual,useNodesReadOnly: () => mockUseNodesReadOnly(),useWorkflow: () => mockUseWorkflow(),- useIsChatMode: () => mockUseIsChatMode(),}})@@ -151,7 +150,7 @@ describe('start/use-config', () => {)expect(mockRenameInspectVarName).toHaveBeenCalledWith('start-node', 'query', 'prompt')expect(result.current.readOnly).toBe(false)- expect(result.current.isChatMode).toBe(false)+ expect(result.current.isChatflow).toBe(false)})it('should block removal when the variable is still in use and confirm the deletion later', () => {@@ -271,3 +270,10 @@ describe('start/use-config', () => {)})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/nodes/start/__tests__/use-single-run-form-params.spec.ts b/web/app/components/workflow/nodes/start/__tests__/use-single-run-form-params.spec.tsindex b3f3d783c56..3ad4db8f256 100644--- a/web/app/components/workflow/nodes/start/__tests__/use-single-run-form-params.spec.ts+++ b/web/app/components/workflow/nodes/start/__tests__/use-single-run-form-params.spec.ts@@ -1,5 +1,5 @@import type { StartNodeType } from '../types'-import { renderHook } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum, InputVarType } from '@/app/components/workflow/types'import { withSelectorKey } from '@/test/i18n-mock'import useSingleRunFormParams from '../use-single-run-form-params'@@ -16,7 +16,6 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,- useIsChatMode: () => mockUseIsChatMode(),}})@@ -48,16 +47,18 @@ describe('start/use-single-run-form-params', () => {it('should include sys.query and sys.files dependencies for chat mode', () => {mockUseIsChatMode.mockReturnValue(true)- const { result } = renderHook(() =>- useSingleRunFormParams({- id: 'start-node',- payload: createPayload(),- runInputData: { query: 'hello' },- runInputDataRef: { current: {} },- getInputVars: () => [],- setRunInputData,- toVarInputs: () => [],- }),+ const { result } = renderHook(+ () =>+ useSingleRunFormParams({+ id: 'start-node',+ payload: createPayload(),+ runInputData: { query: 'hello' },+ runInputDataRef: { current: {} },+ getInputVars: () => [],+ setRunInputData,+ toVarInputs: () => [],+ }),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)expect(result.current.forms).toHaveLength(1)@@ -84,16 +85,18 @@ describe('start/use-single-run-form-params', () => {it('should omit sys.query when the workflow is not in chat mode', () => {mockUseIsChatMode.mockReturnValue(false)- const { result } = renderHook(() =>- useSingleRunFormParams({- id: 'start-node',- payload: createPayload(),- runInputData: {},- runInputDataRef: { current: {} },- getInputVars: () => [],- setRunInputData,- toVarInputs: () => [],- }),+ const { result } = renderHook(+ () =>+ useSingleRunFormParams({+ id: 'start-node',+ payload: createPayload(),+ runInputData: {},+ runInputDataRef: { current: {} },+ getInputVars: () => [],+ setRunInputData,+ toVarInputs: () => [],+ }),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)expect(result.current.forms[0]!.inputs).toEqual(@@ -105,3 +108,10 @@ describe('start/use-single-run-form-params', () => {])})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/nodes/start/panel.tsx b/web/app/components/workflow/nodes/start/panel.tsxindex 9dfd5da2f15..d6f2075f6e7 100644--- a/web/app/components/workflow/nodes/start/panel.tsx+++ b/web/app/components/workflow/nodes/start/panel.tsx@@ -17,7 +17,7 @@ const Panel: FC<NodePanelProps<StartNodeType>> = ({ id, data }) => {const { t } = useTranslation(['common', 'workflow'])const {readOnly,- isChatMode,+ isChatflow,inputs,isShowAddVarModal,showAddVarModal,@@ -62,7 +62,7 @@ const Panel: FC<NodePanelProps<StartNodeType>> = ({ id, data }) => {<div className="mt-1 space-y-1"><Split className="my-2" />- {isChatMode && (+ {isChatflow && (<VarItemreadonlypayload={@@ -78,7 +78,7 @@ const Panel: FC<NodePanelProps<StartNodeType>> = ({ id, data }) => {<VarItemreadonly- showLegacyBadge={!isChatMode}+ showLegacyBadge={!isChatflow}payload={{variable: 'userinput.files',diff --git a/web/app/components/workflow/nodes/start/use-config.ts b/web/app/components/workflow/nodes/start/use-config.tsindex 80d2e98e996..011d3f8e3bd 100644--- a/web/app/components/workflow/nodes/start/use-config.ts+++ b/web/app/components/workflow/nodes/start/use-config.ts@@ -1,20 +1,22 @@import type { StartNodeType } from './types'import type { InputVar, MoreInfo, ValueSelector } from '@/app/components/workflow/types'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'import { ChangeType } from '@/app/components/workflow/types'import { toast } from '@/app/notifications'import { hasDuplicateStr } from '@/utils/var'import useInspectVarsCrud from '../../hooks/use-inspect-vars-crud'-import { useIsChatMode, useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'+import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'const useConfig = (id: string, payload: StartNodeType) => {const { t } = useTranslation(['appDebug'])const { nodesReadOnly: readOnly } = useNodesReadOnly()const { handleOutVarRenameChange, isVarUsedInNodes, removeUsedVarInNodes } = useWorkflow()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const { inputs, setInputs } = useNodeCrud<StartNodeType>(id, payload)@@ -114,7 +116,7 @@ const useConfig = (id: string, payload: StartNodeType) => {)return {readOnly,- isChatMode,+ isChatflow,inputs,isShowAddVarModal,showAddVarModal: () => setIsShowAddVarModal(true),diff --git a/web/app/components/workflow/nodes/start/use-single-run-form-params.ts b/web/app/components/workflow/nodes/start/use-single-run-form-params.tsindex a1378468081..be733c33af2 100644--- a/web/app/components/workflow/nodes/start/use-single-run-form-params.ts+++ b/web/app/components/workflow/nodes/start/use-single-run-form-params.ts@@ -2,9 +2,10 @@ import type { RefObject } from 'react'import type { StartNodeType } from './types'import type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'import type { InputVar, ValueSelector, Variable } from '@/app/components/workflow/types'+import { useAtomValue } from 'jotai'import { useTranslation } from 'react-i18next'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { InputVarType } from '@/app/components/workflow/types'-import { useIsChatMode } from '../../hooks/use-workflow'type Params = {id: string@@ -17,7 +18,7 @@ type Params = {}const useSingleRunFormParams = ({ id, payload, runInputData, setRunInputData }: Params) => {const { t } = useTranslation(['workflowModels'])- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const forms = (() => {const forms: FormProps[] = []@@ -28,7 +29,7 @@ const useSingleRunFormParams = ({ id, payload, runInputData, setRunInputData }:}})- if (isChatMode) {+ if (isChatflow) {inputs.push({label: 'sys.query',variable: '#sys.query#',@@ -60,7 +61,7 @@ const useSingleRunFormParams = ({ id, payload, runInputData, setRunInputData }:})const vars: ValueSelector[] = [...inputVars, ['sys', 'files']]- if (isChatMode) vars.push(['sys', 'query'])+ if (isChatflow) vars.push(['sys', 'query'])return vars}diff --git a/web/app/components/workflow/nodes/tool/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/tool/__tests__/panel.spec.tsxindex 6ea8227d6c7..f385892c379 100644--- a/web/app/components/workflow/nodes/tool/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/tool/__tests__/panel.spec.tsx@@ -2,9 +2,10 @@ import type { ReactNode } from 'react'import type { ToolNodeType } from '../types'import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { NodePanelProps } from '@/app/components/workflow/types'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, screen } from '@testing-library/react'import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { CollectionType } from '@/app/components/tools/types'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum } from '@/app/components/workflow/types'import Panel from '../panel'@@ -146,7 +147,9 @@ const renderPanel = (data: ToolNodeType = createNodeData()) => {},}- return render(<Panel {...props} />)+ return render(<Panel {...props} />, {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ })}const createConfigResult = (overrides: Record<string, unknown> = {}) => ({diff --git a/web/app/components/workflow/nodes/tool/panel.tsx b/web/app/components/workflow/nodes/tool/panel.tsxindex fbf2389a1fe..8b2b9775e48 100644--- a/web/app/components/workflow/nodes/tool/panel.tsx+++ b/web/app/components/workflow/nodes/tool/panel.tsx@@ -1,9 +1,11 @@import type { FC } from 'react'import type { ToolNodeType } from './types'import type { NodePanelProps } from '@/app/components/workflow/types'+import { useAtomValue } from 'jotai'import * as React from 'react'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'+import { editorResourceKindAtom } from '@/app/components/workflow/editor-resource/state'import Field from '@/app/components/workflow/nodes/_base/components/field'import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/components/output-vars'import StructureOutputItem from '@/app/components/workflow/nodes/_base/components/variable/object-child-tree-panel/show'@@ -19,7 +21,7 @@ import useConfig from './hooks/use-config'const i18nPrefix = 'nodes.tool'const Panel: FC<NodePanelProps<ToolNodeType>> = ({ id, data }) => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const {readOnly,inputs,@@ -37,7 +39,7 @@ const Panel: FC<NodePanelProps<ToolNodeType>> = ({ id, data }) => {} = useConfig(id, data)const [collapsed, setCollapsed] = React.useState(false)- const pipelineId = useStore((s) => s.pipelineId)+ const resourceKind = useAtomValue(editorResourceKindAtom)const setShowInputFieldPanel = useStore((s) => s.setShowInputFieldPanel)const { schemaTypeDefinitions } = useMatchSchemaType()@@ -66,7 +68,7 @@ const Panel: FC<NodePanelProps<ToolNodeType>> = ({ id, data }) => {onChange={setInputVar}currentProvider={currCollection}currentTool={currTool}- showManageInputField={!!pipelineId}+ showManageInputField={resourceKind === 'knowledge-pipeline'}onManageInputField={() => setShowInputFieldPanel?.(true)}/></Field>diff --git a/web/app/components/workflow/nodes/trigger-webhook/__tests__/use-config.spec.tsx b/web/app/components/workflow/nodes/trigger-webhook/__tests__/use-config.spec.tsxindex 0cbe43f7829..888ab428b05 100644--- a/web/app/components/workflow/nodes/trigger-webhook/__tests__/use-config.spec.tsx+++ b/web/app/components/workflow/nodes/trigger-webhook/__tests__/use-config.spec.tsx@@ -1,7 +1,7 @@import type { WebhookTriggerNodeType } from '../types'+import { renderEditorHook as renderHookWithConsoleQuery } from '@/app/components/workflow/editor-resource/__tests__/render'import { BlockEnum, VarType } from '@/app/components/workflow/types'import { toast } from '@/app/notifications'-import { renderHookWithConsoleQuery } from '@/test/console/query-data'import { createNodeCrudModuleMock } from '../../__tests__/use-config-test-utils'import { useConfig } from '../use-config'@@ -43,14 +43,8 @@ vi.mock('@/app/components/workflow/nodes/_base/hooks/use-node-crud', () => ({...createNodeCrudModuleMock<WebhookTriggerNodeType>(mockSetInputs),}))-const routeParams = vi.hoisted(() => ({ appId: 'app-1' as string | undefined }))const mockRequest = vi.hoisted(() => vi.fn())-vi.mock('@/next/navigation', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/next/navigation')>()),- useParams: () => routeParams,-}))-vi.mock('@/service/console/browser', () => ({consoleBrowserLink: { call: mockRequest },}))@@ -77,7 +71,6 @@ const createPayload = (describe('useConfig', () => {beforeEach(() => {vi.clearAllMocks()- routeParams.appId = 'app-1'mockRequest.mockReset()mockUseNodesReadOnly.mockReturnValue({ nodesReadOnly: false })mockIsVarUsedInNodes.mockReturnValue(false)@@ -240,11 +233,15 @@ describe('useConfig', () => {expect(mockRequest).toHaveBeenCalledTimes(2)})- it('should expose readonly state and skip url generation without app id', async () => {+ it('should expose readonly state and skip url generation in a snippet', async () => {mockUseNodesReadOnly.mockReturnValue({ nodesReadOnly: true })- routeParams.appId = undefined- const { result } = renderHookWithConsoleQuery(() => useConfig('webhook-node', createPayload()))+ const { result } = renderHookWithConsoleQuery(+ () => useConfig('webhook-node', createPayload()),+ {+ resource: { kind: 'snippet', snippetId: 'snippet-1' },+ },+ )expect(result.current.readOnly).toBe(true)diff --git a/web/app/components/workflow/nodes/trigger-webhook/use-config.ts b/web/app/components/workflow/nodes/trigger-webhook/use-config.tsindex fa6c011a6fc..f4aaab40427 100644--- a/web/app/components/workflow/nodes/trigger-webhook/use-config.ts+++ b/web/app/components/workflow/nodes/trigger-webhook/use-config.ts@@ -1,11 +1,12 @@import type { SelectorParam } from 'i18next'import type { HttpMethod, WebhookHeader, WebhookParameter, WebhookTriggerNodeType } from './types'import { useQueryClient } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'import { toast } from '@/app/notifications'-import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'import {@@ -35,7 +36,7 @@ export const useConfig = (id: string, payload: WebhookTriggerNodeType) => {const { t } = useTranslation(['appDebug'])const { nodesReadOnly: readOnly } = useNodesReadOnly()const { inputs, setInputs } = useNodeCrud<WebhookTriggerNodeType>(id, payload)- const { appId } = useParams<{ appId?: string }>()+ const appId = useAtomValue(editorAppIdAtom)const queryClient = useQueryClient()const { isVarUsedInNodes, removeUsedVarInNodes } = useWorkflow()diff --git a/web/app/components/workflow/nodes/variable-assigner/__tests__/hooks.spec.ts b/web/app/components/workflow/nodes/variable-assigner/__tests__/hooks.spec.tsindex 2a2cd77df0f..9bb2ed5f1f8 100644--- a/web/app/components/workflow/nodes/variable-assigner/__tests__/hooks.spec.ts+++ b/web/app/components/workflow/nodes/variable-assigner/__tests__/hooks.spec.ts@@ -1,5 +1,6 @@-import { act, renderHook } from '@testing-library/react'-import { FlowType } from '@/types/common'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'+import { act } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { VarType } from '../../../types'import { useGetAvailableVars, useVariableAssigner } from '../hooks'@@ -11,7 +12,7 @@ const mockUseWorkflowVariables = vi.hoisted(() => vi.fn())const mockUseIsChatMode = vi.hoisted(() => vi.fn())const mockUseWorkflowStore = vi.hoisted(() => vi.fn())const mockFlowType = vi.hoisted(() => ({- value: undefined as FlowType | undefined,+ value: undefined as EditorResource['kind'] | undefined,}))vi.mock('reactflow', () => ({@@ -34,7 +35,6 @@ vi.mock('../../../hooks/use-workflow', async (importOriginal) => {return {...actual,useWorkflow: () => mockUseWorkflow(),- useIsChatMode: () => mockUseIsChatMode(),}})@@ -52,10 +52,12 @@ vi.mock('@/app/components/workflow/store', () => ({}))vi.mock('@/app/components/workflow/hooks-store/store', () => ({- useHooksStore: (selector: (state: { configsMap?: { flowType?: FlowType } }) => unknown) =>+ useHooksStore: (+ selector: (state: { configsMap?: { resourceKind?: EditorResource['kind'] } }) => unknown,+ ) =>selector({configsMap: {- flowType: mockFlowType.value,+ resourceKind: mockFlowType.value,},}),}))@@ -115,7 +117,9 @@ describe('variable-assigner/hooks', () => {})it('should append target variables, ignore duplicates, and update grouped variables', () => {- const { result } = renderHook(() => useVariableAssigner())+ const { result } = renderHook(() => useVariableAssigner(), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleAssignVariableValueChange('assigner-1', ['start', 'bar'], {@@ -186,7 +190,9 @@ describe('variable-assigner/hooks', () => {},])- const { result } = renderHook(() => useVariableAssigner())+ const { result } = renderHook(() => useVariableAssigner(), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleAddVariableInAddVariablePopupWithPosition(@@ -232,7 +238,9 @@ describe('variable-assigner/hooks', () => {})it('should update the hovered group state on enter and leave', () => {- const { result } = renderHook(() => useVariableAssigner())+ const { result } = renderHook(() => useVariableAssigner(), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleGroupItemMouseEnter('group-1')@@ -286,7 +294,9 @@ describe('variable-assigner/hooks', () => {getNodeAvailableVars,})- const { result } = renderHook(() => useGetAvailableVars())+ const { result } = renderHook(() => useGetAvailableVars(), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })expect(result.current('current-node', 'target', () => true, true)).toEqual([{@@ -304,7 +314,6 @@ describe('variable-assigner/hooks', () => {})it('should filter system variables when the current flow is a snippet', () => {- mockFlowType.value = FlowType.snippetmockUseNodes.mockReturnValue([{id: 'current-node',@@ -328,7 +337,9 @@ describe('variable-assigner/hooks', () => {getNodeAvailableVars,})- const { result } = renderHook(() => useGetAvailableVars())+ const { result } = renderHook(() => useGetAvailableVars(), {+ resource: { kind: 'snippet', snippetId: 'snippet-1' },+ })expect(result.current('current-node', 'target', () => true, false)).toEqual([{@@ -338,3 +349,10 @@ describe('variable-assigner/hooks', () => {])})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockUseIsChatMode()) }+})diff --git a/web/app/components/workflow/nodes/variable-assigner/hooks.ts b/web/app/components/workflow/nodes/variable-assigner/hooks.tsindex 9ebcee4d8a7..5097c94d6ec 100644--- a/web/app/components/workflow/nodes/variable-assigner/hooks.ts+++ b/web/app/components/workflow/nodes/variable-assigner/hooks.ts@@ -2,15 +2,18 @@ import type { Node, ValueSelector, Var } from '../../types'import type { VarGroupItem, VariableAssignerNodeType } from './types'import { uniqBy } from 'es-toolkit/compat'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useNodes, useStoreApi } from 'reactflow'-import { FlowType } from '@/types/common'-import { useHooksStore } from '../../hooks-store/store'+import {+ editorResourceKindAtom,+ isChatflowAtom,+} from '@/app/components/workflow/editor-resource/state'import { useNodeDataUpdate } from '../../hooks/use-node-data-update'-import { useIsChatMode, useWorkflow } from '../../hooks/use-workflow'+import { useWorkflow } from '../../hooks/use-workflow'import { useWorkflowVariables } from '../../hooks/use-workflow-variables'import { useWorkflowStore } from '../../store'-import { filterSnippetSystemVars, isSnippetCanvas } from '../_base/hooks/snippet-input-field-vars'+import { filterSnippetSystemVars } from '../_base/hooks/snippet-input-field-vars'export const useVariableAssigner = () => {const store = useStoreApi()@@ -126,9 +129,8 @@ export const useGetAvailableVars = () => {const nodes: Node[] = useNodes()const { getBeforeNodesInSameBranchIncludeParent } = useWorkflow()const { getNodeAvailableVars } = useWorkflowVariables()- const isChatMode = useIsChatMode()- const isSnippetFlow =- useHooksStore((s) => s.configsMap?.flowType) === FlowType.snippet || isSnippetCanvas()+ const isChatflow = useAtomValue(isChatflowAtom)+ const isSnippetFlow = useAtomValue(editorResourceKindAtom) === 'snippet'const getAvailableVars = useCallback((nodeId: string, handleId: string, filterVar: (v: Var) => boolean, hideEnv = false) => {const availableNodes: Node[] = []@@ -143,7 +145,7 @@ export const useGetAvailableVars = () => {const availableVars = getNodeAvailableVars({parentNode,beforeNodes: uniqBy(availableNodes, 'id').filter((node) => node.id !== nodeId),- isChatMode,+ isChatflow,hideEnv,hideChatVar: false,filterVar,@@ -163,7 +165,7 @@ export const useGetAvailableVars = () => {getNodeAvailableVars({parentNode,beforeNodes: uniqBy(availableNodes, 'id').filter((node) => node.id !== nodeId),- isChatMode,+ isChatflow,filterVar,}),isSnippetFlow,@@ -173,7 +175,7 @@ export const useGetAvailableVars = () => {nodes,getBeforeNodesInSameBranchIncludeParent,getNodeAvailableVars,- isChatMode,+ isChatflow,isSnippetFlow,],)diff --git a/web/app/components/workflow/operator/__tests__/add-block.spec.tsx b/web/app/components/workflow/operator/__tests__/add-block.spec.tsxindex 6a08533e79e..c2b71d70919 100644--- a/web/app/components/workflow/operator/__tests__/add-block.spec.tsx+++ b/web/app/components/workflow/operator/__tests__/add-block.spec.tsx@@ -1,7 +1,7 @@import type { NodeDefault } from '../../types'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { FlowType } from '@/types/common'import { createNode } from '../../__tests__/fixtures'import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'import { BlockClassification } from '../../block-selector/types'@@ -29,7 +29,7 @@ const {let mockNodesReadOnly = falselet mockIsChatMode = false-let mockFlowType: FlowType = FlowType.appFlow+let mockFlowType: EditorResource['kind'] = 'app'const answerBlock: NodeDefault = {metaData: {@@ -55,7 +55,6 @@ vi.mock('../../hooks/use-available-blocks', () => ({}))vi.mock('../../hooks/use-workflow', () => ({- useIsChatMode: () => mockIsChatMode,useNodesReadOnly: () => ({ nodesReadOnly: mockNodesReadOnly }),}))@@ -74,7 +73,7 @@ vi.mock('../../hooks/use-panel-interactions', () => ({vi.mock('../../hooks-store', () => ({useHooksStore: (selector: (state: Record<string, unknown>) => unknown) =>selector({- configsMap: { flowType: mockFlowType },+ configsMap: { resourceKind: mockFlowType },availableNodesMetaData: { nodes: [answerBlock] },}),}))@@ -125,7 +124,7 @@ describe('AddBlock', () => {vi.clearAllMocks()mockNodesReadOnly = falsemockIsChatMode = false- mockFlowType = FlowType.appFlow+ mockFlowType = 'app'})it('opens the real selector and exposes its open state', async () => {@@ -198,3 +197,10 @@ describe('AddBlock', () => {})})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockIsChatMode) }+})diff --git a/web/app/components/workflow/operator/__tests__/export-image.spec.tsx b/web/app/components/workflow/operator/__tests__/export-image.spec.tsxindex 24d6dc1d806..f6f05a62602 100644--- a/web/app/components/workflow/operator/__tests__/export-image.spec.tsx+++ b/web/app/components/workflow/operator/__tests__/export-image.spec.tsx@@ -1,6 +1,9 @@-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import { fireEvent, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { act } from 'react'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'+import { createConsoleQueryClient, seedAppDetail } from '@/test/console/query-data'+import { createAppDetailFixture } from '@/test/fixtures/app'import { ExportImage } from '../export-image'const mockToPng = vi.fn()@@ -61,6 +64,15 @@ vi.mock('@/app/components/base/image-uploader/image-preview', () => ({),}))+function createExportQueryClient() {+ const queryClient = createConsoleQueryClient()+ seedAppDetail(+ queryClient,+ createAppDetailFixture({ id: 'app-1', mode: 'workflow', name: mockWorkflowState.appName }),+ )+ return queryClient+}+describe('ExportImage', () => {beforeEach(() => {vi.clearAllMocks()@@ -81,7 +93,10 @@ describe('ExportImage', () => {it('opens the menu and exports the current view as png', async () => {const user = userEvent.setup()- render(<ExportImage />)+ render(<ExportImage />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ queryClient: createExportQueryClient(),+ })await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))const menu = screen.getByRole('menu', { name: 'workflow.common.exportImage' })@@ -114,7 +129,10 @@ describe('ExportImage', () => {const user = userEvent.setup()mockGetNodesReadOnly.mockReturnValue(true)- render(<ExportImage />)+ render(<ExportImage />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ queryClient: createExportQueryClient(),+ })const trigger = screen.getByRole('button', { name: 'workflow.common.exportImage' })expect(trigger).toHaveAttribute('aria-disabled', 'true')@@ -129,7 +147,10 @@ describe('ExportImage', () => {it('shows a preview when exporting the whole workflow', async () => {vi.useFakeTimers()- render(<ExportImage />)+ render(<ExportImage />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ queryClient: createExportQueryClient(),+ })fireEvent.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))fireEvent.click(screen.getAllByText('workflow.common.exportPNG')[1]!)@@ -154,7 +175,10 @@ describe('ExportImage', () => {])('exports the current view with %s', async (label, exporter, fileName) => {const user = userEvent.setup()- render(<ExportImage />)+ render(<ExportImage />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ queryClient: createExportQueryClient(),+ })await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))await user.click(screen.getAllByText(label)[0]!)@@ -171,7 +195,10 @@ describe('ExportImage', () => {it('exports the whole workflow as svg', async () => {vi.useFakeTimers()- render(<ExportImage />)+ render(<ExportImage />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ queryClient: createExportQueryClient(),+ })fireEvent.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))fireEvent.click(screen.getAllByText('workflow.common.exportSVG')[1]!)@@ -187,12 +214,39 @@ describe('ExportImage', () => {expect(screen.getByTestId('image-preview')).toHaveTextContent('Demo App-whole-workflow.svg')})+ it('uses the refreshed App name when exporting without restarting the editor', async () => {+ const user = userEvent.setup()+ const queryClient = createExportQueryClient()+ render(<ExportImage />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ queryClient,+ })+ await act(async () => {+ seedAppDetail(+ queryClient,+ createAppDetailFixture({ id: 'app-1', mode: 'workflow', name: 'Renamed App' }),+ )+ })+ await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))+ const group = screen.getByRole('group', { name: 'workflow.common.currentView' })+ await user.click(within(group).getByRole('menuitem', { name: 'workflow.common.exportPNG' }))+ await waitFor(() =>+ expect(mockDownloadUrl).toHaveBeenCalledWith({+ url: 'data:image/png;base64,current',+ fileName: 'Renamed App.png',+ }),+ )+ })+it('returns early when there is no app or knowledge name', async () => {const user = userEvent.setup()mockWorkflowState.appName = ''mockWorkflowState.knowledgeName = ''- render(<ExportImage />)+ render(<ExportImage />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ queryClient: createExportQueryClient(),+ })await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))await user.click(screen.getAllByText('workflow.common.exportPNG')[0]!)@@ -205,7 +259,10 @@ describe('ExportImage', () => {const user = userEvent.setup()document.querySelector('.react-flow__viewport')?.remove()- render(<ExportImage />)+ render(<ExportImage />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ queryClient: createExportQueryClient(),+ })await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))await user.click(screen.getAllByText('workflow.common.exportPNG')[0]!)@@ -217,7 +274,10 @@ describe('ExportImage', () => {it('returns early when the workflow becomes read only before exporting', async () => {const user = userEvent.setup()- render(<ExportImage />)+ render(<ExportImage />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ queryClient: createExportQueryClient(),+ })await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))mockGetNodesReadOnly.mockReturnValue(true)@@ -232,7 +292,10 @@ describe('ExportImage', () => {const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})mockToJpeg.mockRejectedValueOnce(new Error('boom'))- render(<ExportImage />)+ render(<ExportImage />, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ queryClient: createExportQueryClient(),+ })await user.click(screen.getByRole('button', { name: 'workflow.common.exportImage' }))await user.click(screen.getAllByText('workflow.common.exportJPEG')[0]!)diff --git a/web/app/components/workflow/operator/add-block.tsx b/web/app/components/workflow/operator/add-block.tsxindex dc9246a266a..bd3228b7bdc 100644--- a/web/app/components/workflow/operator/add-block.tsx+++ b/web/app/components/workflow/operator/add-block.tsx@@ -1,17 +1,20 @@import type { BlockSelectorProps } from '@/app/components/workflow/block-selector'import type { Node, OnSelectBlock } from '@/app/components/workflow/types'import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useAtomValue } from 'jotai'import { memo, useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import { useStoreApi } from 'reactflow'import BlockSelector from '@/app/components/workflow/block-selector'+import {+ editorResourceKindAtom,+ isChatflowAtom,+} from '@/app/components/workflow/editor-resource/state'import { BlockEnum } from '@/app/components/workflow/types'-import { FlowType } from '@/types/common'-import { useHooksStore } from '../hooks-store'import { useAvailableBlocks } from '../hooks/use-available-blocks'import { useNodesMetaData } from '../hooks/use-nodes-meta-data'import { usePanelInteractions } from '../hooks/use-panel-interactions'-import { useIsChatMode, useNodesReadOnly } from '../hooks/use-workflow'+import { useNodesReadOnly } from '../hooks/use-workflow'import { useWorkflowStore } from '../store'import {generateNewNode,@@ -34,17 +37,17 @@ const AddBlock = ({onClose,isolateKeyboardEvents,}: AddBlockProps) => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const store = useStoreApi()const workflowStore = useWorkflowStore()- const isChatMode = useIsChatMode()+ const isChatflow = useAtomValue(isChatflowAtom)const { nodesReadOnly } = useNodesReadOnly()const { handlePaneContextmenuCancel } = usePanelInteractions()const [open, setOpen] = useState(false)const { availableNextBlocks } = useAvailableBlocks(BlockEnum.Start, false)const { nodesMap: nodesMetaDataMap } = useNodesMetaData()- const flowType = useHooksStore((s) => s.configsMap?.flowType)- const showStartTab = flowType !== FlowType.ragPipeline && !isChatMode+ const resourceKind = useAtomValue(editorResourceKindAtom)+ const showStartTab = resourceKind !== 'knowledge-pipeline' && !isChatflowconst handleOpenChange = useCallback((open: boolean) => {diff --git a/web/app/components/workflow/operator/export-image.tsx b/web/app/components/workflow/operator/export-image.tsxindex 93de442d83b..8f4d4925ce3 100644--- a/web/app/components/workflow/operator/export-image.tsx+++ b/web/app/components/workflow/operator/export-image.tsx@@ -8,25 +8,35 @@ import {DropdownMenuTrigger,} from '@langgenius/dify-ui/dropdown-menu'import { IconButton } from '@langgenius/dify-ui/icon-button'+import { skipToken, useQuery } from '@tanstack/react-query'import { toJpeg, toPng, toSvg } from 'html-to-image'+import { useAtomValue } from 'jotai'import { memo, useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import { getNodesBounds, useReactFlow } from 'reactflow'import ImagePreview from '@/app/components/base/image-uploader/image-preview'+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'import { useStore } from '@/app/components/workflow/store'+import { consoleQuery } from '@/service/console'import { downloadUrl } from '@/utils/download'import { useNodesReadOnly } from '../hooks/use-workflow'import TipPopup from './tip-popup'const ExportImage = memo(() => {- const { t } = useTranslation(['workflow'])+ const { t } = useTranslation(['workflow'] as const)const { getNodesReadOnly } = useNodesReadOnly()const reactFlow = useReactFlow()const [previewUrl, setPreviewUrl] = useState('')const [previewTitle, setPreviewTitle] = useState('')const knowledgeName = useStore((s) => s.knowledgeName)- const appName = useStore((s) => s.appName)+ const appId = useAtomValue(editorAppIdAtom)+ const { data: appName } = useQuery(+ consoleQuery.apps.byAppId.get.queryOptions({+ input: appId ? { params: { app_id: appId } } : skipToken,+ select: (app) => app.name,+ }),+ )const isReadOnly = getNodesReadOnly()const handleExportImage = useCallback(diff --git a/web/app/components/workflow/panel-contextmenu.tsx b/web/app/components/workflow/panel-contextmenu.tsxindex d56d48044b6..6702e3695dd 100644--- a/web/app/components/workflow/panel-contextmenu.tsx+++ b/web/app/components/workflow/panel-contextmenu.tsx@@ -5,17 +5,19 @@ import {ContextMenuItem,ContextMenuSeparator,} from '@langgenius/dify-ui/context-menu'+import { useAtomValue } from 'jotai'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'-import { FlowType } from '@/types/common'+import {+ editorResourceKindAtom,+ isChatflowAtom,+} from '@/app/components/workflow/editor-resource/state'import { useHooksStore } from './hooks-store'import { useDSL } from './hooks/use-DSL'import { useNodesInteractions } from './hooks/use-nodes-interactions'-import { useIsChatMode } from './hooks/use-workflow'import { useWorkflowMoveMode } from './hooks/use-workflow-panel-interactions'import { useWorkflowStartRun } from './hooks/use-workflow-start-run'import { TEST_RUN_MENU_HOTKEY } from './hotkeys'-import { isSnippetCanvas } from './nodes/_base/hooks/snippet-input-field-vars'import AddBlock from './operator/add-block'import { useOperator } from './operator/hooks'import { handleWorkflowMenuKeyDown } from './shortcuts/handle-workflow-menu-key-down'@@ -40,8 +42,8 @@ export function PanelContextmenu({ onClose }: { onClose: () => void }) {const { isCommentModeAvailable } = useWorkflowMoveMode()const { exportCheck } = useDSL()const accessControl = useHooksStore((s) => s.accessControl)- const flowType = useHooksStore((s) => s.configsMap?.flowType)- const isChatMode = useIsChatMode()+ const resourceKind = useAtomValue(editorResourceKindAtom)+ const isChatflow = useAtomValue(isChatflowAtom)const workflowOperationReadOnly = !!(workflowRunningData?.result.status === WorkflowRunningStatus.Running ||workflowRunningData?.result.status === WorkflowRunningStatus.Paused ||@@ -49,7 +51,7 @@ export function PanelContextmenu({ onClose }: { onClose: () => void }) {isRestoring)const canEditWorkflow = accessControl.canEdit && !workflowOperationReadOnly- const shouldHideImportApp = flowType === FlowType.snippet || isSnippetCanvas()+ const shouldHideImportApp = resourceKind === 'snippet'const addBlockTrigger = (<ContextMenuItem@@ -66,11 +68,11 @@ export function PanelContextmenu({ onClose }: { onClose: () => void }) {)const handleRunAction = useCallback(() => {- if (isChatMode) handleWorkflowStartRunInChatflow()+ if (isChatflow) handleWorkflowStartRunInChatflow()else handleStartWorkflowRun()onClose()- }, [isChatMode, handleWorkflowStartRunInChatflow, handleStartWorkflowRun, onClose])+ }, [isChatflow, handleWorkflowStartRunInChatflow, handleStartWorkflowRun, onClose])if (!isPanelContextMenu) return null@@ -137,10 +139,10 @@ export function PanelContextmenu({ onClose }: { onClose: () => void }) {className="justify-between gap-4 px-3 text-text-secondary"onClick={handleRunAction}>- {isChatMode+ {isChatflow? t(($) => $['common.debugAndPreview'], { ns: 'workflow' }): t(($) => $['common.run'], { ns: 'workflow' })}- {!isChatMode && <ShortcutKbd hotkey={TEST_RUN_MENU_HOTKEY} />}+ {!isChatflow && <ShortcutKbd hotkey={TEST_RUN_MENU_HOTKEY} />}</ContextMenuItem>)}</ContextMenuGroup>diff --git a/web/app/components/workflow/panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/__tests__/index.spec.tsxindex 942608cead5..fc79d1ab971 100644--- a/web/app/components/workflow/panel/__tests__/index.spec.tsx+++ b/web/app/components/workflow/panel/__tests__/index.spec.tsx@@ -199,7 +199,6 @@ describe('Panel', () => {}}versionHistoryPanelProps={{latestVersionId: 'version-1',- restoreVersionUrl: (versionId) => `/apps/app-1/workflows/${versionId}/restore`,}}/>,)diff --git a/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx b/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsxindex d9f340afe1d..41145508890 100644--- a/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx+++ b/web/app/components/workflow/panel/__tests__/inputs-panel.spec.tsx@@ -4,7 +4,6 @@ import type { FileUpload } from '@/app/components/base/features/types'import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { TransferMethod } from '@/types/app'-import { FlowType } from '@/types/common'import { createStartNode } from '../../__tests__/fixtures'import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'import { InputVarType, WorkflowRunningStatus } from '../../types'@@ -56,11 +55,7 @@ const createHooksStoreProps = (overrides: Partial<HooksStoreShape> = {},): Partial<HooksStoreShape> => ({handleRun: vi.fn(),- configsMap: {- flowId: 'flow-1',- flowType: FlowType.appFlow,- fileSettings: fileSettingsWithImage,- },+ fileSettings: fileSettingsWithImage,...overrides,})@@ -236,12 +231,8 @@ describe('InputsPanel', () => {},hooksStoreProps: createHooksStoreProps({handleRun,- configsMap: {- flowId: 'flow-1',- flowType: FlowType.appFlow,- fileSettings: {- enabled: false,- },+ fileSettings: {+ enabled: false,},}),},@@ -268,12 +259,8 @@ describe('InputsPanel', () => {files: [uploadingRunFile],},hooksStoreProps: createHooksStoreProps({- configsMap: {- flowId: 'flow-1',- flowType: FlowType.appFlow,- fileSettings: {- enabled: false,- },+ fileSettings: {+ enabled: false,},}),})diff --git a/web/app/components/workflow/panel/chat-record/__tests__/index.spec.tsx b/web/app/components/workflow/panel/chat-record/__tests__/index.spec.tsxindex 3ddb5175827..53bd6d88bdc 100644--- a/web/app/components/workflow/panel/chat-record/__tests__/index.spec.tsx+++ b/web/app/components/workflow/panel/chat-record/__tests__/index.spec.tsx@@ -2,16 +2,11 @@ import type { HistoryWorkflowData } from '@/app/components/workflow/types'import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'+import { EditorResourceScope } from '@/app/components/workflow/editor-resource/provider'import ChatRecord from '../index'-const routeParams = vi.hoisted(() => ({ appId: 'app-1' }))const mockRequest = vi.hoisted(() => vi.fn())-vi.mock('@/next/navigation', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/next/navigation')>()),- useParams: () => routeParams,-}))-vi.mock('@/service/console/browser', () => ({consoleBrowserLink: { call: mockRequest },}))@@ -25,7 +20,6 @@ const historyWorkflowData: HistoryWorkflowData = {describe('ChatRecord', () => {beforeEach(() => {- routeParams.appId = 'app-1'mockRequest.mockReset()})@@ -116,17 +110,22 @@ describe('ChatRecord', () => {has_more: false,limit: 20,})- const { store } = renderWorkflowComponent(<ChatRecord />, {+ const view = (appId: string) => (+ <EditorResourceScope resource={{ kind: 'app', appId, mode: 'workflow' }}>+ <ChatRecord />+ </EditorResourceScope>+ )+ const { store, rerender } = renderWorkflowComponent(view('app-1'), {initialStoreState: { historyWorkflowData },})await waitFor(() => expect(mockRequest).toHaveBeenCalledTimes(1))- routeParams.appId = 'app-2'act(() => {store.setState({historyWorkflowData: { ...historyWorkflowData, conversation_id: 'conversation-2' },})})+ rerender(view('app-2'))expect(await screen.findByText('Current answer')).toBeInTheDocument()expect(mockRequest).toHaveBeenLastCalledWith(['apps', 'byAppId', 'chatMessages', 'get'],diff --git a/web/app/components/workflow/panel/chat-record/index.tsx b/web/app/components/workflow/panel/chat-record/index.tsxindex ef661afdd85..3d3158ede71 100644--- a/web/app/components/workflow/panel/chat-record/index.tsx+++ b/web/app/components/workflow/panel/chat-record/index.tsx@@ -2,12 +2,13 @@ import type { IChatItem } from '@/app/components/base/chat/chat/type'import type { ChatItem } from '@/app/components/base/chat/types'import { RiCloseLine } from '@remixicon/react'import { skipToken, useQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { memo, useMemo, useState } from 'react'import Chat from '@/app/components/base/chat/chat'import { buildChatItemTree, getThreadMessages } from '@/app/components/base/chat/utils'import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'-import { useParams } from '@/next/navigation'+import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { consoleQuery } from '@/service/console'import { useWorkflowRun } from '../../hooks/use-workflow-run'import { useStore, useWorkflowStore } from '../../store'@@ -49,7 +50,7 @@ function getFormattedChatList(messages: any[]) {}const ChatRecord = () => {- const { appId } = useParams<{ appId: string }>()+ const { appId } = useAtomValue(workflowAppIdentityAtom)const [selectedMessage, setSelectedMessage] = useState<{appId: stringconversationId: string | undefineddiff --git a/web/app/components/workflow/panel/chat-variable-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/chat-variable-panel/__tests__/index.spec.tsxindex 51979764356..d3081ebeb95 100644--- a/web/app/components/workflow/panel/chat-variable-panel/__tests__/index.spec.tsx+++ b/web/app/components/workflow/panel/chat-variable-panel/__tests__/index.spec.tsx@@ -1,6 +1,7 @@import type { ConversationVariable, Node } from '@/app/components/workflow/types'-import { render, screen, waitFor } from '@testing-library/react'+import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import ChatVariablePanel from '../index'import { ChatVarType } from '../type'@@ -197,7 +198,7 @@ describe('ChatVariablePanel', () => {it('should toggle the tips area and close the panel', async () => {const user = userEvent.setup()- render(<ChatVariablePanel />)+ render(<ChatVariablePanel />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })expect(screen.getByText('workflow.chatVariable.panelDescription')).toBeInTheDocument()@@ -222,7 +223,7 @@ describe('ChatVariablePanel', () => {it('should prepend newly added variables and sync the workflow draft', async () => {const user = userEvent.setup()- render(<ChatVariablePanel />)+ render(<ChatVariablePanel />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })await user.click(screen.getByRole('button', { name: 'save-add' }))@@ -250,7 +251,7 @@ describe('ChatVariablePanel', () => {mockFindUsedVarNodes.mockReturnValue([effectedNode])mockUpdateNodeVars.mockReturnValue(updatedNode)- render(<ChatVariablePanel />)+ render(<ChatVariablePanel />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })await user.click(screen.getByRole('button', { name: 'edit-conversation_var' }))await user.click(screen.getByRole('button', { name: 'save-edit' }))@@ -275,7 +276,7 @@ describe('ChatVariablePanel', () => {mockFindUsedVarNodes.mockReturnValue([effectedNode])mockUpdateNodeVars.mockReturnValue(prunedNode)- render(<ChatVariablePanel />)+ render(<ChatVariablePanel />, { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } })await user.click(screen.getByRole('button', { name: 'delete-conversation_var' }))expect(screen.getByTestId('remove-effect-var-confirm')).toBeInTheDocument()diff --git a/web/app/components/workflow/panel/chat-variable-panel/index.tsx b/web/app/components/workflow/panel/chat-variable-panel/index.tsxindex aac7cd50114..3098ae20742 100644--- a/web/app/components/workflow/panel/chat-variable-panel/index.tsx+++ b/web/app/components/workflow/panel/chat-variable-panel/index.tsx@@ -2,10 +2,12 @@ import type { ConversationVariable } from '@/app/components/workflow/types'import { cn } from '@langgenius/dify-ui/cn'import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible'import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useAtomValue } from 'jotai'import { memo, useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import BlockIcon from '@/app/components/workflow/block-icon'import { webSocketClient } from '@/app/components/workflow/collaboration/core/websocket-manager'+import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'import RemoveEffectVarConfirm from '@/app/components/workflow/nodes/_base/components/remove-effect-var-confirm'import {findUsedVarNodes,@@ -25,7 +27,7 @@ const ChatVariablePanel = () => {const varList = useStore((s) => s.conversationVariables) as ConversationVariable[]const updateChatVarList = useStore((s) => s.setConversationVariables)const setControlPromptEditorRerenderKey = useStore((s) => s.setControlPromptEditorRerenderKey)- const appId = useStore((s) => s.appId) as string+ const { appId } = useAtomValue(workflowAppIdentityAtom)const { invalidateConversationVarValues } = useInspectVarsCrud()const [showTip, setShowTip] = useState(true)diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx b/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsxindex 7e769acb35d..85a0c94fe49 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx@@ -13,14 +13,8 @@ import ChatWrapper from '../chat-wrapper'const mockUseChat = vi.hoisted(() => vi.fn())const mockUseSubscription = vi.hoisted(() => vi.fn())-const routeParams = vi.hoisted(() => ({ appId: 'app-1' }))const mockRequest = vi.hoisted(() => vi.fn())-vi.mock('@/next/navigation', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/next/navigation')>()),- useParams: () => routeParams,-}))-vi.mock('@/service/console/browser', () => ({consoleBrowserLink: { call: mockRequest },}))@@ -164,7 +158,6 @@ const createChatWrapperRef = () =>describe('ChatWrapper', () => {beforeEach(() => {vi.clearAllMocks()- routeParams.appId = 'app-1'mockRequest.mockReset()mockRequest.mockResolvedValue({ data: [] })mockUseChat.mockReturnValue(createChatState())diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx b/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsxindex c7ad62eb3d2..2d307d2a43f 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx@@ -247,8 +247,8 @@ describe('debug-and-preview components', () => {renderWorkflowComponent(<ConversationVariableModal conversationID="conversation-1" onHide={vi.fn()} />,{+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },initialStoreState: {- appId: 'app-1',conversationVariables: [createConversationVariable()],},},@@ -428,8 +428,8 @@ describe('debug-and-preview components', () => {}),],edges: [],+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },initialStoreState: {- appId: 'app-1',conversationVariables: [createConversationVariable()],},},diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/conversation-variable-modal.spec.tsx b/web/app/components/workflow/panel/debug-and-preview/__tests__/conversation-variable-modal.spec.tsxindex 96cd5dca1d9..3f1313bc74e 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/conversation-variable-modal.spec.tsx+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/conversation-variable-modal.spec.tsx@@ -96,8 +96,8 @@ describe('ConversationVariableModal', () => {renderWorkflowComponent(<ConversationVariableModal conversationID="conversation-1" onHide={onHide} />,{+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },initialStoreState: {- appId: 'app-1',conversationVariables: [createConversationVariable(),createConversationVariable({@@ -139,8 +139,8 @@ describe('ConversationVariableModal', () => {renderWorkflowComponent(<ConversationVariableModal conversationID="conversation-1" onHide={vi.fn()} />,{+ resource: { kind: 'app' as const, appId: 'app-1', mode: 'workflow' as const },initialStoreState: {- appId: 'app-1',conversationVariables: [createConversationVariable()],},},diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.tsindex dad3dd59f05..9ce2dbd0098 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.ts+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.ts@@ -1,4 +1,5 @@-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { sseGet } from '@/service/base'import { submitHumanInputForm } from '@/service/workflow'import { useChat } from '../hooks'@@ -21,7 +22,7 @@ vi.mock('@/service/base', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mockInvalidAllLastRun,+ useInvalidateAllLastRun: () => mockInvalidAllLastRun,}))vi.mock('@/service/workflow', () => ({@@ -56,7 +57,7 @@ vi.mock('../../../hooks/use-set-workflow-vars-with-value', () => ({vi.mock('../../../hooks-store', () => ({useHooksStore: () => ({configsMap: {- flowType: 'appFlow',+ resourceKind: 'appFlow',flowId: 'flow-1',},}),@@ -99,7 +100,9 @@ describe('useChat', () => {sendCallbacks = callbacks})- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'test' }, {})@@ -133,7 +136,9 @@ describe('useChat', () => {})it('submits human input forms through the workflow service', async () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleSubmitHumanInputForm('token-123', {@@ -153,7 +158,9 @@ describe('useChat', () => {const node = { id: 'node-1', type: 'custom', data: { title: 'Human Input' } }mockGetNodes.mockReturnValue([node, { id: 'node-2', type: 'custom', data: { title: 'Other' } }])- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })expect(result.current.getHumanInputNodeData('node-1')).toEqual(node)expect(result.current.getHumanInputNodeData('missing')).toBeUndefined()diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.tsindex 7974b447d6a..48925586011 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts@@ -1,5 +1,6 @@import type { ChatItemInTree } from '@/app/components/base/chat/types'-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { useChat } from '../../hooks'const mockHandleRun = vi.fn()@@ -19,7 +20,7 @@ vi.mock('@/service/base', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mockInvalidAllLastRun,+ useInvalidateAllLastRun: () => mockInvalidAllLastRun,}))vi.mock('@/service/workflow', () => ({@@ -90,7 +91,9 @@ describe('useChat – handleResume', () => {capturedResumeOptions = options})- const hook = renderHook(() => useChat({}))+ const hook = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {hook.result.current.handleSend({ query: 'test' }, {})@@ -117,7 +120,9 @@ describe('useChat – handleResume', () => {}it('should call sseGet with the correct URL', () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleResume('msg-1', 'wfr-1', {})@@ -136,7 +141,9 @@ describe('useChat – handleResume', () => {options.getAbortController(mockAbortCtrl)})- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleResume('msg-1', 'wfr-1', {})@@ -161,7 +168,9 @@ describe('useChat – handleResume', () => {sendCallbacks = callbacks})- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'test' }, {})@@ -203,7 +212,9 @@ describe('useChat – handleResume', () => {capturedResumeOptions = options})- const hook = renderHook(() => useChat({}))+ const hook = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {hook.result.current.handleSend({ query: 'test' }, {})@@ -380,8 +391,9 @@ describe('useChat – handleResume', () => {capturedResumeOptions = options})- const hook = renderHook(() =>- useChat({ suggested_questions_after_answer: { enabled: true } }),+ const hook = renderHook(+ () => useChat({ suggested_questions_after_answer: { enabled: true } }),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)act(() => {@@ -430,8 +442,9 @@ describe('useChat – handleResume', () => {capturedResumeOptions = options})- const hook = renderHook(() =>- useChat({ suggested_questions_after_answer: { enabled: true } }),+ const hook = renderHook(+ () => useChat({ suggested_questions_after_answer: { enabled: true } }),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)act(() => {@@ -474,8 +487,9 @@ describe('useChat – handleResume', () => {capturedResumeOptions = options})- const hook = renderHook(() =>- useChat({ suggested_questions_after_answer: { enabled: true } }),+ const hook = renderHook(+ () => useChat({ suggested_questions_after_answer: { enabled: true } }),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)act(() => {@@ -941,7 +955,9 @@ describe('useChat – handleResume with bare prevChatTree (no humanInputFormData},]- const hook = renderHook(() => useChat({}, undefined, prevChatTree))+ const hook = renderHook(() => useChat({}, undefined, prevChatTree), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {hook.result.current.handleResume('bare-msg', 'wfr-bare', {})@@ -972,7 +988,9 @@ describe('useChat – handleResume with bare prevChatTree (no humanInputFormData},]- const hook = renderHook(() => useChat({}, undefined, prevChatTree))+ const hook = renderHook(() => useChat({}, undefined, prevChatTree), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {hook.result.current.handleResume('bare-msg-nt', 'wfr-bare-nt', {})@@ -1102,7 +1120,9 @@ describe('useChat – handleResume with bare prevChatTree (no humanInputFormData},]- const hook = renderHook(() => useChat({}, undefined, prevChatTreeNoWP))+ const hook = renderHook(() => useChat({}, undefined, prevChatTreeNoWP), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })let opts: anymockSseGet.mockImplementation((_url: any, _opts: any, options: any) => {opts = optionsdiff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.tsindex 1fed2813aa6..23d075f5647 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts@@ -1,4 +1,5 @@-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { useChat } from '../../hooks'const mockHandleRun = vi.fn()@@ -21,7 +22,7 @@ vi.mock('@/service/base', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mockInvalidAllLastRun,+ useInvalidateAllLastRun: () => mockInvalidAllLastRun,}))vi.mock('@/service/workflow', () => ({@@ -90,7 +91,9 @@ describe('useChat – handleSend', () => {})it('should call handleRun with processed params', () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'hello', inputs: {} }, {})@@ -103,7 +106,9 @@ describe('useChat – handleSend', () => {it('should return false and skip handleRun when test/run permission is missing', () => {mockHooksStoreState.canRun = false- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })let returned: unknownact(() => {@@ -118,7 +123,9 @@ describe('useChat – handleSend', () => {it('should show notification and return false when already responding', () => {mockHandleRun.mockImplementation(() => {})- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'first' }, {})@@ -133,7 +140,9 @@ describe('useChat – handleSend', () => {})it('should set isResponding to true after sending', () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'hello' }, {})})@@ -141,7 +150,9 @@ describe('useChat – handleSend', () => {})it('should add placeholder question and answer to chatList', () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'test question' }, {})@@ -158,7 +169,9 @@ describe('useChat – handleSend', () => {})it('should strip url from local_file transfer method files', () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend(@@ -208,7 +221,9 @@ describe('useChat – handleSend', () => {callbacks.onCompleted(false)})- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'first' }, {})diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.tsindex e5d5c58e010..70cbc2383aa 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts@@ -1,4 +1,5 @@-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { useChat } from '../../hooks'const mockHandleRun = vi.fn()@@ -19,7 +20,7 @@ vi.mock('@/service/base', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mockInvalidAllLastRun,+ useInvalidateAllLastRun: () => mockInvalidAllLastRun,}))vi.mock('@/service/workflow', () => ({@@ -78,7 +79,9 @@ describe('useChat – handleStop', () => {})it('should set isResponding to false', () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleStop()})@@ -86,7 +89,9 @@ describe('useChat – handleStop', () => {})it('should not call stopChat when taskId is empty even if stopChat is provided', () => {- const { result } = renderHook(() => useChat({}, undefined, undefined, mockStopChat))+ const { result } = renderHook(() => useChat({}, undefined, undefined, mockStopChat), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleStop()})@@ -94,7 +99,9 @@ describe('useChat – handleStop', () => {})it('should reset iter/loop times to defaults', () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleStop()})@@ -108,7 +115,9 @@ describe('useChat – handleStop', () => {callbacks.getAbortController({ abort: mockWfAbort } as any)})- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'test' }, {})@@ -136,8 +145,9 @@ describe('useChat – handleStop', () => {return Promise.resolve({ data: ['s'] })})- const { result } = renderHook(() =>- useChat({ suggested_questions_after_answer: { enabled: true } }),+ const { result } = renderHook(+ () => useChat({ suggested_questions_after_answer: { enabled: true } }),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)act(() => {@@ -169,7 +179,9 @@ describe('useChat – handleStop', () => {})})- const { result } = renderHook(() => useChat({}, undefined, undefined, mockStopChat))+ const { result } = renderHook(() => useChat({}, undefined, undefined, mockStopChat), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'test' }, {})@@ -190,7 +202,9 @@ describe('useChat – handleRestart', () => {it('should clear suggestedQuestions and set isResponding to false', () => {const config = { opening_statement: 'Hello' }- const { result } = renderHook(() => useChat(config))+ const { result } = renderHook(() => useChat(config), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleRestart()@@ -201,7 +215,9 @@ describe('useChat – handleRestart', () => {})it('should reset iter/loop times to defaults', () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleRestart()})diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.tsindex b35764f3b43..e71f43c5afd 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts@@ -1,5 +1,6 @@import type { ChatItemInTree } from '@/app/components/base/chat/types'-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { useChat } from '../../hooks'const mockHandleRun = vi.fn()@@ -19,7 +20,7 @@ vi.mock('@/service/base', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mockInvalidAllLastRun,+ useInvalidateAllLastRun: () => mockInvalidAllLastRun,}))vi.mock('@/service/workflow', () => ({@@ -86,7 +87,9 @@ describe('useChat – handleSwitchSibling', () => {})mockSseGet.mockImplementation(() => {})- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'test' }, {})@@ -124,7 +127,9 @@ describe('useChat – handleSwitchSibling', () => {sendCallbacks = callbacks})- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'test' }, {})@@ -151,7 +156,9 @@ describe('useChat – handleSwitchSibling', () => {})it('should return undefined from findMessageInTree when not found', () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSwitchSibling('nonexistent-id', {})@@ -167,7 +174,9 @@ describe('useChat – handleSwitchSibling', () => {})mockSseGet.mockImplementation(() => {})- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'parent' }, {})@@ -230,7 +239,9 @@ describe('useChat – handleSubmitHumanInputForm', () => {})it('should call submitHumanInputForm with token and data', async () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })await act(async () => {await result.current.handleSubmitHumanInputForm('token-123', {@@ -259,7 +270,9 @@ describe('useChat – getHumanInputNodeData', () => {{ id: 'node-2', type: 'custom', data: { title: 'Other' } },])- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })const node = result.current.getHumanInputNodeData('node-1')expect(node).toEqual(mockNode)})@@ -267,7 +280,9 @@ describe('useChat – getHumanInputNodeData', () => {it('should return undefined when no matching node', () => {mockGetNodes.mockReturnValue([{ id: 'node-2', type: 'custom', data: {} }])- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })const node = result.current.getHumanInputNodeData('nonexistent')expect(node).toBeUndefined()})@@ -278,7 +293,9 @@ describe('useChat – getHumanInputNodeData', () => {{ id: 'node-1', type: 'custom', data: { found: true } },])- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })const node = result.current.getHumanInputNodeData('node-1')expect(node).toEqual({ id: 'node-1', type: 'custom', data: { found: true } })})@@ -290,7 +307,9 @@ describe('useChat – conversationId and setTargetMessageId', () => {})it('should initially be an empty string', () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })expect(result.current.conversationId).toBe('')})@@ -328,7 +347,9 @@ describe('useChat – conversationId and setTargetMessageId', () => {},]- const { result } = renderHook(() => useChat({}, undefined, prevChatTree))+ const { result } = renderHook(() => useChat({}, undefined, prevChatTree), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })const defaultList = result.current.chatListexpect(defaultList.some((item) => item.id === 'a1')).toBe(true)@@ -363,7 +384,9 @@ describe('useChat – updateCurrentQAOnTree with parent_message_id', () => {})it('should handle follow-up message with parent_message_id', async () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {result.current.handleSend({ query: 'first' }, {})diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.tsindex 84289e0b540..d5e786f029d 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/opening-statement.spec.ts@@ -1,5 +1,5 @@import type { ChatItemInTree } from '@/app/components/base/chat/types'-import { renderHook } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { useChat } from '../../hooks'const mockHandleRun = vi.fn()@@ -19,7 +19,7 @@ vi.mock('@/service/base', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mockInvalidAllLastRun,+ useInvalidateAllLastRun: () => mockInvalidAllLastRun,}))vi.mock('@/service/workflow', () => ({@@ -78,18 +78,24 @@ describe('workflow debug useChat – opening statement stability', () => {})it('should return empty chatList when config has no opening_statement', () => {- const { result } = renderHook(() => useChat({}))+ const { result } = renderHook(() => useChat({}), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })expect(result.current.chatList).toEqual([])})it('should return empty chatList when opening_statement is an empty string', () => {- const { result } = renderHook(() => useChat({ opening_statement: '' }))+ const { result } = renderHook(() => useChat({ opening_statement: '' }), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })expect(result.current.chatList).toEqual([])})it('should use stable id "opening-statement" instead of Date.now()', () => {const config = { opening_statement: 'Welcome!' }- const { result } = renderHook(() => useChat(config))+ const { result } = renderHook(() => useChat(config), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })expect(result.current.chatList[0]!.id).toBe('opening-statement')})@@ -101,6 +107,7 @@ describe('workflow debug useChat – opening statement stability', () => {const formSettings = { inputs: { name: 'Alice' }, inputsForm: [] }const { result, rerender } = renderHook(({ fs }) => useChat(config, fs), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },initialProps: { fs: formSettings },})@@ -120,6 +127,7 @@ describe('workflow debug useChat – opening statement stability', () => {}const { result, rerender } = renderHook(({ fs }) => useChat(config, fs), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },initialProps: { fs: { inputs: { name: 'Alice' }, inputsForm: [] } },})@@ -150,7 +158,10 @@ describe('workflow debug useChat – opening statement stability', () => {const { result, rerender } = renderHook(({ cfg }) => useChat(cfg, undefined, prevChatTree as ChatItemInTree[]),- { initialProps: { cfg: config } },+ {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ initialProps: { cfg: config },+ },)const openerBefore = result.current.chatList[0]@@ -167,14 +178,18 @@ describe('workflow debug useChat – opening statement stability', () => {opening_statement: 'Welcome!',suggested_questions: ['How are you?', 'What can you do?'],}- const { result } = renderHook(() => useChat(config))+ const { result } = renderHook(() => useChat(config), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })const opener = result.current.chatList[0]expect(opener!.suggestedQuestions).toEqual(['How are you?', 'What can you do?'])})it('should not include suggestedQuestions when config has none', () => {const config = { opening_statement: 'Welcome!' }- const { result } = renderHook(() => useChat(config))+ const { result } = renderHook(() => useChat(config), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })const opener = result.current.chatList[0]expect(opener!.suggestedQuestions).toBeUndefined()})diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.tsindex 470915484cc..4753a39e3e9 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts@@ -1,4 +1,5 @@-import { act, renderHook } from '@testing-library/react'+import { act } from '@testing-library/react'+import { renderEditorHook as renderHook } from '@/app/components/workflow/editor-resource/__tests__/render'import { useChat } from '../../hooks'const mockHandleRun = vi.fn()@@ -18,7 +19,7 @@ vi.mock('@/service/base', () => ({}))vi.mock('@/service/use-workflow', () => ({- useInvalidAllLastRun: () => mockInvalidAllLastRun,+ useInvalidateAllLastRun: () => mockInvalidAllLastRun,}))vi.mock('@/service/workflow', () => ({@@ -83,7 +84,9 @@ describe('useChat – handleSend SSE callbacks', () => {})function setupAndSend(config: any = {}) {- const hook = renderHook(() => useChat(config))+ const hook = renderHook(() => useChat(config), {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },+ })act(() => {hook.result.current.handleSend({ query: 'test' },@@ -339,8 +342,9 @@ describe('useChat – handleSend SSE callbacks', () => {getAbortCtrl(new AbortController())return Promise.resolve({ data: ['suggestion1'] })})- const hook = renderHook(() =>- useChat({ suggested_questions_after_answer: { enabled: true } }),+ const hook = renderHook(+ () => useChat({ suggested_questions_after_answer: { enabled: true } }),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)mockHandleRun.mockImplementation((_params: any, callbacks: any) => {@@ -365,8 +369,9 @@ describe('useChat – handleSend SSE callbacks', () => {it('should set suggestedQuestions to empty array when fetch fails', async () => {const mockGetSuggested = vi.fn().mockRejectedValue(new Error('fail'))- const hook = renderHook(() =>- useChat({ suggested_questions_after_answer: { enabled: true } }),+ const hook = renderHook(+ () => useChat({ suggested_questions_after_answer: { enabled: true } }),+ { resource: { kind: 'app', appId: 'app-1', mode: 'workflow' } },)mockHandleRun.mockImplementation((_params: any, callbacks: any) => {diff --git a/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx b/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsxindex b1b785eabb8..2a5be2a3660 100644--- a/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx+++ b/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx@@ -4,14 +4,15 @@ import type { HumanInputFormSubmitData } from '@/app/components/base/chat/chat/aimport type { ChatItem, OnSend } from '@/app/components/base/chat/types'import type { FileEntity } from '@/app/components/base/file-uploader/types'import { useMutation, useQueryClient } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { memo, useCallback, useEffect, useImperativeHandle, useMemo } from 'react'import { useNodes } from 'reactflow'import Chat from '@/app/components/base/chat/chat'import { getLastAnswer, isValidGeneratedAnswer } from '@/app/components/base/chat/utils'import { useFeatures } from '@/app/components/base/features/hooks'+import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'import { EVENT_WORKFLOW_STOP } from '@/app/components/workflow/variable-inspect/types'import { useEventEmitterContextContext } from '@/context/event-emitter'-import { useParams } from '@/next/navigation'import { consoleQuery } from '@/service/console'import { useStore, useWorkflowStore } from '../../store'import { BlockEnum, WorkflowRunningStatus } from '../../types'@@ -39,7 +40,7 @@ const ChatWrapper = ({const nodes = useNodes<StartNodeType>()const startNode = nodes.find((node) => node.data.type === BlockEnum.Start)const startVariables = startNode?.data.variables- const { appId } = useParams<{ appId: string }>()+ const { appId } = useAtomValue(workflowAppIdentityAtom)const queryClient = useQueryClient()const { mutateAsync: stopChat } = useMutation(consoleQuery.apps.byAppId.chatMessages.byTaskId.stop.post.mutationOptions(),diff --git a/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx b/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsxindex fcaa5fed412..15070e5087b 100644--- a/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx+++ b/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx@@ -1,4 +1,5 @@'use client'+import type { ConversationVariable } from '@/app/components/workflow/types'import { cn } from '@langgenius/dify-ui/cn'import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'@@ -7,9 +8,11 @@ import { RiCloseLine } from '@remixicon/react'import { useMount } from 'ahooks'import copy from 'copy-to-clipboard'import { capitalize } from 'es-toolkit/string'+import { useAtomValue } from 'jotai'import * as React from 'react'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'@@ -26,7 +29,7 @@ const ConversationVariableModal = ({ conversationID, onHide }: Props) => {const { t } = useTranslation(['appLog', 'common', 'workflow'])const { formatTime } = useTimestamp()const varList = useStore((s) => s.conversationVariables) as ConversationVariable[]- const appID = useStore((s) => s.appId)+ const appID = useAtomValue(editorAppIdAtom)const [currentVar, setCurrentVar] = React.useState<ConversationVariable>(varList[0]!)const [latestValueMap, setLatestValueMap] = React.useState<Record<string, string>>({})const [latestValueTimestampMap, setLatestValueTimestampMap] = React.useState<diff --git a/web/app/components/workflow/panel/debug-and-preview/hooks.ts b/web/app/components/workflow/panel/debug-and-preview/hooks.tsindex 5ad3a079673..d044af79fb8 100644--- a/web/app/components/workflow/panel/debug-and-preview/hooks.ts+++ b/web/app/components/workflow/panel/debug-and-preview/hooks.ts@@ -7,6 +7,7 @@ import type { IOtherOptions } from '@/service/base'import type { ReasoningChunkResponse } from '@/types/workflow'import { uniqBy } from 'es-toolkit/compat'import { produce, setAutoFreeze } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { useStoreApi } from 'reactflow'@@ -18,9 +19,10 @@ import {getProcessedFilesFromResponse,} from '@/app/components/base/file-uploader/utils'import { CUSTOM_NODE } from '@/app/components/workflow/constants'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import { toast } from '@/app/notifications'import { sseGet } from '@/service/base'-import { useInvalidAllLastRun } from '@/service/use-workflow'+import { useInvalidateAllLastRun } from '@/service/use-workflow'import { submitHumanInputForm } from '@/service/workflow'import { TransferMethod } from '@/types/app'import { DEFAULT_ITER_TIMES, DEFAULT_LOOP_TIMES } from '../../constants'@@ -54,9 +56,9 @@ export const useChat = (const [isResponding, setIsResponding] = useState(false)const isRespondingRef = useRef(false)const workflowEventsAbortControllerRef = useRef<AbortController | null>(null)- const configsMap = useHooksStore((s) => s.configsMap)+ const resource = useAtomValue(editorResourceAtom)const canRun = useHooksStore((s) => s.accessControl.canRun)- const invalidAllLastRun = useInvalidAllLastRun(configsMap?.flowType, configsMap?.flowId)+ const invalidAllLastRun = useInvalidateAllLastRun(resource)const { fetchInspectVars } = useSetWorkflowVarsWithValue()const [suggestedQuestions, setSuggestedQuestions] = useState<string[]>([])const cancelSuggestedQuestionsRef = useRef<(() => void) | null>(null)diff --git a/web/app/components/workflow/panel/env-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/env-panel/__tests__/index.spec.tsxindex d184ab2e7d1..365c241610d 100644--- a/web/app/components/workflow/panel/env-panel/__tests__/index.spec.tsx+++ b/web/app/components/workflow/panel/env-panel/__tests__/index.spec.tsx@@ -1,12 +1,14 @@import type { ReactElement } from 'react'import type { ModelParameterRule } from '@/app/components/header/account-setting/model-provider-page/declarations'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type { SyncDraftCallback } from '@/app/components/workflow/hooks-store'import type { Shape } from '@/app/components/workflow/store/workflow'import type { EnvironmentVariable } from '@/app/components/workflow/types'-import { act, render, screen, waitFor } from '@testing-library/react'+import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'import { WorkflowContext } from '@/app/components/workflow/context'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { createWorkflowStore } from '@/app/components/workflow/store/workflow'import EnvPanel from '../index'@@ -120,13 +122,16 @@ vi.mock('@/app/components/workflow/nodes/_base/components/variable/utils', () =>updateNodeVars: mockUpdateNodeVars,}))+vi.mock('../requests', () => ({+ fetchEnvironmentVariables: async () => (await mockFetchWorkflowDraft()).environment_variables,+}))+vi.mock('@/service/workflow', () => ({updateEnvironmentVariables: (payload: {appId: stringenvironmentVariables: EnvironmentVariable[]deletedEnvironmentVariableIds: string[]}) => mockUpdateEnvironmentVariables(payload),- fetchWorkflowDraft: () => mockFetchWorkflowDraft(),}))vi.mock('@/app/components/workflow/collaboration/core/websocket-manager', () => ({@@ -221,13 +226,19 @@ const createEnv = (overrides: Partial<EnvironmentVariable> = {}): EnvironmentVar...overrides,})-const renderWithProviders = (ui: ReactElement, storeState: Partial<Shape> = {}) => {+const renderWithProviders = (+ ui: ReactElement,+ storeState: Partial<Shape> = {},+ resource: EditorResource = { kind: 'app', appId: 'app-1', mode: 'workflow' },+) => {const store = createWorkflowStore({})store.setState(storeState)return {store,- ...render(<WorkflowContext value={store}>{ui}</WorkflowContext>),+ ...render(<WorkflowContext value={store}>{ui}</WorkflowContext>, {+ resource,+ }),}}@@ -256,7 +267,6 @@ describe('EnvPanel container', () => {it('should add variables and normalize secret values after syncing', async () => {const user = userEvent.setup()const { store } = renderWithProviders(<EnvPanel />, {- appId: 'app-1',environmentVariables: [],envSecrets: {},})@@ -280,11 +290,109 @@ describe('EnvPanel container', () => {expect(mockDoSyncWorkflowDraft).not.toHaveBeenCalled()})+ it('persists new pipeline variables through draft sync without app requests or socket events', async () => {+ const user = userEvent.setup()+ const existingEnv = createEnv({+ name: 'existing_variable',+ value_type: 'string',+ value: 'existing',+ })+ const emit = vi.fn()+ mockGetSocket.mockReturnValue({ emit })+ const { store } = renderWithProviders(+ <EnvPanel />,+ {+ environmentVariables: [existingEnv],+ envSecrets: {},+ },+ { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ )+ let completeSync!: () => void+ let variablesSentToDraft: EnvironmentVariable[] = []+ mockDoSyncWorkflowDraft.mockImplementationOnce((_notRefresh, callback) => {+ variablesSentToDraft = store.getState().environmentVariables+ return new Promise((resolve) => {+ completeSync = () => {+ callback?.onSuccess?.()+ resolve()+ }+ })+ })++ await user.click(screen.getByRole('button', { name: 'Save variable' }))+ expect(await screen.findByText('created_name')).toBeInTheDocument()+ expect(variablesSentToDraft).toEqual([+ expect.objectContaining({ id: 'env-created', name: 'created_name', value: 'created-value' }),+ existingEnv,+ ])+ await act(async () => completeSync())++ expect(screen.getByText('created_name')).toBeInTheDocument()+ expect(screen.getByText('existing_variable')).toBeInTheDocument()+ expect(mockUpdateEnvironmentVariables).not.toHaveBeenCalled()+ expect(mockGetSocket).not.toHaveBeenCalled()+ expect(emit).not.toHaveBeenCalled()+ })++ it('restores the persisted pipeline variable after draft sync fails and preserves other variables', async () => {+ const user = userEvent.setup()+ const existingEnv = createEnv({+ name: 'existing_variable',+ value_type: 'string',+ value: 'existing',+ })+ const untouchedEnv = createEnv({+ id: 'env-untouched',+ name: 'untouched_variable',+ value_type: 'string',+ value: 'untouched',+ })+ const emit = vi.fn()+ mockGetSocket.mockReturnValue({ emit })+ mockVariableTriggerState.savePayload = { ...existingEnv, name: 'rejected_name' }+ mockFetchWorkflowDraft.mockResolvedValue({ environment_variables: [existingEnv, untouchedEnv] })+ let failSync!: () => void+ mockDoSyncWorkflowDraft.mockImplementation(async (_notRefresh, callback) => {+ callback?.onError?.()+ })+ mockDoSyncWorkflowDraft.mockImplementationOnce(+ (_notRefresh, callback) =>+ new Promise((resolve) => {+ failSync = () => {+ callback?.onError?.()+ resolve()+ }+ }),+ )+ renderWithProviders(+ <EnvPanel />,+ {+ environmentVariables: [existingEnv, untouchedEnv],+ envSecrets: {},+ },+ { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ )++ await user.click(screen.getByRole('button', { name: 'Edit existing_variable' }))+ await user.click(screen.getByRole('button', { name: 'Save variable' }))+ expect(await screen.findByRole('button', { name: 'Edit rejected_name' })).toBeInTheDocument()+ await act(async () => failSync())++ expect(+ await screen.findByRole('button', { name: 'Edit existing_variable' }),+ ).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Edit rejected_name' })).not.toBeInTheDocument()+ expect(screen.getByText('untouched_variable')).toBeInTheDocument()+ expect(mockFetchWorkflowDraft).toHaveBeenCalled()+ expect(mockUpdateEnvironmentVariables).not.toHaveBeenCalled()+ expect(mockGetSocket).not.toHaveBeenCalled()+ expect(emit).not.toHaveBeenCalled()+ })+it('should delete unused variables and sync draft changes', async () => {const user = userEvent.setup()const env = createEnv({ value_type: 'string', value: 'plain-text' })const { store } = renderWithProviders(<EnvPanel />, {- appId: 'app-1',environmentVariables: [env],envSecrets: {},})@@ -497,7 +605,6 @@ describe('EnvPanel container', () => {})const { store } = renderWithProviders(<EnvPanel />, {- appId: 'app-1',environmentVariables: [env],envSecrets: {},})@@ -630,7 +737,6 @@ describe('EnvPanel container', () => {mockVariableTriggerState.savePayload = nextEnvconst { store } = renderWithProviders(<EnvPanel />, {- appId: 'app-1',environmentVariables: [env],envSecrets: {},})@@ -684,7 +790,6 @@ describe('EnvPanel container', () => {mockGetNodes.mockReturnValue([llmNode])const { store } = renderWithProviders(<EnvPanel />, {- appId: 'app-1',environmentVariables: [env],envSecrets: {},})diff --git a/web/app/components/workflow/panel/env-panel/index.tsx b/web/app/components/workflow/panel/env-panel/index.tsxindex f2ee348c3d1..a8350bb1e6c 100644--- a/web/app/components/workflow/panel/env-panel/index.tsx+++ b/web/app/components/workflow/panel/env-panel/index.tsx@@ -1,4 +1,5 @@import type { ModelSelectorProvider } from '@/app/components/header/account-setting/model-provider-page/model-selector/types'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type { LLMNodeType } from '@/app/components/workflow/nodes/llm/types'import type {EnvironmentVariable,@@ -9,11 +10,13 @@ import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { RiCloseLine } from '@remixicon/react'import { cloneDeep } from 'es-toolkit/object'import { isEqual } from 'es-toolkit/predicate'+import { useAtomValue } from 'jotai'import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import { isLLMEnvironmentVariableValue } from '@/app/components/workflow/llm-environment-variable'import RemoveEffectVarConfirm from '@/app/components/workflow/nodes/_base/components/remove-effect-var-confirm'import {@@ -32,6 +35,7 @@ import {} from '@/utils/completion-params'import { useCollaborativeWorkflow } from '../../hooks/use-collaborative-workflow'import { useNodesSyncDraft } from '../../hooks/use-nodes-sync-draft'+import { fetchEnvironmentVariables } from './requests'const HIDDEN_SECRET_VALUE = '[__HIDDEN__]'@@ -154,7 +158,8 @@ const getLLMEnvironmentValue = (const useEnvPanelActions = ({collaborativeWorkflow,workflowStore,- appId,+ resource,+ doSyncWorkflowDraft,updateEnvList,setEnvSecrets,setControlPromptEditorRerenderKey,@@ -162,7 +167,8 @@ const useEnvPanelActions = ({}: {collaborativeWorkflow: ReturnType<typeof useCollaborativeWorkflow>workflowStore: ReturnType<typeof useWorkflowStore>- appId: string+ resource: EditorResource+ doSyncWorkflowDraft: ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']updateEnvList: (envList: EnvironmentVariable[]) => voidsetEnvSecrets: (envSecrets: Record<string, string>) => voidsetControlPromptEditorRerenderKey: (controlPromptEditorRerenderKey: number) => void@@ -170,6 +176,8 @@ const useEnvPanelActions = ({}) => {const emitVarsAndFeaturesUpdate = useCallback(async (syncWorkflowDraft = false) => {+ if (resource.kind !== 'app') return+ const { appId } = resourcetry {const { webSocketClient } =await import('@/app/components/workflow/collaboration/core/websocket-manager')@@ -184,17 +192,23 @@ const useEnvPanelActions = ({console.error('Failed to emit vars_and_features_update event:', error)}},- [appId],+ [resource],)const persistEnvironmentVariables = useCallback(async (patch: EnvironmentVariablePatch, syncWorkflowDraft = false) => {+ if (resource.kind !== 'app') {+ let succeeded = false+ await doSyncWorkflowDraft(false, {+ onSuccess: () => {+ succeeded = true+ },+ })+ return succeeded+ }try {const { updateEnvironmentVariables } = await import('@/service/workflow')- await updateEnvironmentVariables({- appId,- ...patch,- })+ await updateEnvironmentVariables({ appId: resource.appId, ...patch })await emitVarsAndFeaturesUpdate(syncWorkflowDraft)return true} catch (error) {@@ -202,19 +216,17 @@ const useEnvPanelActions = ({return false}},- [appId, emitVarsAndFeaturesUpdate],+ [resource, doSyncWorkflowDraft, emitVarsAndFeaturesUpdate],)const fetchPersistedEnvironmentVariables = useCallback(async () => {try {- const { fetchWorkflowDraft } = await import('@/service/workflow')- const workflow = await fetchWorkflowDraft(`/apps/${appId}/workflows/draft`)- return workflow.environment_variables+ return await fetchEnvironmentVariables(resource)} catch (error) {console.error('Failed to refresh environment variables:', error)return undefined}- }, [appId])+ }, [resource])const getAffectedNodes = useCallback((env: EnvironmentVariable) => {@@ -421,7 +433,7 @@ const EnvPanel = () => {const updateEnvList = useStore((s) => s.setEnvironmentVariables)const setEnvSecrets = useStore((s) => s.setEnvSecrets)const setControlPromptEditorRerenderKey = useStore((s) => s.setControlPromptEditorRerenderKey)- const appId = useStore((s) => s.appId) as string+ const resource = useAtomValue(editorResourceAtom)const { doSyncWorkflowDraft } = useNodesSyncDraft()const { activeTextGenerationModelList } = useTextGenerationCurrentProviderAndModelAndModelList()const {@@ -436,7 +448,8 @@ const EnvPanel = () => {} = useEnvPanelActions({collaborativeWorkflow,workflowStore,- appId,+ resource,+ doSyncWorkflowDraft,updateEnvList,setEnvSecrets,setControlPromptEditorRerenderKey,diff --git a/web/app/components/workflow/panel/env-panel/requests.ts b/web/app/components/workflow/panel/env-panel/requests.tsnew file mode 100644index 00000000000..93941080f8b--- /dev/null+++ b/web/app/components/workflow/panel/env-panel/requests.ts@@ -0,0 +1,35 @@+import type { EditorResource } from '../../editor-resource/resource'+import type { EnvironmentVariable } from '../../types'+import { consoleClient } from '@/service/console'+import { isLLMEnvironmentVariableValue } from '../../llm-environment-variable'++export async function fetchEnvironmentVariables(+ resource: EditorResource,+): Promise<EnvironmentVariable[]> {+ const workflow = await (() => {+ switch (resource.kind) {+ case 'app':+ return consoleClient.apps.byAppId.workflows.draft.get({+ params: { app_id: resource.appId },+ })+ case 'knowledge-pipeline':+ return consoleClient.rag.pipelines.byPipelineId.workflows.draft.get({+ params: { pipeline_id: resource.pipelineId },+ })+ case 'snippet':+ return consoleClient.snippets.bySnippetId.workflows.draft.get({+ params: { snippet_id: resource.snippetId },+ })+ }+ })()+ return workflow.environment_variables.map((variable) => {+ const { value_type, value } = variable+ if ((value_type === 'string' || value_type === 'secret') && typeof value === 'string')+ return { ...variable, value_type, value }+ if (value_type === 'number' && typeof value === 'number')+ return { ...variable, value_type, value }+ if (value_type === 'llm' && isLLMEnvironmentVariableValue(value))+ return { ...variable, value_type, value }+ throw new Error(`Unsupported environment variable: ${variable.name}`)+ })+}diff --git a/web/app/components/workflow/panel/global-variable-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/global-variable-panel/__tests__/index.spec.tsxindex be6e1f92bb4..6635ff0ed6f 100644--- a/web/app/components/workflow/panel/global-variable-panel/__tests__/index.spec.tsx+++ b/web/app/components/workflow/panel/global-variable-panel/__tests__/index.spec.tsx@@ -18,9 +18,7 @@ vi.mock('../../../constants', () => ({isInWorkflowPage: () => mockIsWorkflowPage,}))-vi.mock('../../../hooks/use-workflow', () => ({- useIsChatMode: () => mockIsChatMode,-}))+vi.mock('../../../hooks/use-workflow', () => ({}))describe('global-variable-panel path', () => {beforeEach(() => {@@ -43,3 +41,10 @@ describe('global-variable-panel path', () => {).toBeInTheDocument()})})++vi.mock('@/app/components/workflow/editor-resource/state', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('@/app/components/workflow/editor-resource/state')>()+ const { atom } = await import('jotai')+ return { ...actual, isChatflowAtom: atom(() => mockIsChatMode) }+})diff --git a/web/app/components/workflow/panel/global-variable-panel/index.tsx b/web/app/components/workflow/panel/global-variable-panel/index.tsxindex 3ca86195da0..f0d562e1714 100644--- a/web/app/components/workflow/panel/global-variable-panel/index.tsx+++ b/web/app/components/workflow/panel/global-variable-panel/index.tsx@@ -1,21 +1,22 @@import type { GlobalVariable } from '../../types'import { cn } from '@langgenius/dify-ui/cn'import { RiCloseLine } from '@remixicon/react'+import { useAtomValue } from 'jotai'import { memo } from 'react'import { useTranslation } from 'react-i18next'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'import { useStore } from '@/app/components/workflow/store'import { isInWorkflowPage } from '../../constants'-import { useIsChatMode } from '../../hooks/use-workflow'import Item from './item'const Panel = () => {- const { t } = useTranslation(['workflow'])- const isChatMode = useIsChatMode()+ const { t } = useTranslation(['workflow'] as const)+ const isChatflow = useAtomValue(isChatflowAtom)const setShowPanel = useStore((s) => s.setShowGlobalVariablePanel)const isWorkflowPage = isInWorkflowPage()const globalVariableList: GlobalVariable[] = [- ...(isChatMode+ ...(isChatflow? [{name: 'conversation_id',@@ -52,7 +53,7 @@ const Panel = () => {description: t(($) => $['globalVar.fieldsDescription.workflowRunId'], { ns: 'workflow' }),},// is workflow- ...(isWorkflowPage && !isChatMode+ ...(isWorkflowPage && !isChatflow? [{name: 'timestamp',diff --git a/web/app/components/workflow/panel/inputs-panel.tsx b/web/app/components/workflow/panel/inputs-panel.tsxindex 4f75625430d..254f1d283c9 100644--- a/web/app/components/workflow/panel/inputs-panel.tsx+++ b/web/app/components/workflow/panel/inputs-panel.tsx@@ -20,7 +20,7 @@ const InputsPanel = ({ onRun }: Props) => {const { t } = useTranslation(['workflow'])const workflowStore = useWorkflowStore()const inputs = useStore((s) => s.inputs)- const fileSettings = useHooksStore((s) => s.configsMap?.fileSettings)+ const fileSettings = useHooksStore((s) => s.fileSettings)const canRunWorkflow = useHooksStore((s) => s.accessControl.canRun)const nodes = useNodes<StartNodeType>()const files = useStore((s) => s.files)diff --git a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsxindex 9666067fa35..94d47050ad5 100644--- a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx+++ b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx@@ -6,9 +6,8 @@ import { fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { NuqsTestingAdapter } from 'nuqs/adapters/testing'import { useEffect, useRef } from 'react'+import { renderEditor as renderWithConsoleState } from '@/app/components/workflow/editor-resource/__tests__/render'import { createConsoleQueryWrapper } from '@/test/console/query-data'-import { render as renderWithConsoleState } from '@/test/console/render'-import { AppModeEnum } from '@/types/app'import { VersionHistoryContextMenuOptions, WorkflowVersion } from '../../../types'const mockHandleRestoreFromPublishedWorkflow = vi.fn()@@ -86,7 +85,7 @@ vi.mock('@/app/notifications', () => ({ toast: mockToast }))vi.mock('@/service/use-workflow', () => ({useDeleteWorkflow: () => ({ mutateAsync: vi.fn() }),useInvalidateAppWorkflow: () => mockInvalidateAppWorkflow,- useInvalidAllLastRun: () => vi.fn(),+ useInvalidateAllLastRun: () => vi.fn(),useResetWorkflowVersionHistory: () => vi.fn(),useRestoreWorkflow: () => ({ mutateAsync: mockRestoreWorkflow }),useUpdateWorkflow: () => ({ mutateAsync: mockUpdateWorkflow }),@@ -135,14 +134,14 @@ vi.mock('../../../hooks-store', () => ({useHooksStore: (selector: (state: {accessControl: { canImportExportDSL: boolean }- configsMap: { flowId: string; flowType: string }+ configsMap: { flowId: string; resourceKind: string }}) => unknown,) =>selector({accessControl: { canImportExportDSL: true },configsMap: {flowId: 'app-1',- flowType: 'appFlow',+ resourceKind: 'appFlow',},}),}))@@ -293,12 +292,7 @@ describe('VersionHistoryPanel', () => {mockHasNextPage = trueconst { VersionHistoryPanel } = await import('../index')- render(- <VersionHistoryPanel- latestVersionId="published-version-id"- restoreVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}/restore`}- />,- )+ render(<VersionHistoryPanel latestVersionId="published-version-id" />)await user.click(screen.getByRole('button', { name: 'workflow.common.loadMore' }))expect(mockFetchNextPage).toHaveBeenCalledTimes(1)@@ -319,12 +313,7 @@ describe('VersionHistoryPanel', () => {it('should call handleLoadBackupDraft when draft version is selected on mount', async () => {const { VersionHistoryPanel } = await import('../index')- render(- <VersionHistoryPanel- latestVersionId="published-version-id"- restoreVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}/restore`}- />,- )+ render(<VersionHistoryPanel latestVersionId="published-version-id" />)expect(mockHandleLoadBackupDraft).toHaveBeenCalled()expect(mockHandleRestoreFromPublishedWorkflow).not.toHaveBeenCalled()@@ -333,12 +322,7 @@ describe('VersionHistoryPanel', () => {it('should call handleRestoreFromPublishedWorkflow when clicking published version', async () => {const { VersionHistoryPanel } = await import('../index')- render(- <VersionHistoryPanel- latestVersionId="published-version-id"- restoreVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}/restore`}- />,- )+ render(<VersionHistoryPanel latestVersionId="published-version-id" />)vi.clearAllMocks()@@ -352,12 +336,7 @@ describe('VersionHistoryPanel', () => {it('should set current version before confirming restore from context menu', async () => {const { VersionHistoryPanel } = await import('../index')- render(- <VersionHistoryPanel- latestVersionId="published-version-id"- restoreVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}/restore`}- />,- )+ render(<VersionHistoryPanel latestVersionId="published-version-id" />)await waitFor(() => {expect(mockHandleLoadBackupDraft).toHaveBeenCalled()@@ -373,9 +352,7 @@ describe('VersionHistoryPanel', () => {id: 'published-version-id',}),)- expect(mockRestoreWorkflow).toHaveBeenCalledWith(- '/apps/app-1/workflows/published-version-id/restore',- )+ expect(mockRestoreWorkflow).toHaveBeenCalledWith('published-version-id')expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({ isRestoring: false })expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({ backupDraft: undefined })expect(mockHandleRefreshWorkflowDraft).toHaveBeenCalled()@@ -386,12 +363,7 @@ describe('VersionHistoryPanel', () => {const { VersionHistoryPanel } = await import('../index')mockPlanType = 'sandbox'- render(- <VersionHistoryPanel- latestVersionId="published-version-id"- restoreVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}/restore`}- />,- )+ render(<VersionHistoryPanel latestVersionId="published-version-id" />)vi.clearAllMocks()@@ -406,12 +378,7 @@ describe('VersionHistoryPanel', () => {const { VersionHistoryPanel } = await import('../index')mockPlanType = 'sandbox'- render(- <VersionHistoryPanel- latestVersionId="published-version-id"- restoreVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}/restore`}- />,- )+ render(<VersionHistoryPanel latestVersionId="published-version-id" />)vi.clearAllMocks()@@ -425,12 +392,7 @@ describe('VersionHistoryPanel', () => {mockPublishedEnvironments = [{ id: 'environment-id', name: 'Production' }]const { VersionHistoryPanel } = await import('../index')- render(- <VersionHistoryPanel- latestVersionId="published-version-id"- restoreVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}/restore`}- />,- )+ render(<VersionHistoryPanel latestVersionId="published-version-id" />)fireEvent.click(screen.getByText('delete-published-version-id'))@@ -443,12 +405,7 @@ describe('VersionHistoryPanel', () => {it('should allow deleting a version that is not deployed', async () => {const { VersionHistoryPanel } = await import('../index')- render(- <VersionHistoryPanel- latestVersionId="published-version-id"- restoreVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}/restore`}- />,- )+ render(<VersionHistoryPanel latestVersionId="published-version-id" />)fireEvent.click(screen.getByText('delete-published-version-id'))@@ -463,12 +420,7 @@ describe('VersionHistoryPanel', () => {version: WorkflowVersion.Draft,})- render(- <VersionHistoryPanel- latestVersionId="published-version-id"- restoreVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}/restore`}- />,- )+ render(<VersionHistoryPanel latestVersionId="published-version-id" />)vi.clearAllMocks()mockRestoreWorkflow.mockRejectedValueOnce(new Error('restore failed'))@@ -477,9 +429,7 @@ describe('VersionHistoryPanel', () => {fireEvent.click(screen.getByText('confirm restore'))await waitFor(() => {- expect(mockRestoreWorkflow).toHaveBeenCalledWith(- '/apps/app-1/workflows/published-version-id/restore',- )+ expect(mockRestoreWorkflow).toHaveBeenCalledWith('published-version-id')})expect(mockWorkflowStoreSetState).not.toHaveBeenCalledWith({ isRestoring: false })@@ -505,9 +455,7 @@ describe('VersionHistoryPanel', () => {render(<VersionHistoryPanel- appMode={AppModeEnum.WORKFLOW}latestVersionId="published-version-id"- restoreVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}/restore`}updateVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}`}/>,)@@ -519,7 +467,7 @@ describe('VersionHistoryPanel', () => {expect(mockUpdateWorkflow).toHaveBeenCalledWith({appId: 'app-1',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,releaseNotes: 'Updated notes',title: 'Updated release',url: '/apps/app-1/workflows/published-version-id',@@ -537,6 +485,7 @@ function render(ui: ReactElement) {features: { billing: { subscription: { plan: mockPlanType } } },})return renderWithConsoleState(ui, {+ resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },wrapper: ({ children }) => (<NuqsTestingAdapter><QueryWrapper>{children}</QueryWrapper>diff --git a/web/app/components/workflow/panel/version-history-panel/__tests__/version-history-item.spec.tsx b/web/app/components/workflow/panel/version-history-panel/__tests__/version-history-item.spec.tsxindex 7babfd7f96b..9bcc932db30 100644--- a/web/app/components/workflow/panel/version-history-panel/__tests__/version-history-item.spec.tsx+++ b/web/app/components/workflow/panel/version-history-panel/__tests__/version-history-item.spec.tsx@@ -1,7 +1,7 @@import type { VersionHistory } from '@/types/workflow'import { fireEvent, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { renderWithConsoleQuery as render } from '@/test/console/query-data'+import { renderEditor as render } from '@/app/components/workflow/editor-resource/__tests__/render'import { VersionHistoryContextMenuOptions, WorkflowVersion } from '../../../types'import VersionHistoryItem from '../version-history-item'diff --git a/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/index.spec.tsx b/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/index.spec.tsxindex b5b79b87366..0f3b0478b9a 100644--- a/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/index.spec.tsx+++ b/web/app/components/workflow/panel/version-history-panel/action-menu/__tests__/index.spec.tsx@@ -20,7 +20,9 @@ const renderActionMenu = (ui: React.ReactElement, pipelineId?: string) => {seedSystemFeatures(queryClient, { deployment_edition: deploymentEdition })return renderWorkflowComponent(<NuqsTestingAdapter>{ui}</NuqsTestingAdapter>, {queryClient,- initialStoreState: { pipelineId },+ resource: pipelineId+ ? { kind: 'knowledge-pipeline', pipelineId }+ : { kind: 'app', appId: 'app-1', mode: 'workflow' },})}diff --git a/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsx b/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsxindex 299da2b8888..dfc091c393c 100644--- a/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsx+++ b/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsx@@ -13,7 +13,7 @@ import * as React from 'react'import { useMemo, useRef } from 'react'import { useTranslation } from 'react-i18next'import PremiumBadge from '@/app/components/base/premium-badge'-import { useStore } from '@/app/components/workflow/store'+import { editorResourceKindAtom } from '@/app/components/workflow/editor-resource/state'import { deploymentEditionAtom } from '@/features/system-features/state'import { consoleQuery } from '@/service/console'import { VersionHistoryContextMenuOptions } from '../../../types'@@ -31,7 +31,7 @@ type ActionMenuProps = {const useActionMenu = (props: ActionMenuProps) => {const { workflowId, isNamedVersion, canImportExportDSL } = propsconst { t } = useTranslation(['app', 'common', 'workflow', 'workflowHistory'])- const pipelineId = useStore((s) => s.pipelineId)+ const resourceKind = useAtomValue(editorResourceKindAtom)const deploymentEdition = useAtomValue(deploymentEditionAtom)const { data: plan } = useQuery(consoleQuery.features.get.queryOptions({@@ -64,7 +64,7 @@ const useActionMenu = (props: ActionMenuProps) => {name: t(($) => $['versionHistory.nameThisVersion'], { ns: 'workflowHistory' }),},// todo: pipeline support export specific version DSL- ...(canImportExportDSL && !pipelineId+ ...(canImportExportDSL && resourceKind !== 'knowledge-pipeline'? [{key: VersionHistoryContextMenuOptions.exportDSL,@@ -85,7 +85,7 @@ const useActionMenu = (props: ActionMenuProps) => {plan,canImportExportDSL,isNamedVersion,- pipelineId,+ resourceKind,shouldShowUpgrade,t,workflowId,diff --git a/web/app/components/workflow/panel/version-history-panel/index.tsx b/web/app/components/workflow/panel/version-history-panel/index.tsxindex 4ad03dfe7d3..e8cc9ef3622 100644--- a/web/app/components/workflow/panel/version-history-panel/index.tsx+++ b/web/app/components/workflow/panel/version-history-panel/index.tsx@@ -1,6 +1,5 @@'use client'-import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { VersionHistory } from '@/types/workflow'import { Separator } from '@langgenius/dify-ui/separator'import { useQuery, useSuspenseQuery } from '@tanstack/react-query'@@ -11,6 +10,8 @@ import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import VersionInfoModal from '@/app/components/app/app-publisher/version-info-modal'import { PlanUpgradeModal } from '@/app/components/billing/plan-upgrade-modal'+import { getEditorResourceId } from '@/app/components/workflow/editor-resource/resource'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import { getWorkflowVersionName } from '@/app/components/workflow/utils/version'import { toast } from '@/app/notifications'import { userProfileQueryOptions } from '@/features/account-profile/client'@@ -18,14 +19,13 @@ import { deploymentEditionAtom } from '@/features/system-features/state'import { consoleQuery } from '@/service/console'import {useDeleteWorkflow,- useInvalidAllLastRun,+ useInvalidateAllLastRun,useInvalidateAppWorkflow,useResetWorkflowVersionHistory,useRestoreWorkflow,useUpdateWorkflow,useWorkflowVersionHistory,} from '@/service/use-workflow'-import { FlowType } from '@/types/common'import { useHooksStore } from '../../hooks-store'import { useDSL } from '../../hooks/use-DSL'import { useWorkflowRefreshDraft } from '../../hooks/use-workflow-refresh-draft'@@ -47,19 +47,15 @@ const HISTORY_PER_PAGE = 10const INITIAL_PAGE = 1export type VersionHistoryPanelProps = {- appMode?: AppModegetVersionListUrl?: stringdeleteVersionUrl?: (versionId: string) => string- restoreVersionUrl: (versionId: string) => stringupdateVersionUrl?: (versionId: string) => stringlatestVersionId?: string}export const VersionHistoryPanel = ({- appMode,getVersionListUrl,deleteVersionUrl,- restoreVersionUrl,updateVersionUrl,latestVersionId,}: VersionHistoryPanelProps) => {@@ -91,9 +87,10 @@ export const VersionHistoryPanel = ({...userProfileQueryOptions(),select: (data) => data.profile,})- const configsMap = useHooksStore((s) => s.configsMap)+ const resource = useAtomValue(editorResourceAtom)+ const resourceId = getEditorResourceId(resource)const canImportExportDSL = useHooksStore((s) => s.accessControl.canImportExportDSL)- const invalidAllLastRun = useInvalidAllLastRun(configsMap?.flowType, configsMap?.flowId)+ const invalidAllLastRun = useInvalidateAllLastRun(resource)const invalidateAppWorkflow = useInvalidateAppWorkflow()const { deleteAllInspectVars } = workflowStore.getState()const { t } = useTranslation(['billing', 'common', 'workflow', 'workflowHistory'])@@ -251,8 +248,8 @@ export const VersionHistoryPanel = ({const emitWorkflowUpdate = useCallback(async () => {try {- const appId = configsMap?.flowId- if (!appId) return+ if (resource.kind !== 'app') return+ const { appId } = resourceconst { collaborationManager } =await import('../../collaboration/core/collaboration-manager')@@ -260,10 +257,10 @@ export const VersionHistoryPanel = ({} catch (error) {console.error('Failed to emit workflow update:', error)}- }, [configsMap?.flowId])+ }, [resource])const resetWorkflowVersionHistory = useResetWorkflowVersionHistory()- const { mutateAsync: restoreWorkflow } = useRestoreWorkflow()+ const { mutateAsync: restoreWorkflow } = useRestoreWorkflow(resource)const handleRestore = useCallback(async (item: VersionHistory) => {@@ -271,7 +268,7 @@ export const VersionHistoryPanel = ({await emitRestoreIntent(item)try {- await restoreWorkflow(restoreVersionUrl(item.id))+ await restoreWorkflow(item.id)setCurrentVersion(item)workflowStore.setState({ isRestoring: false })workflowStore.setState({ backupDraft: undefined })@@ -294,7 +291,6 @@ export const VersionHistoryPanel = ({setShowWorkflowVersionHistoryPanel,emitRestoreIntent,restoreWorkflow,- restoreVersionUrl,setCurrentVersion,workflowStore,handleRefreshWorkflowDraft,@@ -343,8 +339,8 @@ export const VersionHistoryPanel = ({const { id, ...rest } = paramsawait updateWorkflow({- ...(configsMap?.flowType === FlowType.appFlow && configsMap.flowId- ? { appId: configsMap.flowId, appMode }+ ...(resource.kind === 'app' && resourceId+ ? { appId: resource.appId, appMode: resource.mode }: {}),url: updateVersionUrl?.(id || '') || '',...rest,@@ -352,12 +348,8 @@ export const VersionHistoryPanel = ({{onSuccess: () => {setEditModalOpen(false)- if (- id === latestVersionId &&- configsMap?.flowType === FlowType.appFlow &&- configsMap.flowId- )- invalidateAppWorkflow(configsMap.flowId)+ if (id === latestVersionId && resource.kind === 'app' && resourceId)+ invalidateAppWorkflow(resourceId)},onError: () => {toast.error(@@ -371,9 +363,8 @@ export const VersionHistoryPanel = ({)},[- appMode,- configsMap?.flowId,- configsMap?.flowType,+ resourceId,+ resource,invalidateAppWorkflow,latestVersionId,t,diff --git a/web/app/components/workflow/update-dsl-modal.helpers.ts b/web/app/components/workflow/update-dsl-modal.helpers.tsindex 3e8a01c84df..d0d9931111f 100644--- a/web/app/components/workflow/update-dsl-modal.helpers.ts+++ b/web/app/components/workflow/update-dsl-modal.helpers.ts@@ -3,7 +3,6 @@ import type { TFunction } from 'i18next'import type { CommonNodeType, Node } from './types'import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'import { DSLImportStatus } from '@/models/app'-import { AppModeEnum } from '@/types/app'import { loadYaml } from '@/utils/yaml'import { BlockEnum, SupportUploadFileTypes } from './types'@@ -46,7 +45,7 @@ type ImportNotificationPayload = {}export const getInvalidNodeTypes = (mode?: AppMode): BlockEnum[] => {- if (mode === AppModeEnum.ADVANCED_CHAT) {+ if (mode === 'advanced-chat') {return [BlockEnum.End,BlockEnum.TriggerWebhook,diff --git a/web/app/components/workflow/utils/normalize-workflow-nodes.ts b/web/app/components/workflow/utils/normalize-workflow-nodes.tsindex bf06065b834..b40180afc7c 100644--- a/web/app/components/workflow/utils/normalize-workflow-nodes.ts+++ b/web/app/components/workflow/utils/normalize-workflow-nodes.ts@@ -1,11 +1,10 @@-import { AppModeEnum } from '@/types/app'import { BlockEnum } from '../types'export const normalizeWorkflowNodes = <T extends { data: Record<string, unknown> }>(nodes: T[],appMode?: string,): T[] => {- if (appMode !== AppModeEnum.WORKFLOW) return nodes+ if (appMode !== 'workflow') return nodesreturn nodes.map((node) => {if (node.data.type !== BlockEnum.LLM || !('memory' in node.data)) return nodediff --git a/web/app/components/workflow/variable-inspect/__tests__/resource-requests.spec.tsx b/web/app/components/workflow/variable-inspect/__tests__/resource-requests.spec.tsxnew file mode 100644index 00000000000..21cffefcf75--- /dev/null+++ b/web/app/components/workflow/variable-inspect/__tests__/resource-requests.spec.tsx@@ -0,0 +1,243 @@+import type {+ WorkflowDraftVariableResponse,+ WorkflowDraftVariableWithoutValueResponse,+} from '@dify/contracts/api/console/apps/types.gen'+import type { EditorResource } from '../../editor-resource/resource'+import { act, renderHook, waitFor } from '@testing-library/react'+import { consoleQuery } from '@/service/console'+import {+ useConversationVarValues,+ useDeleteAllInspectorVars,+ useDeleteInspectVar,+ useDeleteNodeInspectorVars,+ useEditInspectorVar,+ useInvalidateAllLastRun,+ useInvalidateConversationVarValues,+ useInvalidateLastRun,+ useInvalidateSysVarValues,+ useResetInspectorVar,+ useSysVarValues,+} from '@/service/use-workflow'+import { fetchAllInspectVars, fetchNodeInspectVars } from '@/service/workflow'+import { createQueryClientWrapper } from '@/test/console/query-client'+import { createTestQueryClient } from '@/test/query-client'++const request = vi.hoisted(() =>+ vi.fn<+ (url: string, init: RequestInit | undefined, options: { request: Request }) => Promise<Response>+ >(),+)+vi.mock('@/service/base', () => ({ request }))++const summary: WorkflowDraftVariableWithoutValueResponse = {+ id: 'variable-1',+ type: 'node',+ name: 'answer',+ description: '',+ selector: ['node-1', 'answer'],+ value_type: 'string',+ edited: false,+ visible: true,+ is_truncated: false,+}+const variable: WorkflowDraftVariableResponse = { ...summary, value: 'result', full_content: null }+const hosts: { resource: EditorResource; prefix: string }[] = [+ { resource: { kind: 'app', appId: 'workflow-1', mode: 'workflow' }, prefix: '/apps/workflow-1' },+ {+ resource: { kind: 'app', appId: 'chatflow-1', mode: 'advanced-chat' },+ prefix: '/apps/chatflow-1',+ },+ {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ prefix: '/rag/pipelines/pipeline-1',+ },+ { resource: { kind: 'snippet', snippetId: 'snippet-1' }, prefix: '/snippets/snippet-1' },+]++beforeEach(() => {+ request.mockReset()+})++describe.each(hosts)('inspector requests for $prefix', ({ resource, prefix }) => {+ it('loads every summary page, then loads values for the selected node through the same resource', async () => {+ request.mockImplementation(async (url) => {+ const path = new URL(url)+ if (path.pathname.endsWith('/nodes/node-1/variables'))+ return Response.json({ items: [variable] })+ return Response.json({+ total: 101,+ items:+ path.searchParams.get('page') === '1'+ ? Array.from({ length: 100 }, (_, index) => ({ ...summary, id: `variable-${index}` }))+ : [{ ...summary, id: 'variable-last' }],+ })+ })+ const summaries = await fetchAllInspectVars(resource)+ expect(summaries).toHaveLength(101)+ expect(summaries[0]).not.toHaveProperty('value')+ expect(await fetchNodeInspectVars(resource, 'node-1')).toEqual([variable])+ expect(request.mock.calls.map(([url]) => new URL(url).pathname)).toEqual([+ `/console/api${prefix}/workflows/draft/variables`,+ `/console/api${prefix}/workflows/draft/variables`,+ `/console/api${prefix}/workflows/draft/nodes/node-1/variables`,+ ])+ })++ it('routes edits, reset and deletions without treating another resource ID as an app ID', async () => {+ request.mockImplementation(async (_url, _init, { request }) =>+ request.method === 'DELETE' || request.method === 'PUT'+ ? new Response(null, { status: 204 })+ : Response.json(variable),+ )+ const client = createTestQueryClient()+ const { result } = renderHook(+ () => ({+ edit: useEditInspectorVar(resource),+ reset: useResetInspectorVar(resource),+ remove: useDeleteInspectVar(resource),+ removeNode: useDeleteNodeInspectorVars(resource),+ removeAll: useDeleteAllInspectorVars(resource),+ }),+ { wrapper: createQueryClientWrapper(client) },+ )+ await act(async () => {+ await result.current.edit.mutateAsync({ varId: 'variable-1', value: 'changed' })+ await result.current.reset.mutateAsync('variable-1')+ await result.current.remove.mutateAsync('variable-1')+ await result.current.removeNode.mutateAsync('node-1')+ await result.current.removeAll.mutateAsync()+ })+ const requests = request.mock.calls.map(([, , options]) => options.request)+ expect(requests.map((request) => request.method)).toEqual([+ 'PATCH',+ 'PUT',+ 'DELETE',+ 'DELETE',+ 'DELETE',+ ])+ expect(requests.map((request) => new URL(request.url).pathname)).toEqual([+ `/console/api${prefix}/workflows/draft/variables/variable-1`,+ `/console/api${prefix}/workflows/draft/variables/variable-1/reset`,+ `/console/api${prefix}/workflows/draft/variables/variable-1`,+ `/console/api${prefix}/workflows/draft/nodes/node-1/variables`,+ `/console/api${prefix}/workflows/draft/variables`,+ ])+ expect(await requests[0]!.json()).toEqual({ value: 'changed' })+ })+})++it('invalidates only the current app variable queries and leaves other editors cached', async () => {+ request.mockResolvedValue(Response.json({ items: [variable] }))+ const client = createTestQueryClient()+ const current: EditorResource = { kind: 'app', appId: 'app-1', mode: 'advanced-chat' }+ const input = (appId: string) => ({ input: { params: { app_id: appId } } })+ const conversation = consoleQuery.apps.byAppId.workflows.draft.conversationVariables.get+ const system = consoleQuery.apps.byAppId.workflows.draft.systemVariables.get+ for (const appId of ['app-1', 'app-2']) {+ client.setQueryData(conversation.queryKey(input(appId)), { items: [] })+ client.setQueryData(system.queryKey(input(appId)), { items: [] })+ }+ const { result } = renderHook(+ () => ({+ conversation: useInvalidateConversationVarValues(current),+ system: useInvalidateSysVarValues(current),+ }),+ { wrapper: createQueryClientWrapper(client) },+ )+ await act(async () => {+ await result.current.conversation()+ await result.current.system()+ })+ expect(client.getQueryState(conversation.queryKey(input('app-1')))?.isInvalidated).toBe(true)+ expect(client.getQueryState(system.queryKey(input('app-1')))?.isInvalidated).toBe(true)+ expect(client.getQueryState(conversation.queryKey(input('app-2')))?.isInvalidated).toBe(false)+ expect(client.getQueryState(system.queryKey(input('app-2')))?.isInvalidated).toBe(false)+ expect(request).not.toHaveBeenCalled()+})++it.each(hosts.filter(({ resource }) => resource.kind !== 'app'))(+ 'does not request app-only variables for $prefix',+ async ({ resource }) => {+ const { result } = renderHook(+ () => ({+ conversation: useConversationVarValues(resource),+ system: useSysVarValues(resource),+ }),+ { wrapper: createQueryClientWrapper(createTestQueryClient()) },+ )+ await waitFor(() => expect(result.current.conversation.fetchStatus).toBe('idle'))+ expect(result.current.system.fetchStatus).toBe('idle')+ expect(request).not.toHaveBeenCalled()+ },+)++const lastRunTargets = [+ {+ resource: { kind: 'app', appId: 'shared-id', mode: 'workflow' },+ keyForNode: (nodeId: string) =>+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.lastRun.get.queryKey({+ input: { params: { app_id: 'shared-id', node_id: nodeId } },+ }),+ },+ {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'shared-id' },+ keyForNode: (nodeId: string) =>+ consoleQuery.rag.pipelines.byPipelineId.workflows.draft.nodes.byNodeId.lastRun.get.queryKey({+ input: { params: { pipeline_id: 'shared-id', node_id: nodeId } },+ }),+ },+ {+ resource: { kind: 'snippet', snippetId: 'shared-id' },+ keyForNode: (nodeId: string) =>+ consoleQuery.snippets.bySnippetId.workflows.draft.nodes.byNodeId.lastRun.get.queryKey({+ input: { params: { snippet_id: 'shared-id', node_id: nodeId } },+ }),+ },+ {+ resource: { kind: 'app', appId: 'other-app', mode: 'advanced-chat' },+ keyForNode: (nodeId: string) =>+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.lastRun.get.queryKey({+ input: { params: { app_id: 'other-app', node_id: nodeId } },+ }),+ },+] satisfies { resource: EditorResource; keyForNode: (nodeId: string) => readonly unknown[] }[]++it.each(lastRunTargets)(+ 'isolates node and whole-resource last-run invalidation for $resource',+ async (target) => {+ const client = createTestQueryClient()+ const cachedRuns = lastRunTargets.flatMap((entry) =>+ ['node-1', 'node-2'].map((nodeId) => ({+ target: entry,+ nodeId,+ queryKey: entry.keyForNode(nodeId),+ })),+ )+ for (const { queryKey, nodeId } of cachedRuns)+ client.setQueryData(queryKey, { id: `run-${nodeId}`, node_id: nodeId, status: 'succeeded' })++ const { result } = renderHook(+ () => ({+ invalidateNode: useInvalidateLastRun(target.resource, 'node-1'),+ invalidateResource: useInvalidateAllLastRun(target.resource),+ }),+ { wrapper: createQueryClientWrapper(client) },+ )++ await act(async () => {+ await result.current.invalidateNode()+ })+ for (const entry of cachedRuns)+ expect(client.getQueryState(entry.queryKey)?.isInvalidated).toBe(+ entry.target === target && entry.nodeId === 'node-1',+ )++ await act(async () => {+ await result.current.invalidateResource()+ })+ for (const entry of cachedRuns)+ expect(client.getQueryState(entry.queryKey)?.isInvalidated).toBe(entry.target === target)++ expect(request).not.toHaveBeenCalled()+ },+)diff --git a/web/app/components/workflow/variable-inspect/__tests__/value-content.helpers.spec.ts b/web/app/components/workflow/variable-inspect/__tests__/value-content.helpers.spec.tsindex a2bf049c554..b6beb6df553 100644--- a/web/app/components/workflow/variable-inspect/__tests__/value-content.helpers.spec.ts+++ b/web/app/components/workflow/variable-inspect/__tests__/value-content.helpers.spec.ts@@ -71,7 +71,16 @@ describe('value-content helpers', () => {createVar({name: 'file',value_type: VarType.file,- value: { id: 'file-1' },+ value: {+ id: 'file-1',+ filename: 'report.pdf',+ mime_type: 'application/pdf',+ type: 'document',+ transfer_method: 'remote_url',+ related_id: null,+ remote_url: 'https://example.com/report.pdf',+ size: 12,+ },}),),).toHaveLength(1)@@ -84,7 +93,16 @@ describe('value-content helpers', () => {type: VarInInspectType.system,name: 'files',value_type: VarType.arrayFile,- value: [{ id: 'file-2' }],+ value: [+ {+ id: 'file-2',+ filename: 'photo.png',+ type: 'image',+ transfer_method: 'local_file',+ related_id: 'upload-2',+ size: 20,+ },+ ],}),),).toHaveLength(1)diff --git a/web/app/components/workflow/variable-inspect/display-content.tsx b/web/app/components/workflow/variable-inspect/display-content.tsxindex fe2f9768030..053d83f62a6 100644--- a/web/app/components/workflow/variable-inspect/display-content.tsx+++ b/web/app/components/workflow/variable-inspect/display-content.tsx@@ -1,4 +1,3 @@-import type { VarType } from '../types'import type { ChunkInfo } from '@/app/components/rag-pipeline/components/chunk-card-list/types'import type { ParentMode } from '@/models/datasets'import { cn } from '@langgenius/dify-ui/cn'@@ -14,7 +13,7 @@ import { PreviewType, ViewMode } from './types'type DisplayContentProps = {previewType: PreviewType- varType: VarType+ varType: stringschemaType?: stringmdString?: stringjsonString?: stringdiff --git a/web/app/components/workflow/variable-inspect/right.tsx b/web/app/components/workflow/variable-inspect/right.tsxindex 7cfde70f957..d8233dfa81a 100644--- a/web/app/components/workflow/variable-inspect/right.tsx+++ b/web/app/components/workflow/variable-inspect/right.tsx@@ -5,6 +5,7 @@ import { IconButton, iconButtonVariants } from '@langgenius/dify-ui/icon-button'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { useBoolean } from 'ahooks'import { produce } from 'immer'+import { useAtomValue } from 'jotai'import { useCallback, useMemo } from 'react'import { useTranslation } from 'react-i18next'import GetAutomaticResModal from '@/app/components/app/configuration/config/automatic/get-automatic-res'@@ -12,13 +13,13 @@ import Badge from '@/app/components/base/badge'import { CopyFeedback } from '@/app/components/base/copy-feedback'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import BlockIcon from '@/app/components/workflow/block-icon'+import { getEditorResourceId } from '@/app/components/workflow/editor-resource/resource'+import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'import { VariableIconWithColor } from '@/app/components/workflow/nodes/_base/components/variable/variable-label'import { useEventEmitterContextContext } from '@/context/event-emitter'-import { AppModeEnum } from '@/types/app'import { VarInInspectType } from '@/types/workflow'import GetCodeGeneratorResModal from '../../app/configuration/config/code-generator/get-code-generator-res'import { PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER } from '../../base/prompt-editor/plugins/update-block'-import { useHooksStore } from '../hooks-store'import useCurrentVars from '../hooks/use-inspect-vars-crud'import { useNodesInteractions } from '../hooks/use-nodes-interactions'import { useToolIcon } from '../hooks/use-tool-icon'@@ -77,7 +78,8 @@ const Right = ({ nodeId, currentNodeVar, handleOpenMenu, isValueFetching }: Propreturn String(value)}- const configsMap = useHooksStore((s) => s.configsMap)+ const resource = useAtomValue(editorResourceAtom)+ const resourceId = getEditorResourceId(resource)const { eventEmitter } = useEventEmitterContextContext()const { handleNodeSelect } = useNodesInteractions()const { node } = useNodeInfo(nodeId)@@ -329,9 +331,9 @@ const Right = ({ nodeId, currentNodeVar, handleOpenMenu, isValueFetching }: Prop(isCodeBlock ? (<GetCodeGeneratorResModalisShow- mode={AppModeEnum.CHAT}+ modelMode="chat"onClose={handleHidePromptGenerator}- flowId={configsMap?.flowId || ''}+ flowId={resourceId || ''}nodeId={nodeId}currentCode={currentPrompt}codeLanguages={node?.data?.code_languages || CodeLanguage.python3}@@ -339,11 +341,11 @@ const Right = ({ nodeId, currentNodeVar, handleOpenMenu, isValueFetching }: Prop/>) : (<GetAutomaticResModal- mode={AppModeEnum.CHAT}+ modelMode="chat"isShowonClose={handleHidePromptGenerator}onFinished={handleUpdatePrompt}- flowId={configsMap?.flowId || ''}+ flowId={resourceId || ''}nodeId={nodeId}currentPrompt={currentPrompt}/>diff --git a/web/app/components/workflow/variable-inspect/value-content.helpers.ts b/web/app/components/workflow/variable-inspect/value-content.helpers.tsindex 46ccc3e1d70..19fa9dbc137 100644--- a/web/app/components/workflow/variable-inspect/value-content.helpers.ts+++ b/web/app/components/workflow/variable-inspect/value-content.helpers.ts@@ -1,4 +1,5 @@-import type { VarInInspect } from '@/types/workflow'+import type { FileResponse, VarInInspect } from '@/types/workflow'+import { zFileTransferMethod } from '@dify/contracts/api/console/apps/zod.gen'import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'import {checkJsonSchemaDepth,@@ -52,17 +53,45 @@ export const getValueEditorState = (currentVar: VarInInspect) => {}}+const toInspectFile = (value: unknown): FileResponse | undefined => {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined+ const transferMethod = zFileTransferMethod.safeParse(+ 'transfer_method' in value ? value.transfer_method : undefined,+ )+ if (!transferMethod.success) return undefined+ const stringField = (key: string) => {+ const field = Reflect.get(value, key)+ return typeof field === 'string' ? field : ''+ }+ return {+ related_id: stringField('related_id'),+ extension: stringField('extension'),+ filename: stringField('filename'),+ size: 'size' in value && typeof value.size === 'number' ? value.size : 0,+ mime_type: stringField('mime_type'),+ transfer_method: transferMethod.data,+ type: stringField('type'),+ url: stringField('url'),+ upload_file_id: stringField('upload_file_id'),+ remote_url: stringField('remote_url'),+ }+}+export const formatInspectFileValue = (currentVar: VarInInspect) => {- if (currentVar.value_type === 'file')- return currentVar.value ? getProcessedFilesFromResponse([currentVar.value]) : []- if (- currentVar.value_type === 'array[file]' ||- (currentVar.type === VarInInspectType.system && currentVar.name === 'files')+ const values =+ currentVar.value_type === 'file'+ ? [currentVar.value]+ : (currentVar.value_type === 'array[file]' ||+ (currentVar.type === VarInInspectType.system && currentVar.name === 'files')) &&+ Array.isArray(currentVar.value)+ ? currentVar.value+ : []+ return getProcessedFilesFromResponse(+ values.flatMap((value) => {+ const file = toInspectFile(value)+ return file ? [file] : []+ }),)- return currentVar.value && currentVar.value.length > 0- ? getProcessedFilesFromResponse(currentVar.value)- : []- return []}export const validateInspectJsonValue = (value: string, type: string) => {diff --git a/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts b/web/app/components/workflow/workflow-generator/__tests__/apply.spec.tsindex f73be396cd8..e319a3b6122 100644--- a/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts+++ b/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts@@ -2,7 +2,6 @@ import type { GeneratedGraph } from '../types'import { BlockEnum } from '@/app/components/workflow/types'import { createHttpError } from '@/service/http-error'import { createAppDetailFixture } from '@/test/fixtures/app'-import { AppModeEnum } from '@/types/app'import {applyToCurrentApp,applyToNewApp,@@ -69,7 +68,7 @@ describe('applyToNewApp', () => {beforeEach(() => {vi.clearAllMocks()mockCreateApp.mockResolvedValue(- createAppDetailFixture({ id: 'new-app-1', mode: AppModeEnum.WORKFLOW }),+ createAppDetailFixture({ id: 'new-app-1', mode: 'workflow' as const }),)mockSyncWorkflowDraft.mockResolvedValue({})})@@ -78,11 +77,15 @@ describe('applyToNewApp', () => {// its draft and return the routing context the caller uses to navigate.it('should create the app, sync the draft and return the new app id and mode', async () => {const graph = makeGraph()- const result = await applyToNewApp({ mode: 'workflow', graph, instruction: 'Summarize a URL' })+ const result = await applyToNewApp({+ mode: 'workflow',+ graph,+ instruction: 'Summarize a URL',+ })expect(mockCreateApp).toHaveBeenCalledWith(expect.objectContaining({- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow',icon_type: 'emoji',}),)@@ -96,16 +99,16 @@ describe('applyToNewApp', () => {})expect(result).toEqual({appId: 'new-app-1',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,permissionKeys: [],})})- // Mode → AppModeEnum must round-trip for chatflow; the type-level guarantee+ // Mode → AppMode must round-trip for chatflow; the type-level guarantee// is verified at runtime so a regression here is caught before users hit it.- it('should map advanced-chat mode to AppModeEnum.ADVANCED_CHAT', async () => {+ it('should map advanced-chat mode to Chatflow', async () => {mockCreateApp.mockResolvedValueOnce(- createAppDetailFixture({ id: 'cf-1', mode: AppModeEnum.ADVANCED_CHAT }),+ createAppDetailFixture({ id: 'cf-1', mode: 'advanced-chat' as const }),)const result = await applyToNewApp({@@ -115,9 +118,9 @@ describe('applyToNewApp', () => {})expect(mockCreateApp).toHaveBeenCalledWith(- expect.objectContaining({ mode: AppModeEnum.ADVANCED_CHAT }),+ expect.objectContaining({ mode: 'advanced-chat' as const }),)- expect(result.appMode).toBe(AppModeEnum.ADVANCED_CHAT)+ expect(result.appMode).toBe('advanced-chat')})it('should remove LLM memory before saving a generated Workflow draft', async () => {@@ -214,7 +217,7 @@ describe('applyToNewApp', () => {// and the original sync error is re-thrown so the caller can toast it.it('should delete the new app when syncWorkflowDraft fails', async () => {mockCreateApp.mockResolvedValueOnce(- createAppDetailFixture({ id: 'doomed', mode: AppModeEnum.WORKFLOW }),+ createAppDetailFixture({ id: 'doomed', mode: 'workflow' as const }),)const syncErr = new Error('sync exploded')mockSyncWorkflowDraft.mockRejectedValueOnce(syncErr)@@ -237,7 +240,7 @@ describe('applyToNewApp', () => {// carries the orphan app id so the toast can name it.it('should throw WorkflowApplyOrphanError when both sync and rollback fail', async () => {mockCreateApp.mockResolvedValueOnce(- createAppDetailFixture({ id: 'orphan-7', mode: AppModeEnum.WORKFLOW }),+ createAppDetailFixture({ id: 'orphan-7', mode: 'workflow' as const }),)mockSyncWorkflowDraft.mockRejectedValueOnce(new Error('sync exploded'))mockDeleteApp.mockRejectedValueOnce(new Error('delete also exploded'))@@ -262,7 +265,7 @@ describe('applyToCurrentApp', () => {it('should remove LLM memory before replacing the current Workflow draft', async () => {await applyToCurrentApp({appId: 'app-42',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,graph: makeGraphWithMemory(),})@@ -270,7 +273,7 @@ describe('applyToCurrentApp', () => {expect(savedGraph.nodes[1].data).not.toHaveProperty('memory')})- it.each([AppModeEnum.ADVANCED_CHAT, undefined])(+ it.each(['advanced-chat', undefined] as const)('should preserve LLM memory when the current app mode is %s',async (appMode) => {const graph = makeGraphWithMemory()diff --git a/web/app/components/workflow/workflow-generator/apply.ts b/web/app/components/workflow/workflow-generator/apply.tsindex 0437a7f604b..a084d9060a9 100644--- a/web/app/components/workflow/workflow-generator/apply.ts+++ b/web/app/components/workflow/workflow-generator/apply.ts@@ -1,5 +1,5 @@import type { GeneratedGraph, WorkflowGeneratorMode } from './types'-import type { AppModeEnum } from '@/types/app'+import type { WorkflowAppMode } from '@/app/components/apps/app-type'import { normalizeWorkflowNodes } from '@/app/components/workflow/utils/normalize-workflow-nodes'import { consoleClient } from '@/service/console'import { getHttpErrorStatus } from '@/service/http-error'@@ -8,7 +8,7 @@ import { fetchWorkflowDraft, syncWorkflowDraft } from '@/service/workflow'const MODE_TO_APP_MODE = {workflow: 'workflow','advanced-chat': 'advanced-chat',-} as const satisfies Record<WorkflowGeneratorMode, AppModeEnum>+} as const satisfies Record<WorkflowGeneratorMode, WorkflowAppMode>/*** Thrown by ``applyToCurrentApp`` when the backend rejects the sync because@@ -86,7 +86,7 @@ export const applyToNewApp = async ({icon,}: ApplyToNewAppParams): Promise<{appId: string- appMode: AppModeEnum+ appMode: WorkflowAppModepermissionKeys?: string[]}> => {const appMode = MODE_TO_APP_MODE[mode]@@ -134,7 +134,7 @@ export const applyToNewApp = async ({type ApplyToCurrentAppParams = {appId: string- appMode?: AppModeEnum+ appMode?: WorkflowAppModegraph: GeneratedGraph}diff --git a/web/context/debug-configuration.ts b/web/context/debug-configuration.tsindex c8498459dc2..d6632a3d7d9 100644--- a/web/context/debug-configuration.ts+++ b/web/context/debug-configuration.ts@@ -1,4 +1,5 @@import type { RefObject } from 'react'+import type { ConfigurationAppMode } from '@/app/components/app/configuration/hooks/configuration-lifecycle/types'import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { Collection } from '@/app/components/tools/types'import type { ExternalDataTool } from '@/models/common'@@ -31,7 +32,7 @@ import {DEFAULT_COMPLETION_PROMPT_CONFIG,} from '@/config'import { PromptMode } from '@/models/debug'-import { AppModeEnum, ModelModeType, Resolution, RETRIEVE_TYPE, TransferMethod } from '@/types/app'+import { ModelModeType, Resolution, RETRIEVE_TYPE, TransferMethod } from '@/types/app'type IDebugConfiguration = {readonly?: boolean@@ -39,7 +40,7 @@ type IDebugConfiguration = {onOpenFeatures: () => voidappId: stringisTrailFinished: boolean- mode: AppModeEnum+ mode: ConfigurationAppModemodelModeType: ModelModeTypepromptMode: PromptModesetPromptMode: (promptMode: PromptMode) => void@@ -122,7 +123,7 @@ const DebugConfigurationContext = createContext<IDebugConfiguration>({appId: '',onOpenFeatures: noop,isTrailFinished: false,- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,modelModeType: ModelModeType.chat,promptMode: PromptMode.simple,setPromptMode: noop,diff --git a/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsxindex 42c1e6dd90b..0123da264e7 100644--- a/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx+++ b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx@@ -23,7 +23,6 @@ import AppIcon from '@/app/components/base/app-icon'import { toast } from '@/app/notifications'import { getAgentACLCapabilities } from '@/features/agent-v2/acl'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'import { getAgentWebAppUrl } from '../../web-app-access'import { useWebAppAccessControl } from './use-web-app-access-control'@@ -325,7 +324,7 @@ function createSettingsAppInfo(agent: AgentAppDetailWithSite): SettingsAppInfo |return {id: appId,- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,site: {title: site.title ?? agent.name,description: site.description ?? '',diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsxindex c1ca4c1f9a8..ea289f167b6 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx@@ -1,4 +1,5 @@'use client'+import type { AgentKnowledgeDatasetConfig } from '@dify/contracts/api/console/agent/types.gen'import type { ReactNode } from 'react'import type {@@ -46,7 +47,7 @@ import {} from '@/features/agent-v2/agent-composer/knowledge-validation'import { agentComposerKnowledgeRetrievalsAtom } from '@/features/agent-v2/agent-composer/store-modules/knowledge'import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'-import { AppModeEnum, RETRIEVE_METHOD, RETRIEVE_TYPE } from '@/types/app'+import { RETRIEVE_METHOD, RETRIEVE_TYPE } from '@/types/app'type KnowledgeRetrievalQueryMode = 'agent' | 'custom'type MetadataFilteringConditions = {@@ -576,7 +577,7 @@ function AgentKnowledgeRetrievalDialogContent({model: {provider: model.provider,name: model.modelId,- mode: model.mode ?? singleRetrievalConfig?.model.mode ?? AppModeEnum.CHAT,+ mode: model.mode ?? singleRetrievalConfig?.model.mode ?? 'chat',completion_params: singleRetrievalConfig?.model.completion_params ?? {temperature: 0.7,},@@ -590,7 +591,7 @@ function AgentKnowledgeRetrievalDialogContent({model: {provider: singleRetrievalConfig?.model.provider ?? '',name: singleRetrievalConfig?.model.name ?? '',- mode: singleRetrievalConfig?.model.mode ?? AppModeEnum.CHAT,+ mode: singleRetrievalConfig?.model.mode ?? 'chat',completion_params: completionParams,},},@@ -688,7 +689,7 @@ function AgentKnowledgeRetrievalDialogContent({metadataModelConfig: {provider: model.provider,name: model.modelId,- mode: model.mode ?? metadataModelConfig?.mode ?? AppModeEnum.CHAT,+ mode: model.mode ?? metadataModelConfig?.mode ?? 'chat',completion_params: metadataModelConfig?.completion_params ?? { temperature: 0.7 },},})@@ -698,7 +699,7 @@ function AgentKnowledgeRetrievalDialogContent({metadataModelConfig: {provider: metadataModelConfig?.provider ?? '',name: metadataModelConfig?.name ?? '',- mode: metadataModelConfig?.mode ?? AppModeEnum.CHAT,+ mode: metadataModelConfig?.mode ?? 'chat',completion_params: completionParams,},})diff --git a/web/features/agent-v2/analytics.ts b/web/features/agent-v2/analytics.tsindex 36137a0f151..c3dfd4a68a0 100644--- a/web/features/agent-v2/analytics.ts+++ b/web/features/agent-v2/analytics.ts@@ -1,8 +1,6 @@-import { skipToken, useQuery } from '@tanstack/react-query'+import { useAtomValue } from 'jotai'import { trackEvent } from '@/app/components/base/amplitude'-import { useParams } from '@/next/navigation'-import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'+import { isChatflowAtom } from '@/app/components/workflow/editor-resource/state'export type AgentScope = (typeof AgentScope)[keyof typeof AgentScope]export const AgentScope = {@@ -12,15 +10,9 @@ export const AgentScope = {} as constexport const useInlineAgentScope = () => {- const { appId } = useParams<{ appId?: string }>()- const { data: appMode } = useQuery(- consoleQuery.apps.byAppId.get.queryOptions({- input: appId ? { params: { app_id: appId } } : skipToken,- select: (appDetail) => appDetail.mode,- }),- )+ const isChatflow = useAtomValue(isChatflowAtom)- return appMode === AppModeEnum.ADVANCED_CHAT ? AgentScope.InChatflow : AgentScope.InWorkflow+ return isChatflow ? AgentScope.InChatflow : AgentScope.InWorkflow}export const trackAgentBuildModeRun = (agentScope: AgentScope) => {diff --git a/web/features/home/__tests__/template-card.spec.tsx b/web/features/home/__tests__/template-card.spec.tsxindex 10e9cf6e2fb..74611d65d34 100644--- a/web/features/home/__tests__/template-card.spec.tsx+++ b/web/features/home/__tests__/template-card.spec.tsx@@ -8,7 +8,6 @@ import userEvent from '@testing-library/user-event'import * as React from 'react'import { trackEvent } from '@/app/components/base/amplitude'import { renderWithConsoleQuery } from '@/test/console/query-data'-import { AppModeEnum } from '@/types/app'import { TemplateCard } from '../template-card'vi.mock('@/app/components/app/type-selector', () => ({@@ -37,7 +36,7 @@ const createApp = (overrides: TemplateFixtureOverrides = {}): TemplateFixture =>...overrides,app: {id: 'id-1',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,icon_type: null,icon: '🤖',icon_background: '#fff',@@ -80,13 +79,13 @@ describe('TemplateCard', () => {})it.each([- [AppModeEnum.CHAT, 'APP.TYPES.CHATBOT'],- [AppModeEnum.ADVANCED_CHAT, 'APP.TYPES.ADVANCED'],- [AppModeEnum.AGENT_CHAT, 'APP.TYPES.AGENT'],- [AppModeEnum.AGENT, 'APP.TYPES.AGENT'],- [AppModeEnum.WORKFLOW, 'APP.TYPES.WORKFLOW'],- [AppModeEnum.COMPLETION, 'APP.TYPES.COMPLETION'],- ])('should render correct mode label for %s mode', (mode, label) => {+ ['chat', 'APP.TYPES.CHATBOT'],+ ['advanced-chat', 'APP.TYPES.ADVANCED'],+ ['agent-chat', 'APP.TYPES.AGENT'],+ ['agent', 'APP.TYPES.AGENT'],+ ['workflow', 'APP.TYPES.WORKFLOW'],+ ['completion', 'APP.TYPES.COMPLETION'],+ ] as const)('should render correct mode label for %s mode', (mode, label) => {renderComponent({ app: createApp({ app: { ...createApp().app, mode } }) })expect(screen.getByText(label)).toBeInTheDocument()@@ -120,7 +119,7 @@ describe('TemplateCard', () => {deploymentEdition = editionconst templateName = 'An Agent template with a full descriptive name'const app = createApp({- app: { mode: AppModeEnum.AGENT, name: templateName },+ app: { mode: 'agent' as const, name: templateName },description:'A full template description that remains available when visually truncated.',})@@ -144,7 +143,7 @@ describe('TemplateCard', () => {it('should make the app card clickable on cloud edition', () => {renderComponent({- app: createApp({ app: { ...createApp().app, mode: AppModeEnum.WORKFLOW } }),+ app: createApp({ app: { ...createApp().app, mode: 'workflow' as const } }),canCreate: true,})@@ -192,7 +191,7 @@ describe('TemplateCard', () => {(edition, action) => {deploymentEdition = editionrenderComponent({- app: createApp({ app: { mode: AppModeEnum.AGENT }, description: '' }),+ app: createApp({ app: { mode: 'agent' as const }, description: '' }),canCreate: true,})@@ -242,7 +241,7 @@ describe('TemplateCard', () => {it.each(['{Enter}', ' '])('opens an Agent template with %s from the keyboard', async (key) => {const user = userEvent.setup()- const app = createApp({ app: { mode: AppModeEnum.AGENT } })+ const app = createApp({ app: { mode: 'agent' as const } })renderComponent({ app, canCreate: true })diff --git a/web/features/home/home-content/__tests__/home-content.spec.tsx b/web/features/home/home-content/__tests__/home-content.spec.tsxindex 05ac7f68c6c..e524ed3cf7d 100644--- a/web/features/home/home-content/__tests__/home-content.spec.tsx+++ b/web/features/home/home-content/__tests__/home-content.spec.tsx@@ -1,4 +1,4 @@-import type { RecentAppResponse } from '@dify/contracts/api/console/apps/types.gen'+import type { AppMode, RecentAppResponse } from '@dify/contracts/api/console/apps/types.gen'import type {BannerResponse,RecommendedAppDetailResponse,@@ -28,7 +28,6 @@ import { consoleQuery } from '@/service/console'import { createConsoleQueryWrapper } from '@/test/console/query-data'import { seedRegisteredConsoleStateFixture } from '@/test/console/state-fixture'import { renderWithNuqs } from '@/test/nuqs-testing'-import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'import { HomeContent } from '../home-content'@@ -473,7 +472,7 @@ type AppFixtureOverrides = Omit<Partial<RecommendedAppResponse>, 'app'> & {const createApp = (overrides: AppFixtureOverrides = {}): AppFixture => ({app: {id: overrides.app?.id ?? 'app-basic-id',- mode: overrides.app?.mode ?? AppModeEnum.CHAT,+ mode: overrides.app?.mode ?? 'chat',icon_type: overrides.app?.icon_type ?? 'emoji',icon: overrides.app?.icon ?? '😀',icon_background: overrides.app?.icon_background ?? '#fff',@@ -1028,7 +1027,7 @@ describe('HomeContent', () => {name: 'Alpha',can_trial: true,export_data: 'yaml-content',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})mockHandleImportDSL.mockImplementation(async (_payload: unknown, options: { onSuccess?: () => void; onPending?: () => void }) => {@@ -1036,8 +1035,8 @@ describe('HomeContent', () => {},)mockHandleImportDSLConfirm.mockImplementation(- async (options: { onSuccess?: (payload: { app_mode: AppModeEnum }) => void }) => {- options.onSuccess?.({ app_mode: AppModeEnum.CHAT })+ async (options: { onSuccess?: (payload: { app_mode: AppMode }) => void }) => {+ options.onSuccess?.({ app_mode: 'chat' })},)@@ -1056,7 +1055,7 @@ describe('HomeContent', () => {expect(mockHandleImportDSLConfirm).toHaveBeenCalledTimes(1)expect(mockTrackCreateApp).toHaveBeenCalledWith({source: 'explore_template_list',- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,templateId: 'app-1',})})@@ -1073,7 +1072,7 @@ describe('HomeContent', () => {name: 'Alpha',can_trial: true,export_data: 'latest-yaml',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})mockHandleImportDSL.mockResolvedValue(undefined)const { queryClient } = renderHomeContent({ hasEditPermission: true })@@ -1082,7 +1081,7 @@ describe('HomeContent', () => {name: 'Alpha',can_trial: true,export_data: 'cached-yaml',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})await queryClient.invalidateQueries({queryKey: recommendedAppQueryKey('app-1'),@@ -1131,14 +1130,14 @@ describe('HomeContent', () => {name: 'Alpha',can_trial: true,export_data: 'yaml-content',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})mockHandleImportDSL.mockImplementation(async (_payload: unknown,- options: { onSuccess?: (payload: { app_mode: AppModeEnum }) => void },+ options: { onSuccess?: (payload: { app_mode: AppMode }) => void },) => {- options.onSuccess?.({ app_mode: AppModeEnum.CHAT })+ options.onSuccess?.({ app_mode: 'chat' })},)@@ -1272,14 +1271,14 @@ describe('HomeContent', () => {name: 'Alpha',can_trial: true,export_data: 'yaml-content',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})mockHandleImportDSL.mockImplementation(async (_payload: unknown,- options: { onSuccess?: (payload: { app_mode: AppModeEnum }) => void },+ options: { onSuccess?: (payload: { app_mode: AppMode }) => void },) => {- options.onSuccess?.({ app_mode: AppModeEnum.CHAT })+ options.onSuccess?.({ app_mode: 'chat' })},)@@ -1332,14 +1331,14 @@ describe('HomeContent', () => {name: 'Alpha',can_trial: true,export_data: 'yaml-content',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})mockHandleImportDSL.mockImplementation(async (_payload: unknown,- options: { onSuccess?: (payload: { app_mode: AppModeEnum }) => void },+ options: { onSuccess?: (payload: { app_mode: AppMode }) => void },) => {- options.onSuccess?.({ app_mode: AppModeEnum.CHAT })+ options.onSuccess?.({ app_mode: 'chat' })},)@@ -1400,7 +1399,7 @@ describe('HomeContent', () => {name: 'Alpha',can_trial: true,export_data: 'yaml-content',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})mockHandleImportDSL.mockImplementation(async (_payload: unknown, options: { onPending?: () => void }) => {@@ -1408,8 +1407,8 @@ describe('HomeContent', () => {},)mockHandleImportDSLConfirm.mockImplementation(- async (options: { onSuccess?: (payload: { app_mode: AppModeEnum }) => void }) => {- options.onSuccess?.({ app_mode: AppModeEnum.CHAT })+ async (options: { onSuccess?: (payload: { app_mode: AppMode }) => void }) => {+ options.onSuccess?.({ app_mode: 'chat' })},)@@ -1500,7 +1499,7 @@ describe('HomeContent', () => {name: 'Alpha',can_trial: true,export_data: 'yaml',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})renderHomeContent({ hasEditPermission: true })@@ -1525,14 +1524,14 @@ describe('HomeContent', () => {name: 'Alpha',can_trial: true,export_data: 'yaml',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})mockHandleImportDSL.mockImplementation(async (_payload: unknown,- options: { onSuccess?: (payload: { app_mode: AppModeEnum }) => void },+ options: { onSuccess?: (payload: { app_mode: AppMode }) => void },) => {- options.onSuccess?.({ app_mode: AppModeEnum.CHAT })+ options.onSuccess?.({ app_mode: 'chat' })},)@@ -1556,7 +1555,7 @@ describe('HomeContent', () => {name: 'Alpha',can_trial: true,export_data: 'yaml',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})mockHandleImportDSL.mockImplementation(async (_payload: unknown, options: { onPending?: () => void }) => {@@ -1610,14 +1609,14 @@ describe('HomeContent', () => {name: 'Alpha',can_trial: true,export_data: 'yaml',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,})mockHandleImportDSL.mockImplementation(async (_payload: unknown,- options: { onSuccess?: (payload: { app_mode: AppModeEnum }) => void },+ options: { onSuccess?: (payload: { app_mode: AppMode }) => void },) => {- options.onSuccess?.({ app_mode: AppModeEnum.CHAT })+ options.onSuccess?.({ app_mode: 'chat' })},)@@ -1631,7 +1630,7 @@ describe('HomeContent', () => {await waitFor(() => {expect(mockTrackCreateApp).toHaveBeenCalledWith({source: 'explore_template_preview',- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,templateId: 'app-1',})})diff --git a/web/features/home/template-card.tsx b/web/features/home/template-card.tsxindex 2ab49f36c53..089b5c0c046 100644--- a/web/features/home/template-card.tsx+++ b/web/features/home/template-card.tsx@@ -1,4 +1,5 @@'use client'+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import { cn } from '@langgenius/dify-ui/cn'import { useSuspenseQuery } from '@tanstack/react-query'@@ -8,7 +9,6 @@ import { AppTypeIcon } from '@/app/components/app/type-selector'import { trackEvent } from '@/app/components/base/amplitude'import AppIcon from '@/app/components/base/app-icon'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { AppModeEnum } from '@/types/app'type TemplateCardProps = {app: RecommendedAppResponse@@ -91,27 +91,27 @@ export function TemplateCard({ app, canCreate, onCreate, onTry }: TemplateCardPr</div></div><div className="flex items-center system-2xs-medium-uppercase text-text-tertiary">- {appMode === AppModeEnum.ADVANCED_CHAT && (+ {appMode === 'advanced-chat' && (<div className="truncate">{t(($) => $['types.advanced'], { ns: 'app' }).toUpperCase()}</div>)}- {appMode === AppModeEnum.CHAT && (+ {appMode === 'chat' && (<div className="truncate">{t(($) => $['types.chatbot'], { ns: 'app' }).toUpperCase()}</div>)}- {(appMode === AppModeEnum.AGENT_CHAT || appMode === AppModeEnum.AGENT) && (+ {(appMode === 'agent-chat' || appMode === 'agent') && (<div className="truncate">{t(($) => $['types.agent'], { ns: 'app' }).toUpperCase()}</div>)}- {appMode === AppModeEnum.WORKFLOW && (+ {appMode === 'workflow' && (<div className="truncate">{t(($) => $['types.workflow'], { ns: 'app' }).toUpperCase()}</div>)}- {appMode === AppModeEnum.COMPLETION && (+ {appMode === 'completion' && (<div className="truncate">{t(($) => $['types.completion'], { ns: 'app' }).toUpperCase()}</div>diff --git a/web/hooks/use-import-dsl.spec.tsx b/web/hooks/use-import-dsl.spec.tsxindex 9ed470e595d..b917415acce 100644--- a/web/hooks/use-import-dsl.spec.tsx+++ b/web/hooks/use-import-dsl.spec.tsx@@ -2,7 +2,6 @@ import { act, render, screen, waitFor } from '@testing-library/react'import { DSLImportMode, DSLImportStatus } from '@/models/app'import { httpErrorFromResponse } from '@/service/http-error'import { renderHookWithConsoleQuery } from '@/test/console/query-data'-import { AppModeEnum } from '@/types/app'import { useImportDSL } from './use-import-dsl'const mockPush = vi.hoisted(() => vi.fn())@@ -121,7 +120,7 @@ describe('useImportDSL', () => {id: 'import-1',status: DSLImportStatus.COMPLETED_WITH_WARNINGS,app_id: 'app-1',- app_mode: AppModeEnum.WORKFLOW,+ app_mode: 'workflow',permission_keys: [],warnings: [{@@ -161,7 +160,7 @@ describe('useImportDSL', () => {const pendingResponse = {id: 'import-1',status: DSLImportStatus.PENDING,- app_mode: AppModeEnum.AGENT,+ app_mode: 'agent',imported_dsl_version: '0.2.0',current_dsl_version: '0.1.0',permission_keys: [],@@ -170,7 +169,7 @@ describe('useImportDSL', () => {id: 'import-1',status: DSLImportStatus.COMPLETED_WITH_WARNINGS,app_id: 'app-1',- app_mode: AppModeEnum.AGENT,+ app_mode: 'agent',permission_keys: ['app.acl.view_layout'],warnings: [{@@ -235,7 +234,7 @@ describe('useImportDSL', () => {expect(mockHandleCheckPluginDependencies).toHaveBeenCalledWith('app-1')expect(mockResolveImportedAppRedirectionTarget).toHaveBeenCalledWith({id: 'app-1',- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,permission_keys: ['app.acl.view_layout'],})expect(mockGetRedirection).toHaveBeenCalledTimes(1)diff --git a/web/models/datasets.ts b/web/models/datasets.tsindex e4c9f044536..9d530c7ff2b 100644--- a/web/models/datasets.ts+++ b/web/models/datasets.ts@@ -1,10 +1,11 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { TagResponse as Tag } from '@dify/contracts/api/console/tags/types.gen'import type { DataSourceNotionPage, DataSourceProvider } from './common'import type { DatasourceType } from './pipeline'import type { IndexingType } from '@/app/components/datasets/create/step-two'import type { MetadataItemWithValue } from '@/app/components/datasets/metadata/types'import type { MetadataFilteringVariableType } from '@/app/components/workflow/nodes/knowledge-retrieval/types'-import type { AppIconType, AppModeEnum, RetrievalConfig, TransferMethod } from '@/types/app'+import type { AppIconType, RetrievalConfig, TransferMethod } from '@/types/app'import type { SegmentImportStatus } from '@/types/dataset'import type { I18nKeysByPrefix } from '@/types/i18n'import { PermissionLevel } from './permission'@@ -689,7 +690,7 @@ export type ExternalKnowledgeBaseHitTestingResponse = {export type RelatedApp = {id: stringname: string- mode: AppModeEnum+ mode: AppModeicon_type: AppIconType | nullicon: stringicon_background: stringdiff --git a/web/service/__tests__/use-workflow.spec.tsx b/web/service/__tests__/use-workflow.spec.tsxindex 447326d53b9..d345925a129 100644--- a/web/service/__tests__/use-workflow.spec.tsx+++ b/web/service/__tests__/use-workflow.spec.tsx@@ -10,6 +10,7 @@ import type {} from '@dify/contracts/enterprise-app-deploy/types.gen'import type { InfiniteData } from '@tanstack/react-query'import type { ReactNode } from 'react'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import {DeploymentOperationStatus,DeploymentOperationType,@@ -21,8 +22,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, renderHook } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'-import { usePublishWorkflow, useUpdateWorkflow } from '../use-workflow'+import { usePublishWorkflow, useRestoreWorkflow, useUpdateWorkflow } from '../use-workflow'import {appWorkflowQueryOptions,appWorkflowVersionsInfiniteQueryKey,@@ -31,8 +31,10 @@ import {const mockPatch = vi.hoisted(() => vi.fn())const mockPost = vi.hoisted(() => vi.fn())+const mockRequest = vi.hoisted(() => vi.fn())vi.mock('../base', () => ({+ request: (...args: unknown[]) => mockRequest(...args),del: vi.fn(),get: vi.fn(),patch: (...args: unknown[]) => mockPatch(...args),@@ -175,7 +177,7 @@ describe('useUpdateWorkflow', () => {})})- it.each([AppModeEnum.WORKFLOW, AppModeEnum.ADVANCED_CHAT])(+ it.each(['workflow', 'advanced-chat'] as const)('should synchronize every cached app deployment reference to the updated workflow version (%s)',async (appMode) => {const queryClient = createQueryClient()@@ -384,7 +386,7 @@ describe('useUpdateWorkflow', () => {await act(async () => {await result.current.mutateAsync({appId: 'app-1',- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,url: '/apps/app-1/workflows/workflow-1',title: 'New release',releaseNotes: 'New notes',@@ -437,3 +439,41 @@ describe('useUpdateWorkflow', () => {).toEqual({ environment_deployments: [deployment] })})})++describe('useRestoreWorkflow', () => {+ const resources = [+ { resource: { kind: 'app', appId: 'app-1', mode: 'advanced-chat' }, path: '/apps/app-1' },+ {+ resource: { kind: 'knowledge-pipeline', pipelineId: 'pipeline-1' },+ path: '/rag/pipelines/pipeline-1',+ },+ { resource: { kind: 'snippet', snippetId: 'snippet-1' }, path: '/snippets/snippet-1' },+ ] satisfies { resource: EditorResource; path: string }[]++ beforeEach(() => {+ mockRequest.mockReset()+ })++ it.each(resources)(+ 'restores the selected version for $resource.kind',+ async ({ resource, path }) => {+ mockRequest.mockResolvedValue(+ Response.json({ result: 'success', hash: 'restored-hash', updated_at: 1 }),+ )+ const { result } = renderHook(() => useRestoreWorkflow(resource), {+ wrapper: createWrapper(createQueryClient()),+ })+ await act(async () => {+ await expect(result.current.mutateAsync('version-1')).resolves.toEqual({+ result: 'success',+ hash: 'restored-hash',+ updated_at: 1,+ })+ })+ const [url, , options] = mockRequest.mock.calls[0]!+ expect(new URL(url).pathname).toBe(`/console/api${path}/workflows/version-1/restore`)+ expect(options.request.method).toBe('POST')+ expect(options.silent).toBe(true)+ },+ )+})diff --git a/web/service/debug.ts b/web/service/debug.tsindex 566521271f9..42b1c2585b7 100644--- a/web/service/debug.ts+++ b/web/service/debug.ts@@ -1,6 +1,7 @@+import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'import type { IOnCompleted, IOnData, IOnError, IOnMessageReplace } from './base'import type { ChatPromptConfig, CompletionPromptConfig } from '@/models/debug'-import type { AppModeEnum, ModelModeType } from '@/types/app'+import type { ModelModeType } from '@/types/app'import { get, post, ssePost } from './base'type BasicAppFirstRes = {@@ -95,7 +96,7 @@ export const fetchPromptTemplate = ({modelName,hasSetDataSet,}: {- appMode: AppModeEnum+ appMode: AppModemode: ModelModeTypemodelName: stringhasSetDataSet: booleandiff --git a/web/service/use-flow.ts b/web/service/use-flow.tsdeleted file mode 100644index 9dc4819a5df..00000000000--- a/web/service/use-flow.ts+++ /dev/null@@ -1,31 +0,0 @@-import type { FlowType } from '@/types/common'-import { curry } from 'es-toolkit/compat'-import {- useDeleteAllInspectorVars as useDeleteAllInspectorVarsInner,- useDeleteInspectVar as useDeleteInspectVarInner,- useDeleteNodeInspectorVars as useDeleteNodeInspectorVarsInner,- useEditInspectorVar as useEditInspectorVarInner,- useInvalidateConversationVarValues as useInvalidateConversationVarValuesInner,- useInvalidateSysVarValues as useInvalidateSysVarValuesInner,- useResetConversationVar as useResetConversationVarInner,- useResetToLastRunValue as useResetToLastRunValueInner,-} from './use-workflow'--type Params = {- flowType: FlowType-}--const useFLow = ({ flowType }: Params) => {- return {- useInvalidateConversationVarValues: curry(useInvalidateConversationVarValuesInner)(flowType),- useInvalidateSysVarValues: curry(useInvalidateSysVarValuesInner)(flowType),- useResetConversationVar: curry(useResetConversationVarInner)(flowType),- useResetToLastRunValue: curry(useResetToLastRunValueInner)(flowType),- useDeleteAllInspectorVars: curry(useDeleteAllInspectorVarsInner)(flowType),- useDeleteNodeInspectorVars: curry(useDeleteNodeInspectorVarsInner)(flowType),- useDeleteInspectVar: curry(useDeleteInspectVarInner)(flowType),- useEditInspectorVar: curry(useEditInspectorVarInner)(flowType),- }-}--export default useFLowdiff --git a/web/service/use-workflow.ts b/web/service/use-workflow.tsindex cb8211823ee..1a3f0645af1 100644--- a/web/service/use-workflow.ts+++ b/web/service/use-workflow.ts@@ -10,24 +10,25 @@ import type {WorkflowVersion,} from '@dify/contracts/enterprise-app-deploy/types.gen'import type { InfiniteData, QueryClient, UseQueryOptions } from '@tanstack/react-query'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type { CommonResponse } from '@/models/common'-import type { FlowType } from '@/types/common'import type {FetchWorkflowDraftPageParams,FetchWorkflowDraftPageResponse,- NodeTracing,PublishWorkflowParams,UpdateWorkflowParams,- VarInInspect,WorkflowConfigResponse,WorkflowRunHistoryResponse,} from '@/types/workflow'-import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'-import { consoleQuery } from '@/service/console'-import { AppModeEnum } from '@/types/app'-import { del, get, patch, post, put } from './base'-import { useInvalid } from './use-base'-import { getFlowPrefix } from './utils'+import {+ skipToken,+ useInfiniteQuery,+ useMutation,+ useQuery,+ useQueryClient,+} from '@tanstack/react-query'+import { consoleClient, consoleQuery } from '@/service/console'+import { del, get, patch, post } from './base'import { appWorkflowQueryOptions, appWorkflowVersionsInfiniteQueryKey } from './workflow-queries'const NAME_SPACE = 'workflow'@@ -279,8 +280,7 @@ export const useUpdateWorkflow = () => {if (params.appId) syncAppWorkflowVersionCaches(queryClient, params.appId, updatedWorkflow)const environmentDeploymentsQueryKey =- params.appId &&- (params.appMode === AppModeEnum.WORKFLOW || params.appMode === AppModeEnum.ADVANCED_CHAT)+ params.appId && (params.appMode === 'workflow' || params.appMode === 'advanced-chat')? syncWorkflowDeploymentCaches(queryClient, params.appId, updatedWorkflow): undefinedconst invalidations = [@@ -306,11 +306,28 @@ export const useDeleteWorkflow = () => {})}-export const useRestoreWorkflow = () => {+export const useRestoreWorkflow = (resource: EditorResource) => {return useMutation({mutationKey: [NAME_SPACE, 'restore'],- mutationFn: (url: string) =>- post<CommonResponse & { updated_at: number; hash: string }>(url, {}, { silent: true }),+ mutationFn: (versionId: string) => {+ switch (resource.kind) {+ case 'app':+ return consoleClient.apps.byAppId.workflows.byWorkflowId.restore.post(+ { params: { app_id: resource.appId, workflow_id: versionId } },+ { context: { silent: true } },+ )+ case 'knowledge-pipeline':+ return consoleClient.rag.pipelines.byPipelineId.workflows.byWorkflowId.restore.post(+ { params: { pipeline_id: resource.pipelineId, workflow_id: versionId } },+ { context: { silent: true } },+ )+ case 'snippet':+ return consoleClient.snippets.bySnippetId.workflows.byWorkflowId.restore.post(+ { params: { snippet_id: resource.snippetId, workflow_id: versionId } },+ { context: { silent: true } },+ )+ }+ },})}@@ -327,125 +344,219 @@ export const usePublishWorkflow = () => {})}-const useLastRunKey = [NAME_SPACE, 'last-run']-export const useLastRun = (- flowType: FlowType,- flowId: string,- nodeId: string,- enabled: boolean,-) => {- return useQuery<NodeTracing>({- enabled,- queryKey: [...useLastRunKey, flowType, flowId, nodeId],- queryFn: async () => {- return get(- `${getFlowPrefix(flowType)}/${flowId}/workflows/draft/nodes/${nodeId}/last-run`,- {},+function lastRunQueryOptions(resource: EditorResource, nodeId: string, enabled: boolean) {+ switch (resource.kind) {+ case 'app':+ return consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.lastRun.get.queryOptions({+ input: { params: { app_id: resource.appId, node_id: nodeId } },+ enabled,+ retry: 0,+ context: { silent: true },+ })+ case 'knowledge-pipeline':+ return consoleQuery.rag.pipelines.byPipelineId.workflows.draft.nodes.byNodeId.lastRun.get.queryOptions({- silent: true,+ input: { params: { pipeline_id: resource.pipelineId, node_id: nodeId } },+ enabled,+ retry: 0,+ context: { silent: true },},)- },- retry: 0,- })+ case 'snippet':+ return consoleQuery.snippets.bySnippetId.workflows.draft.nodes.byNodeId.lastRun.get.queryOptions(+ {+ input: { params: { snippet_id: resource.snippetId, node_id: nodeId } },+ enabled,+ retry: 0,+ context: { silent: true },+ },+ )+ }}--export const useInvalidLastRun = (flowType: FlowType, flowId: string, nodeId: string) => {- return useInvalid([...useLastRunKey, flowType, flowId, nodeId])+function lastRunQueryKey(resource: EditorResource, nodeId?: string) {+ switch (resource.kind) {+ case 'app':+ return consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.lastRun.get.key({+ type: 'query',+ input: { params: { app_id: resource.appId, ...(nodeId ? { node_id: nodeId } : {}) } },+ })+ case 'knowledge-pipeline':+ return consoleQuery.rag.pipelines.byPipelineId.workflows.draft.nodes.byNodeId.lastRun.get.key(+ {+ type: 'query',+ input: {+ params: { pipeline_id: resource.pipelineId, ...(nodeId ? { node_id: nodeId } : {}) },+ },+ },+ )+ case 'snippet':+ return consoleQuery.snippets.bySnippetId.workflows.draft.nodes.byNodeId.lastRun.get.key({+ type: 'query',+ input: {+ params: { snippet_id: resource.snippetId, ...(nodeId ? { node_id: nodeId } : {}) },+ },+ })+ }}+export const useLastRun = (resource: EditorResource, nodeId: string, enabled: boolean) =>+ useQuery(lastRunQueryOptions(resource, nodeId, enabled))-// Rerun workflow or change the version of workflow-export const useInvalidAllLastRun = (flowType?: FlowType, flowId?: string) => {- return useInvalid([...useLastRunKey, flowType, flowId])+export const useInvalidateLastRun = (resource: EditorResource, nodeId: string) => {+ const queryClient = useQueryClient()+ return () => queryClient.invalidateQueries({ queryKey: lastRunQueryKey(resource, nodeId) })}-export const useConversationVarValues = (flowType?: FlowType, flowId?: string) => {- return useQuery({- enabled: !!flowId,- queryKey: [NAME_SPACE, flowType, 'conversation var values', flowId],- queryFn: async () => {- const { items } = (await get(- `${getFlowPrefix(flowType)}/${flowId}/workflows/draft/conversation-variables`,- )) as { items: VarInInspect[] }- return items- },- })+export const useInvalidateAllLastRun = (resource: EditorResource) => {+ const queryClient = useQueryClient()+ return () => queryClient.invalidateQueries({ queryKey: lastRunQueryKey(resource) })}-export const useInvalidateConversationVarValues = (flowType: FlowType, flowId: string) => {- return useInvalid([NAME_SPACE, flowType, 'conversation var values', flowId])+export const useConversationVarValues = (resource: EditorResource | undefined) => {+ return useQuery(+ consoleQuery.apps.byAppId.workflows.draft.conversationVariables.get.queryOptions({+ input: resource?.kind === 'app' ? { params: { app_id: resource.appId } } : skipToken,+ select: (response) => response.items,+ }),+ )}-export const useResetConversationVar = (flowType: FlowType, flowId: string) => {- return useMutation({- mutationKey: [NAME_SPACE, flowType, 'reset conversation var', flowId],- mutationFn: async (varId: string) => {- return put(`${getFlowPrefix(flowType)}/${flowId}/workflows/draft/variables/${varId}/reset`)- },- })+export const useInvalidateConversationVarValues = (resource: EditorResource) => {+ const queryClient = useQueryClient()+ return () =>+ resource.kind === 'app'+ ? queryClient.invalidateQueries({+ queryKey: consoleQuery.apps.byAppId.workflows.draft.conversationVariables.get.queryKey({+ input: { params: { app_id: resource.appId } },+ }),+ })+ : Promise.resolve()}-export const useResetToLastRunValue = (flowType: FlowType, flowId: string) => {+export const useResetInspectorVar = (resource: EditorResource) => {return useMutation({- mutationKey: [NAME_SPACE, flowType, 'reset to last run value', flowId],- mutationFn: async (varId: string): Promise<{ value: any }> => {- return put(`${getFlowPrefix(flowType)}/${flowId}/workflows/draft/variables/${varId}/reset`)+ mutationFn: (varId: string) => {+ switch (resource.kind) {+ case 'app':+ return consoleClient.apps.byAppId.workflows.draft.variables.byVariableId.reset.put({+ params: { app_id: resource.appId, variable_id: varId },+ })+ case 'knowledge-pipeline':+ return consoleClient.rag.pipelines.byPipelineId.workflows.draft.variables.byVariableId.reset.put(+ { params: { pipeline_id: resource.pipelineId, variable_id: varId } },+ )+ case 'snippet':+ return consoleClient.snippets.bySnippetId.workflows.draft.variables.byVariableId.reset.put(+ { params: { snippet_id: resource.snippetId, variable_id: varId } },+ )+ }},})}-export const useSysVarValues = (flowType?: FlowType, flowId?: string) => {- return useQuery({- enabled: !!flowId,- queryKey: [NAME_SPACE, flowType, 'sys var values', flowId],- queryFn: async () => {- const { items } = (await get(- `${getFlowPrefix(flowType)}/${flowId}/workflows/draft/system-variables`,- )) as { items: VarInInspect[] }- return items- },- })+export const useSysVarValues = (resource: EditorResource | undefined) => {+ return useQuery(+ consoleQuery.apps.byAppId.workflows.draft.systemVariables.get.queryOptions({+ input: resource?.kind === 'app' ? { params: { app_id: resource.appId } } : skipToken,+ select: (response) => response.items,+ }),+ )}-export const useInvalidateSysVarValues = (flowType: FlowType, flowId: string) => {- return useInvalid([NAME_SPACE, flowType, 'sys var values', flowId])+export const useInvalidateSysVarValues = (resource: EditorResource) => {+ const queryClient = useQueryClient()+ return () =>+ resource.kind === 'app'+ ? queryClient.invalidateQueries({+ queryKey: consoleQuery.apps.byAppId.workflows.draft.systemVariables.get.queryKey({+ input: { params: { app_id: resource.appId } },+ }),+ })+ : Promise.resolve()}-export const useDeleteAllInspectorVars = (flowType: FlowType, flowId: string) => {+export const useDeleteAllInspectorVars = (resource: EditorResource) => {return useMutation({- mutationKey: [NAME_SPACE, flowType, 'delete all inspector vars', flowId],- mutationFn: async () => {- return del(`${getFlowPrefix(flowType)}/${flowId}/workflows/draft/variables`)+ mutationFn: () => {+ switch (resource.kind) {+ case 'app':+ return consoleClient.apps.byAppId.workflows.draft.variables.delete({+ params: { app_id: resource.appId },+ })+ case 'knowledge-pipeline':+ return consoleClient.rag.pipelines.byPipelineId.workflows.draft.variables.delete({+ params: { pipeline_id: resource.pipelineId },+ })+ case 'snippet':+ return consoleClient.snippets.bySnippetId.workflows.draft.variables.delete({+ params: { snippet_id: resource.snippetId },+ })+ }},})}-export const useDeleteNodeInspectorVars = (flowType: FlowType, flowId: string) => {+export const useDeleteNodeInspectorVars = (resource: EditorResource) => {return useMutation({- mutationKey: [NAME_SPACE, flowType, 'delete node inspector vars', flowId],- mutationFn: async (nodeId: string) => {- return del(`${getFlowPrefix(flowType)}/${flowId}/workflows/draft/nodes/${nodeId}/variables`)+ mutationFn: (nodeId: string) => {+ switch (resource.kind) {+ case 'app':+ return consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.variables.delete({+ params: { app_id: resource.appId, node_id: nodeId },+ })+ case 'knowledge-pipeline':+ return consoleClient.rag.pipelines.byPipelineId.workflows.draft.nodes.byNodeId.variables.delete(+ { params: { pipeline_id: resource.pipelineId, node_id: nodeId } },+ )+ case 'snippet':+ return consoleClient.snippets.bySnippetId.workflows.draft.nodes.byNodeId.variables.delete(+ { params: { snippet_id: resource.snippetId, node_id: nodeId } },+ )+ }},})}-export const useDeleteInspectVar = (flowType: FlowType, flowId: string) => {+export const useDeleteInspectVar = (resource: EditorResource) => {return useMutation({- mutationKey: [NAME_SPACE, flowType, 'delete inspector var', flowId],- mutationFn: async (varId: string) => {- return del(`${getFlowPrefix(flowType)}/${flowId}/workflows/draft/variables/${varId}`)+ mutationFn: (varId: string) => {+ switch (resource.kind) {+ case 'app':+ return consoleClient.apps.byAppId.workflows.draft.variables.byVariableId.delete({+ params: { app_id: resource.appId, variable_id: varId },+ })+ case 'knowledge-pipeline':+ return consoleClient.rag.pipelines.byPipelineId.workflows.draft.variables.byVariableId.delete(+ { params: { pipeline_id: resource.pipelineId, variable_id: varId } },+ )+ case 'snippet':+ return consoleClient.snippets.bySnippetId.workflows.draft.variables.byVariableId.delete({+ params: { snippet_id: resource.snippetId, variable_id: varId },+ })+ }},})}// edit the name or value of the inspector var-export const useEditInspectorVar = (flowType: FlowType, flowId: string) => {+export const useEditInspectorVar = (resource: EditorResource) => {return useMutation({- mutationKey: [NAME_SPACE, flowType, 'edit inspector var', flowId],- mutationFn: async ({ varId, ...rest }: { varId: string; name?: string; value?: any }) => {- return patch(`${getFlowPrefix(flowType)}/${flowId}/workflows/draft/variables/${varId}`, {- body: rest,- })+ mutationFn: ({ varId, ...body }: { varId: string; name?: string; value?: unknown }) => {+ switch (resource.kind) {+ case 'app':+ return consoleClient.apps.byAppId.workflows.draft.variables.byVariableId.patch({+ params: { app_id: resource.appId, variable_id: varId },+ body,+ })+ case 'knowledge-pipeline':+ return consoleClient.rag.pipelines.byPipelineId.workflows.draft.variables.byVariableId.patch(+ { params: { pipeline_id: resource.pipelineId, variable_id: varId }, body },+ )+ case 'snippet':+ return consoleClient.snippets.bySnippetId.workflows.draft.variables.byVariableId.patch({+ params: { snippet_id: resource.snippetId, variable_id: varId },+ body,+ })+ }},})}diff --git a/web/service/utils.ts b/web/service/utils.tsdeleted file mode 100644index 6677147c458..00000000000--- a/web/service/utils.ts+++ /dev/null@@ -1,11 +0,0 @@-import { FlowType } from '@/types/common'--const flowPrefixMap = {- [FlowType.appFlow]: 'apps',- [FlowType.ragPipeline]: 'rag/pipelines',- [FlowType.snippet]: 'snippets',-}--export const getFlowPrefix = (type?: FlowType) => {- return flowPrefixMap[type!] || flowPrefixMap[FlowType.appFlow]-}diff --git a/web/service/workflow.spec.ts b/web/service/workflow.spec.tsindex 4388e143171..2bc392aaf33 100644--- a/web/service/workflow.spec.ts+++ b/web/service/workflow.spec.ts@@ -2,15 +2,10 @@ import type { EnvironmentVariable } from '@/app/components/workflow/types'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import { updateEnvironmentVariables } from './workflow'-const mockPost = vi.hoisted(() => vi.fn())+const mockRequest = vi.hoisted(() => vi.fn())-vi.mock('./base', () => ({- get: vi.fn(),- post: mockPost,-}))--vi.mock('@/service/console', () => ({- consoleClient: {},+vi.mock('@/service/console/browser', () => ({+ consoleBrowserLink: { call: mockRequest },}))describe('updateEnvironmentVariables', () => {@@ -32,7 +27,7 @@ describe('updateEnvironmentVariables', () => {},},] satisfies EnvironmentVariable[]- mockPost.mockResolvedValue({ result: 'success' })+ mockRequest.mockResolvedValue({ result: 'success' })await updateEnvironmentVariables({appId: 'app-1',@@ -40,12 +35,17 @@ describe('updateEnvironmentVariables', () => {deletedEnvironmentVariableIds: ['env-2'],})- expect(mockPost).toHaveBeenCalledWith('apps/app-1/workflows/draft/environment-variables', {- body: {- environment_variables: environmentVariables,- patch: true,- deleted_environment_variable_ids: ['env-2'],+ expect(mockRequest).toHaveBeenCalledWith(+ ['apps', 'byAppId', 'workflows', 'draft', 'environmentVariables', 'post'],+ {+ params: { app_id: 'app-1' },+ body: {+ environment_variables: environmentVariables,+ patch: true,+ deleted_environment_variable_ids: ['env-2'],+ },},- })+ expect.any(Object),+ )})})diff --git a/web/service/workflow.ts b/web/service/workflow.tsindex 4d39477709c..3f4691487c2 100644--- a/web/service/workflow.ts+++ b/web/service/workflow.ts@@ -1,11 +1,14 @@-import type { WorkflowFeaturesConfigPayload } from '@dify/contracts/api/console/apps/types.gen'+import type {+ DraftWorkflowNodeRunPayload,+ WorkflowFeaturesConfigPayload,+} from '@dify/contracts/api/console/apps/types.gen'+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'import type {BlockEnum,ConversationVariable,EnvironmentVariable,} from '@/app/components/workflow/types'import type { CommonResponse } from '@/models/common'-import type { FlowType } from '@/types/common'import type {ConversationVariableResponse,FetchWorkflowDraftResponse,@@ -15,7 +18,6 @@ import type {} from '@/types/workflow'import { consoleClient } from '@/service/console'import { get, post } from './base'-import { getFlowPrefix } from './utils'export type WorkflowDraftFeaturesPayload = WorkflowFeaturesConfigPayload@@ -56,32 +58,27 @@ export const fetchNodesDefaultConfigs = (url: string) => {}export const singleNodeRun = (- flowType: FlowType,- flowId: string,- nodeId: string,- params: object,-) => {- return post(`${getFlowPrefix(flowType)}/${flowId}/workflows/draft/nodes/${nodeId}/run`, {- body: params,- })-}--export const getIterationSingleNodeRunUrl = (- flowType: FlowType,- isChatFlow: boolean,- flowId: string,- nodeId: string,-) => {- return `${getFlowPrefix(flowType)}/${flowId}/${isChatFlow ? 'advanced-chat/' : ''}workflows/draft/iteration/nodes/${nodeId}/run`-}--export const getLoopSingleNodeRunUrl = (- flowType: FlowType,- isChatFlow: boolean,- flowId: string,+ resource: EditorResource,nodeId: string,+ body: DraftWorkflowNodeRunPayload,) => {- return `${getFlowPrefix(flowType)}/${flowId}/${isChatFlow ? 'advanced-chat/' : ''}workflows/draft/loop/nodes/${nodeId}/run`+ switch (resource.kind) {+ case 'app':+ return consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.run.post({+ params: { app_id: resource.appId, node_id: nodeId },+ body,+ })+ case 'knowledge-pipeline':+ return consoleClient.rag.pipelines.byPipelineId.workflows.draft.nodes.byNodeId.run.post({+ params: { pipeline_id: resource.pipelineId, node_id: nodeId },+ body,+ })+ case 'snippet':+ return consoleClient.snippets.bySnippetId.workflows.draft.nodes.byNodeId.run.post({+ params: { snippet_id: resource.snippetId, node_id: nodeId },+ body,+ })+ }}export const stopWorkflowRun = (url: string) => {@@ -110,27 +107,33 @@ export const fetchCurrentValueOfConversationVariable = ({return get<ConversationVariableResponse>(url, { params })}-const fetchAllInspectVarsOnePage = async (- flowType: FlowType,- flowId: string,- page: number,-): Promise<{ total: number; items: VarInInspect[] }> => {- return get(`${getFlowPrefix(flowType)}/${flowId}/workflows/draft/variables`, {- params: { page, limit: 100 },- })-}-export const fetchAllInspectVars = async (- flowType: FlowType,- flowId: string,-): Promise<VarInInspect[]> => {- const res = await fetchAllInspectVarsOnePage(flowType, flowId, 1)+const fetchAllInspectVarsOnePage = (resource: EditorResource, page: number) => {+ switch (resource.kind) {+ case 'app':+ return consoleClient.apps.byAppId.workflows.draft.variables.get({+ params: { app_id: resource.appId },+ query: { page, limit: 100 },+ })+ case 'knowledge-pipeline':+ return consoleClient.rag.pipelines.byPipelineId.workflows.draft.variables.get({+ params: { pipeline_id: resource.pipelineId },+ query: { page, limit: 100 },+ })+ case 'snippet':+ return consoleClient.snippets.bySnippetId.workflows.draft.variables.get({+ params: { snippet_id: resource.snippetId },+ query: { page, limit: 100 },+ })+ }+}+export const fetchAllInspectVars = async (resource: EditorResource): Promise<VarInInspect[]> => {+ const res = await fetchAllInspectVarsOnePage(resource, 1)const { items, total } = res- if (total <= 100) return items+ if ((total ?? 0) <= 100) return items- const pageCount = Math.ceil(total / 100)+ const pageCount = Math.ceil((total ?? 0) / 100)const promises = []- for (let i = 2; i <= pageCount; i++)- promises.push(fetchAllInspectVarsOnePage(flowType, flowId, i))+ for (let i = 2; i <= pageCount; i++) promises.push(fetchAllInspectVarsOnePage(resource, i))const restData = await Promise.all(promises)restData.forEach(({ items: item }) => {@@ -139,15 +142,30 @@ export const fetchAllInspectVars = async (return items}-export const fetchNodeInspectVars = async (- flowType: FlowType,- flowId: string,- nodeId: string,-): Promise<VarInInspect[]> => {- const { items } = (await get(- `${getFlowPrefix(flowType)}/${flowId}/workflows/draft/nodes/${nodeId}/variables`,- )) as { items: VarInInspect[] }- return items+export const fetchNodeInspectVars = async (resource: EditorResource, nodeId: string) => {+ switch (resource.kind) {+ case 'app': {+ const { items } =+ await consoleClient.apps.byAppId.workflows.draft.nodes.byNodeId.variables.get({+ params: { app_id: resource.appId, node_id: nodeId },+ })+ return items+ }+ case 'knowledge-pipeline': {+ const { items } =+ await consoleClient.rag.pipelines.byPipelineId.workflows.draft.nodes.byNodeId.variables.get(+ { params: { pipeline_id: resource.pipelineId, node_id: nodeId } },+ )+ return items+ }+ case 'snippet': {+ const { items } =+ await consoleClient.snippets.bySnippetId.workflows.draft.nodes.byNodeId.variables.get({+ params: { snippet_id: resource.snippetId, node_id: nodeId },+ })+ return items+ }+ }}export const updateEnvironmentVariables = ({@@ -157,7 +175,8 @@ export const updateEnvironmentVariables = ({}: {appId: string} & EnvironmentVariablePatch) => {- return post<CommonResponse>(`apps/${appId}/workflows/draft/environment-variables`, {+ return consoleClient.apps.byAppId.workflows.draft.environmentVariables.post({+ params: { app_id: appId },body: {environment_variables: environmentVariables,patch: true,diff --git a/web/types/app.ts b/web/types/app.tsindex 165870b935c..b7b891de520 100644--- a/web/types/app.ts+++ b/web/types/app.ts@@ -46,24 +46,6 @@ export const RETRIEVE_METHOD = {keywordSearch: 'keyword_search' as RETRIEVE_METHOD,} as const-/**- * App modes- */-export type AppModeEnum =- | 'completion'- | 'workflow'- | 'chat'- | 'advanced-chat'- | 'agent-chat'- | 'agent'-export const AppModeEnum = {- COMPLETION: 'completion' as AppModeEnum,- WORKFLOW: 'workflow' as AppModeEnum,- CHAT: 'chat' as AppModeEnum,- ADVANCED_CHAT: 'advanced-chat' as AppModeEnum,- AGENT_CHAT: 'agent-chat' as AppModeEnum,- AGENT: 'agent' as AppModeEnum,-} as const/*** Variable type*/diff --git a/web/types/common.ts b/web/types/common.tsdeleted file mode 100644index f2097b02cdd..00000000000--- a/web/types/common.ts+++ /dev/null@@ -1,7 +0,0 @@-export const FlowType = {- appFlow: 'appFlow',- ragPipeline: 'ragPipeline',- snippet: 'snippet',-} as const--export type FlowType = (typeof FlowType)[keyof typeof FlowType]diff --git a/web/types/workflow.ts b/web/types/workflow.tsindex b33f89ab3e9..ec955f3528a 100644--- a/web/types/workflow.ts+++ b/web/types/workflow.ts@@ -1,4 +1,8 @@-import type { AppMode } from '@dify/contracts/api/console/apps/types.gen'+import type {+ AppMode,+ WorkflowDraftVariableResponse,+ WorkflowDraftVariableWithoutValueResponse,+} from '@dify/contracts/api/console/apps/types.gen'import type { RefObject } from 'react'import type { Viewport } from 'reactflow'import type { ErrorHandleTypeEnum } from '@/app/components/workflow/nodes/_base/components/error-handle/types'@@ -11,9 +15,7 @@ import type {EnvironmentVariable,InputVar,Node,- ValueSelector,Variable,- VarType,WorkflowRunningStatus,} from '@/app/components/workflow/types'import type { RAGPipelineVariables } from '@/models/pipeline'@@ -483,23 +485,12 @@ export const VarInInspectType = {} as constexport type VarInInspectType = (typeof VarInInspectType)[keyof typeof VarInInspectType]-type FullContent = {- size_bytes: number- download_url: string-}--export type VarInInspect = {- id: string- type: VarInInspectType- name: string- description: string- selector: ValueSelector // can get node id from selector[0]- value_type: VarType- value: any- edited: boolean- visible: boolean- is_truncated: boolean- full_content: FullContent+export type VarInInspect = WorkflowDraftVariableWithoutValueResponse & {+ value?: WorkflowDraftVariableResponse['value']+ full_content?: Pick<+ NonNullable<WorkflowDraftVariableResponse['full_content']>,+ 'size_bytes' | 'download_url'+ > | nullschemaType?: string}diff --git a/web/utils/__tests__/create-app-tracking.spec.ts b/web/utils/__tests__/create-app-tracking.spec.tsindex bf0d22d057b..ce441e7ed5f 100644--- a/web/utils/__tests__/create-app-tracking.spec.ts+++ b/web/utils/__tests__/create-app-tracking.spec.ts@@ -2,7 +2,6 @@ import Cookies from 'js-cookie'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import * as amplitude from '@/app/components/base/amplitude/utils'import { AgentScope } from '@/features/agent-v2/analytics'-import { AppModeEnum } from '@/types/app'import {buildCreateAppEventPayload,extractExternalCreateAppAttribution,@@ -96,7 +95,7 @@ describe('create-app-tracking', () => {buildCreateAppEventPayload({source: 'studio_blank',- appMode: AppModeEnum.ADVANCED_CHAT,+ appMode: 'advanced-chat' as const,},null,new Date(2026, 3, 13, 14, 5, 9),@@ -113,7 +112,7 @@ describe('create-app-tracking', () => {buildCreateAppEventPayload({source: 'studio_blank',- appMode: AppModeEnum.AGENT_CHAT,+ appMode: 'agent-chat' as const,},null,new Date(2026, 3, 13, 9, 8, 7),@@ -166,7 +165,7 @@ describe('create-app-tracking', () => {buildCreateAppEventPayload({source: 'studio_blank',- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,},null,new Date(2026, 3, 13, 8, 0, 1),@@ -181,7 +180,7 @@ describe('create-app-tracking', () => {buildCreateAppEventPayload({source: 'studio_blank',- appMode: AppModeEnum.COMPLETION,+ appMode: 'completion' as const,},null,new Date(2026, 3, 13, 8, 0, 2),@@ -198,7 +197,7 @@ describe('create-app-tracking', () => {buildCreateAppEventPayload({source: 'studio_blank',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,},null,new Date(2026, 3, 13, 7, 6, 5),@@ -215,7 +214,7 @@ describe('create-app-tracking', () => {buildCreateAppEventPayload({source: 'studio_template_list',- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,templateId: 'template-1',},null,@@ -234,7 +233,7 @@ describe('create-app-tracking', () => {buildCreateAppEventPayload({source: 'studio_template_list',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,templateId: 'template-1',},{@@ -258,7 +257,7 @@ describe('create-app-tracking', () => {buildCreateAppEventPayload({source: 'external',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,},null,new Date(2026, 3, 13, 7, 6, 5),@@ -277,7 +276,7 @@ describe('create-app-tracking', () => {} as ReturnType<typeof amplitude.flushEvents>)await expect(- trackCreateApp({ source: 'studio_blank', appMode: AppModeEnum.ADVANCED_CHAT }),+ trackCreateApp({ source: 'studio_blank', appMode: 'advanced-chat' as const }),).resolves.toBeUndefined()expect(amplitude.trackEvent).toHaveBeenCalledWith('create_app', {@@ -295,7 +294,7 @@ describe('create-app-tracking', () => {trackCreateApp({source: 'studio_template_list',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,templateId: 'template-1',})@@ -310,7 +309,7 @@ describe('create-app-tracking', () => {trackCreateApp({source: 'studio_template_list',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,templateId: 'template-1',})@@ -357,7 +356,7 @@ describe('create-app-tracking', () => {trackCreateApp({source: 'explore_template_preview',- appMode: AppModeEnum.CHAT,+ appMode: 'chat' as const,templateId: 'template-2',})@@ -380,7 +379,7 @@ describe('create-app-tracking', () => {value: undefined,})- trackCreateApp({ source: 'studio_blank', appMode: AppModeEnum.AGENT_CHAT })+ trackCreateApp({ source: 'studio_blank', appMode: 'agent-chat' as const })expect(amplitude.trackEvent).toHaveBeenCalledWith('create_app', {source: 'studio_blank',@@ -404,7 +403,7 @@ describe('create-app-tracking', () => {}),)- trackCreateApp({ source: 'studio_blank', appMode: AppModeEnum.CHAT })+ trackCreateApp({ source: 'studio_blank', appMode: 'chat' as const })expect(amplitude.trackEvent).toHaveBeenCalledWith('create_app', {source: 'external',@@ -419,7 +418,7 @@ describe('create-app-tracking', () => {it('should not track external source without remembered attribution', () => {trackCreateApp({source: 'external',- appMode: AppModeEnum.WORKFLOW,+ appMode: 'workflow' as const,templateId: 'template-1',})diff --git a/web/utils/app-redirection.spec.ts b/web/utils/app-redirection.spec.tsindex a53955d4fa6..b370e45f61e 100644--- a/web/utils/app-redirection.spec.ts+++ b/web/utils/app-redirection.spec.ts@@ -2,7 +2,7 @@* Test suite for app redirection utility functions* Tests navigation path generation based on user permissions and app modes*/-import { AppModeEnum } from '@/types/app'+import { AppACLPermission } from '@/utils/permission'import { getRedirection, getRedirectionPath } from './app-redirection'@@ -17,7 +17,7 @@ describe('app-redirection', () => {it('returns access point path when it is the only accessible app page', () => {const app = {id: 'app-123',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.AccessPointView],}const result = getRedirectionPath(app)@@ -25,7 +25,7 @@ describe('app-redirection', () => {})it('returns the app list when no app page is accessible', () => {- const app = { id: 'app-123', mode: AppModeEnum.CHAT, permission_keys: [] }+ const app = { id: 'app-123', mode: 'chat' as const, permission_keys: [] }expect(getRedirectionPath(app)).toBe('/apps')})@@ -33,7 +33,7 @@ describe('app-redirection', () => {it('does not redirect Access Point managers to a page they cannot view', () => {const app = {id: 'app-123',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.AccessPointManage],}@@ -43,7 +43,7 @@ describe('app-redirection', () => {it('returns workflow path for workflow mode when app ACL can access layout', () => {const app = {id: 'app-123',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.ViewLayout],}const result = getRedirectionPath(app)@@ -53,7 +53,7 @@ describe('app-redirection', () => {it('returns workflow path for advanced-chat mode when app ACL can access layout', () => {const app = {id: 'app-123',- mode: AppModeEnum.ADVANCED_CHAT,+ mode: 'advanced-chat' as const,permission_keys: [AppACLPermission.TestAndRun],}const result = getRedirectionPath(app)@@ -63,7 +63,7 @@ describe('app-redirection', () => {it('returns configuration path for chat mode when app ACL can access layout', () => {const app = {id: 'app-123',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.Edit],}const result = getRedirectionPath(app)@@ -73,7 +73,7 @@ describe('app-redirection', () => {it('returns configuration path for completion mode when app ACL can access layout', () => {const app = {id: 'app-123',- mode: AppModeEnum.COMPLETION,+ mode: 'completion' as const,permission_keys: [AppACLPermission.ViewLayout],}const result = getRedirectionPath(app)@@ -83,7 +83,7 @@ describe('app-redirection', () => {it('returns configuration path for agent-chat mode when app ACL can access layout', () => {const app = {id: 'app-456',- mode: AppModeEnum.AGENT_CHAT,+ mode: 'agent-chat' as const,permission_keys: [AppACLPermission.ViewLayout],}const result = getRedirectionPath(app)@@ -93,7 +93,7 @@ describe('app-redirection', () => {it('returns the Agent configure path when the backing Agent ID is available', () => {const app = {id: 'app-1',- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,permission_keys: [AppACLPermission.ViewLayout],bound_agent_id: 'agent-1',}@@ -104,7 +104,7 @@ describe('app-redirection', () => {it('falls back to the Agent roster when the backing Agent ID is unavailable', () => {const app = {id: 'app-1',- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,permission_keys: [AppACLPermission.ViewLayout],}@@ -114,12 +114,12 @@ describe('app-redirection', () => {it('handles different app IDs', () => {const app1 = {id: 'abc-123',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.AccessPointView],}const app2 = {id: 'xyz-789',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.ViewLayout],}@@ -128,7 +128,7 @@ describe('app-redirection', () => {})it('returns layout path when the app maintainer has app.create_and_management permission without app ACL keys', () => {- const app = { id: 'app-123', mode: AppModeEnum.CHAT, permission_keys: [] }+ const app = { id: 'app-123', mode: 'chat' as const, permission_keys: [] }expect(getRedirectionPath(app, {@@ -142,7 +142,7 @@ describe('app-redirection', () => {it('returns access config path when app ACL can only configure access', () => {const app = {id: 'app-123',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.AccessConfig],}@@ -152,7 +152,7 @@ describe('app-redirection', () => {it('returns access point path when RBAC is disabled and Access Point remains accessible', () => {const app = {id: 'app-123',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.AccessConfig, AppACLPermission.AccessPointView],}@@ -162,7 +162,7 @@ describe('app-redirection', () => {it('returns overview path when app ACL can only monitor the app', () => {const app = {id: 'app-123',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.Monitor],}@@ -172,7 +172,7 @@ describe('app-redirection', () => {it('returns logs path when app ACL can only access logs and annotations', () => {const app = {id: 'app-123',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.LogAndAnnotation],}@@ -182,7 +182,7 @@ describe('app-redirection', () => {it('returns deploy path when a workflow app ACL can only deploy', () => {const app = {id: 'app-123',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.Deploy],}@@ -200,7 +200,7 @@ describe('app-redirection', () => {it('calls redirection function with access point path when it is accessible', () => {const app = {id: 'app-123',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.AccessPointView],}const mockRedirect = vi.fn()@@ -214,7 +214,7 @@ describe('app-redirection', () => {it('calls redirection function with workflow path when app ACL can access layout', () => {const app = {id: 'app-123',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.ViewLayout],}const mockRedirect = vi.fn()@@ -228,7 +228,7 @@ describe('app-redirection', () => {it('calls redirection function with configuration path for chat mode with layout access', () => {const app = {id: 'app-123',- mode: AppModeEnum.CHAT,+ mode: 'chat' as const,permission_keys: [AppACLPermission.ViewLayout],}const mockRedirect = vi.fn()@@ -242,7 +242,7 @@ describe('app-redirection', () => {it('works with different redirection functions', () => {const app = {id: 'app-123',- mode: AppModeEnum.WORKFLOW,+ mode: 'workflow' as const,permission_keys: [AppACLPermission.ViewLayout],}const paths: string[] = []diff --git a/web/utils/app-redirection.ts b/web/utils/app-redirection.tsindex aaabc4f0dd9..b4f514b3431 100644--- a/web/utils/app-redirection.ts+++ b/web/utils/app-redirection.ts@@ -1,6 +1,5 @@import type { AppPartial } from '@dify/contracts/api/console/apps/types.gen'import type { ResourceMaintainerPermissionOptions } from '@/utils/permission'-import { AppModeEnum } from '@/types/app'import { getAppACLCapabilities } from '@/utils/permission'export type AppRedirectionTarget = {@@ -14,14 +13,13 @@ export const getRedirectionPath = (app: AppRedirectionTarget,maintainerPermissionOptions?: ResourceMaintainerPermissionOptions,) => {- if (app.mode === AppModeEnum.AGENT)+ if (app.mode === 'agent')return app.bound_agent_id ? `/agents/${app.bound_agent_id}/configure` : '/agents'const appACLCapabilities = getAppACLCapabilities(app.permission_keys, maintainerPermissionOptions)if (appACLCapabilities.canAccessLayout) {- if (app.mode === AppModeEnum.WORKFLOW || app.mode === AppModeEnum.ADVANCED_CHAT)- return `/app/${app.id}/workflow`+ if (app.mode === 'workflow' || app.mode === 'advanced-chat') return `/app/${app.id}/workflow`else return `/app/${app.id}/configuration`}@@ -31,8 +29,7 @@ export const getRedirectionPath = (if (appACLCapabilities.canAccessConfig) return `/app/${app.id}/access-config`- if (app.mode === AppModeEnum.WORKFLOW && appACLCapabilities.canDeploy)- return `/app/${app.id}/deploy`+ if (app.mode === 'workflow' && appACLCapabilities.canDeploy) return `/app/${app.id}/deploy`if (appACLCapabilities.canViewAccessPoint) return `/app/${app.id}/access-point`diff --git a/web/utils/create-app-tracking.ts b/web/utils/create-app-tracking.tsindex 9ca3c144a3b..c4b51d03700 100644--- a/web/utils/create-app-tracking.ts+++ b/web/utils/create-app-tracking.ts@@ -1,7 +1,6 @@import type { AgentScope } from '@/features/agent-v2/analytics'import Cookies from 'js-cookie'import { flushEvents, trackEvent } from '@/app/components/base/amplitude/utils'-import { AppModeEnum } from '@/types/app'const CREATE_APP_EXTERNAL_ATTRIBUTION_STORAGE_KEY = 'create_app_external_attribution'@@ -78,11 +77,11 @@ const formatCreateAppTime = (date: Date) => {}const mapOriginalCreateAppMode = (appMode: string): OriginalCreateAppMode => {- if (appMode === AppModeEnum.WORKFLOW) return 'workflow'+ if (appMode === 'workflow') return 'workflow'if (appMode === 'agent-v2') return 'agent-v2'- if (appMode === AppModeEnum.AGENT_CHAT || appMode === 'agent') return 'agent'+ if (appMode === 'agent-chat' || appMode === 'agent') return 'agent'return 'chatflow'}diff --git a/web/utils/imported-app-redirection.spec.ts b/web/utils/imported-app-redirection.spec.tsindex 9f9ed5d166f..14d61694b02 100644--- a/web/utils/imported-app-redirection.spec.ts+++ b/web/utils/imported-app-redirection.spec.ts@@ -1,4 +1,3 @@-import { AppModeEnum } from '@/types/app'import { resolveImportedAppRedirectionTarget } from './imported-app-redirection'const mockFetchAppDetail = vi.hoisted(() => vi.fn())@@ -24,12 +23,12 @@ describe('resolveImportedAppRedirectionTarget', () => {await expect(resolveImportedAppRedirectionTarget({id: 'app-1',- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,permission_keys: ['app.acl.view_layout'],}),).resolves.toEqual({id: 'app-1',- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,permission_keys: ['app.acl.view_layout'],bound_agent_id: 'agent-1',})@@ -42,7 +41,7 @@ describe('resolveImportedAppRedirectionTarget', () => {mockFetchAppDetail.mockRejectedValue(new Error('Failed to fetch App detail'))const target = {id: 'app-1',- mode: AppModeEnum.AGENT,+ mode: 'agent' as const,}await expect(resolveImportedAppRedirectionTarget(target)).resolves.toEqual(target)diff --git a/web/utils/imported-app-redirection.ts b/web/utils/imported-app-redirection.tsindex 68384998602..7c03f9077e5 100644--- a/web/utils/imported-app-redirection.ts+++ b/web/utils/imported-app-redirection.ts@@ -1,11 +1,10 @@import type { AppRedirectionTarget } from '@/utils/app-redirection'import { consoleClient } from '@/service/console'-import { AppModeEnum } from '@/types/app'export const resolveImportedAppRedirectionTarget = async (app: AppRedirectionTarget,): Promise<AppRedirectionTarget> => {- if (app.mode !== AppModeEnum.AGENT) return app+ if (app.mode !== 'agent') return apptry {const importedApp = await consoleClient.apps.byAppId.get({