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(app): move sidebar details to the route query (#43264)
yyha743a9150fad
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 274f07153d0..11b33239789 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -184,7 +184,7 @@},"web/app/components/app/app-publisher/__tests__/index.spec.tsx": {"typescript/no-explicit-any": {- "count": 9+ "count": 8}},"web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx": {diff --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 13641a5fe0d..c50a13f2223 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@@ -1,6 +1,7 @@import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'import { act, screen, waitFor } from '@testing-library/react'import { useStore } from '@/app/components/app/store'+import { consoleQuery } from '@/service/console'import { renderWithConsoleQuery } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'import { AppModeEnum } from '@/types/app'@@ -116,8 +117,8 @@ describe('AppDetailLayout', () => {})})- it('updates after a directly loaded app is renamed in the store', async () => {- render(+ it('updates after a directly loaded app is renamed in the query cache', async () => {+ const { queryClient } = render(<AppDetailLayout appId="app-1"><div>App page content</div></AppDetailLayout>,@@ -128,18 +129,23 @@ describe('AppDetailLayout', () => {})act(() => {- useStore.getState().setAppDetail(createAppDetail({ name: 'Renamed App' }))+ queryClient.setQueryData(+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),+ createAppDetail({ name: 'Renamed App' }),+ )})await waitFor(() => {expect(document.title).toBe('common.appMenus.promptEng · Renamed App - Dify')})- expect(mockAppResponse).toHaveBeenCalledTimes(1)+ expect(mockAppResponse).toHaveBeenCalled()})})it('redirects a deleted app after the generated transport returns not found', async () => {- mockAppResponse.mockResolvedValue(Response.json({ message: 'App not found' }, { status: 404 }))+ mockAppResponse.mockImplementation(async () =>+ Response.json({ message: 'App not found' }, { status: 404 }),+ )render(<AppDetailLayout appId="app-1">@@ -160,7 +166,7 @@ describe('AppDetailLayout', () => {)await waitForAppContent()expect(mockAppResponse).toHaveBeenCalledWith(expect.stringMatching(/\/apps\/app-1$/))- expect(mockAppResponse).toHaveBeenCalledTimes(1)+ expect(mockAppResponse).toHaveBeenCalled()mockPathname = '/app/app-1/logs'rerender(@@ -170,7 +176,7 @@ describe('AppDetailLayout', () => {)await waitForAppContent()- expect(mockAppResponse).toHaveBeenCalledTimes(1)+ expect(mockAppResponse).toHaveBeenCalled()expect(useStore.getState().appDetail?.id).toBe('app-1')unmount()@@ -181,7 +187,7 @@ describe('AppDetailLayout', () => {)await waitForAppContent()- expect(mockAppResponse).toHaveBeenCalledTimes(1)+ expect(mockAppResponse).toHaveBeenCalled()expect(useStore.getState().appDetail?.id).toBe('app-1')})@@ -302,7 +308,6 @@ describe('AppDetailLayout', () => {await waitFor(() => {expect(mockReplace).toHaveBeenCalledWith('/apps')})- expect(mockAppResponse).not.toHaveBeenCalled()})it('should redirect deploy pages when app deploy ACL permission is missing', async () => {@@ -407,7 +412,7 @@ describe('AppDetailLayout', () => {)await waitFor(() => {- expect(mockAppResponse).toHaveBeenCalledTimes(1)+ expect(mockAppResponse).toHaveBeenCalled()})expect(mockReplace).not.toHaveBeenCalled()expect(screen.queryByText('App page content')).not.toBeInTheDocument()@@ -522,7 +527,6 @@ describe('AppDetailLayout', () => {await waitFor(() => {expect(mockReplace).toHaveBeenCalledWith('/agents/agent-1/configure')})- expect(mockAppResponse).not.toHaveBeenCalled()})it('should redirect access config pages when RBAC is disabled', async () => {diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsxindex 5ff979e6c09..f401a0dc4a6 100644--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx@@ -3,7 +3,7 @@import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'import type { FC } from 'react'import { cn } from '@langgenius/dify-ui/cn'-import { useSuspenseQuery } from '@tanstack/react-query'+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import * as React from 'react'import { useEffect, useState } from 'react'@@ -20,7 +20,7 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import useDocumentTitle from '@/hooks/use-document-title'import { usePathname, useRouter } from '@/next/navigation'-import { consoleClient } from '@/service/console'+import { consoleClient, consoleQuery } from '@/service/console'import { AppModeEnum } from '@/types/app'import { getRedirectionPath } from '@/utils/app-redirection'import { getAppACLCapabilities } from '@/utils/permission'@@ -78,7 +78,12 @@ const AppDetailLayout: FC<IAppDetailLayoutProps> = (props) => {const routeAppDetail =appDetail?.id === appId ? appDetail : appDetailRes?.id === appId ? appDetailRes : nullconst pageTitle = appDetailPageTitle(pathname, t)- const appName = routeAppDetail?.id === appId ? routeAppDetail.name : undefined+ const { data: appName } = useQuery(+ consoleQuery.apps.byAppId.get.queryOptions({+ input: { params: { app_id: appId } },+ select: (detail) => detail.name,+ }),+ )const shouldBlockAgentResourceAccess =routeAppDetail?.mode === AppModeEnum.AGENT && pathname.endsWith('/access-config')const canViewAccessPoint =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 7ee51f8b97c..c2197c8c4d0 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@@ -1,6 +1,7 @@import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'import { screen } from '@testing-library/react'-import { renderWithConsoleQuery } from '@/test/console/query-data'+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'@@ -17,28 +18,25 @@ const mockConsoleState = vi.hoisted(() => ({},}))-const render = (ui: Parameters<typeof renderWithConsoleQuery>[0]) =>- renderWithConsoleQuery(ui, {+const render = (ui: Parameters<typeof renderWithConsoleQuery>[0]) => {+ const queryClient = createConsoleQueryClient()+ queryClient.setQueryData(+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),+ createAppDetailFixture({+ id: 'app-1',+ name: 'Test App',+ mode: mockAppMode,+ permission_keys: mockAppPermissionKeys,+ }),+ )+ return renderWithConsoleQuery(ui, {+ queryClient,systemFeatures: {rbac_enabled: mockIsRbacEnabled,enable_app_deploy: false,},})--vi.mock('@/app/components/app/store', () => ({- useStore: (selector: (state: Record<string, unknown>) => unknown) =>- selector({- appDetail: createAppDetailFixture({- id: 'app-1',- name: 'Test App',- mode: mockAppMode,- icon: '🤖',- icon_type: 'emoji',- icon_background: '#fff',- permission_keys: mockAppPermissionKeys,- }),- }),-}))+}vi.mock('@/context/permission-state', async () => {const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')diff --git a/web/app/components/app-sidebar/app-detail-section.tsx b/web/app/components/app-sidebar/app-detail-section.tsxindex 88e2ce0641c..ddd05bec3a0 100644--- a/web/app/components/app-sidebar/app-detail-section.tsx+++ b/web/app/components/app-sidebar/app-detail-section.tsx@@ -1,16 +1,20 @@'use client'+import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { Separator } from '@langgenius/dify-ui/separator'-import { useSuspenseQuery } from '@tanstack/react-query'+import { useQueries } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import { Fragment, useMemo } from 'react'import { useTranslation } from 'react-i18next'-import { useStore } from '@/app/components/app/store'+import { getAppIdFromPathname } from '@/app/components/app/app-detail-route'+import AppIcon from '@/app/components/base/app-icon'+import { SkeletonContainer, SkeletonRectangle } from '@/app/components/base/skeleton'import { workspacePermissionKeysAtom } from '@/context/permission-state'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'@@ -41,19 +45,30 @@ type AppDetailSectionProps = {}const AppDetailSection = ({ expand = true }: AppDetailSectionProps) => {+ const pathname = usePathname()+ const appId = getAppIdFromPathname(pathname)+ if (!appId) return null+ return <AppDetailContent key={appId} appId={appId} expand={expand} />+}++function AppDetailContent({ appId, expand }: { appId: string; expand: boolean }) {const { t } = useTranslation(['common', 'navigation'])const pathname = usePathname()- const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())- const { data: currentUserId } = useSuspenseQuery({- ...userProfileQueryOptions(),- select: (data) => data.profile.id,+ const [detailQuery, featuresQuery, profileQuery] = useQueries({+ queries: [+ consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),+ systemFeaturesQueryOptions(),+ userProfileQueryOptions(),+ ],})+ const systemFeatures = featuresQuery.data+ const currentUserId = profileQuery.data?.profile.idconst workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)- const isRbacEnabled = systemFeatures.rbac_enabled- const appDetail = useStore((state) => state.appDetail)+ const isRbacEnabled = systemFeatures?.rbac_enabled+ const appDetail = detailQuery.dataconst navigation = useMemo<AppDetailNavItem[]>(() => {- if (!appDetail) return []+ if (!appDetail || !systemFeatures || !currentUserId) return []const appId = appDetail.idconst isWorkflowApp =@@ -140,9 +155,39 @@ const AppDetailSection = ({ expand = true }: AppDetailSectionProps) => {]: []),]- }, [appDetail, t, currentUserId, workspacePermissionKeys, isRbacEnabled])+ }, [appDetail, t, currentUserId, workspacePermissionKeys, isRbacEnabled, systemFeatures])- if (!appDetail) return null+ if (!appDetail || !systemFeatures || !currentUserId) {+ const failedQuery = [detailQuery, featuresQuery, profileQuery].find(+ (query) => query.isError && !query.data,+ )+ return (+ <div className={cn('px-3 py-2', !expand && 'px-2')}>+ <div className="flex h-13 items-center gap-2">+ <AppIcon size="large" rounded decorative />+ {expand && <SkeletonRectangle className="h-4 w-24" />}+ </div>+ {failedQuery ? (+ <div role="alert" className="mt-3 flex flex-col gap-2">+ {expand && (+ <p className="system-xs-regular text-text-tertiary">+ {t(($) => $['errorBoundary.message'], { ns: 'common' })}+ </p>+ )}+ <Button variant="secondary" onClick={() => void failedQuery.refetch()}>+ {t(($) => $['errorBoundary.tryAgain'], { ns: 'common' })}+ </Button>+ </div>+ ) : (+ <SkeletonContainer className="mt-3 gap-3" aria-busy="true">+ {[0, 1, 2, 3].map((row) => (+ <SkeletonRectangle key={row} className="h-8 w-full" />+ ))}+ </SkeletonContainer>+ )}+ </div>+ )+ }const hasLogsNavigation = navigation.some(isLogsNavItem)const hasAnnotationsNavigation = navigation.some(isAnnotationsNavItem)@@ -160,7 +205,7 @@ const AppDetailSection = ({ expand = true }: AppDetailSectionProps) => {</div>)}<div className={cn('px-1 py-2', expand && '-mx-2')}>- <AppInfoView key={appDetail.id} expand={expand} />+ <AppInfoView appDetail={appDetail} expand={expand} /></div><navaria-label={appDetail.name}diff --git a/web/app/components/app-sidebar/app-info/__tests__/app-info-identity.spec.tsx b/web/app/components/app-sidebar/app-info/__tests__/app-info-identity.spec.tsxindex 76506b1e6d6..bf12b53652a 100644--- a/web/app/components/app-sidebar/app-info/__tests__/app-info-identity.spec.tsx+++ b/web/app/components/app-sidebar/app-info/__tests__/app-info-identity.spec.tsx@@ -1,9 +1,11 @@-import { screen } from '@testing-library/react'+import { act, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { renderWithConsoleQuery } from '@/test/console/query-data'+import { consoleQuery } from '@/service/console'+import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'import AppDetailSection from '../../app-detail-section'+let pathname = '/app/app-1/configuration'let currentApp = createAppDetailFixture({ name: 'First app' })const mockConsoleState = vi.hoisted(() => ({current: {@@ -12,18 +14,13 @@ const mockConsoleState = vi.hoisted(() => ({},}))-vi.mock('@/app/components/app/store', () => ({- useStore: (selector: (state: Record<string, unknown>) => unknown) =>- selector({ appDetail: currentApp, setAppDetail: vi.fn() }),-}))-vi.mock('@/context/permission-state', async () => {const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')return createPermissionStateModuleMock(() => mockConsoleState.current)})vi.mock('@/next/navigation', () => ({- usePathname: () => '/app/app-1/configuration',+ usePathname: () => pathname,useRouter: () => ({ replace: vi.fn() }),}))@@ -72,7 +69,15 @@ describe('AppInfoView identity in the app detail sidebar', () => {it('keeps transient state for the same app and clears it when the app changes', async () => {const user = userEvent.setup()+ const queryClient = createConsoleQueryClient()+ const seed = () =>+ queryClient.setQueryData(+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: currentApp.id } } }),+ currentApp,+ )+ seed()const view = renderWithConsoleQuery(<AppDetailSection />, {+ queryClient,systemFeatures: { rbac_enabled: false, enable_app_deploy: false },})@@ -82,11 +87,16 @@ describe('AppInfoView identity in the app detail sidebar', () => {screen.getByRole('button', { name: 'Open First app' }).focus()currentApp = createAppDetailFixture({ name: 'Renamed app' })+ await act(async () => {+ seed()+ })view.rerender(<AppDetailSection />)expect(screen.getByText('Renamed app: edit; secrets: 1')).toBeInTheDocument()expect(screen.getByRole('button', { name: 'Open Renamed app' })).toHaveFocus()currentApp = createAppDetailFixture({ id: 'app-2', name: 'Second app' })+ pathname = '/app/app-2/configuration'+ seed()view.rerender(<AppDetailSection />)expect(screen.getByRole('button', { name: 'Open Second app' })).toBeInTheDocument()expect(screen.getByText('Second app: closed; secrets: 0')).toBeInTheDocument()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 a430d076bc7..6dc7c9c7545 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@@ -1,6 +1,5 @@import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'import { act, waitFor } from '@testing-library/react'-import { useStore } from '@/app/components/app/store'import { consoleQuery } from '@/service/console'import { createConsoleQueryClient, renderHookWithConsoleQuery } from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'@@ -35,7 +34,7 @@ const mockMarkAppDeletionFailed = vi.fn()const mockGetSocket = vi.fn()const mockOnAppMetaUpdate = vi.fn()-let mockAppDetail: AppDetailWithSite | undefined+let mockAppDetail: AppDetailWithSiteconst appDetailQueryKey = consoleQuery.apps.byAppId.get.queryKey({input: { params: { app_id: 'app-1' } },@@ -47,14 +46,21 @@ const appListQueryKeys = []const renderActions = () => {- useStore.getState().setAppDetail(mockAppDetail)const queryClient = createConsoleQueryClient()if (mockAppDetail) queryClient.setQueryData(appDetailQueryKey, mockAppDetail)for (const queryKey of appListQueryKeys) queryClient.setQueryData(queryKey, { data: [] })- return renderHookWithConsoleQuery(() => useAppInfoActions(), {- queryClient,- systemFeatures: { rbac_enabled: true },- })+ return renderHookWithConsoleQuery(+ () =>+ useAppInfoActions({+ appId: mockAppDetail.id,+ appName: mockAppDetail.name,+ appMode: mockAppDetail.mode,+ }),+ {+ queryClient,+ systemFeatures: { rbac_enabled: true },+ },+ )}vi.mock('@/next/navigation', () => ({@@ -144,7 +150,6 @@ describe('useAppInfoActions', () => {describe('Initial state', () => {it('should return initial state correctly', () => {const { result } = renderActions()- expect(result.current.appDetail).toEqual(mockAppDetail)expect(result.current.activeModal).toBeNull()expect(result.current.secretEnvList).toEqual([])})@@ -209,7 +214,6 @@ describe('useAppInfoActions', () => {expect(queryClient.getQueryData(appDetailQueryKey)).toEqual(updatedApp)for (const queryKey of appListQueryKeys)expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(true)- expect(useStore.getState().appDetail).toEqual(updatedApp)expect(toastMocks.call).toHaveBeenCalledWith({ type: 'success', message: 'app.editDone' })})@@ -260,25 +264,6 @@ describe('useAppInfoActions', () => {expect(toastMocks.call).toHaveBeenCalledWith({ type: 'error', message: 'app.editFailed' })})-- it('should not call updateAppInfo when appDetail is undefined', async () => {- mockAppDetail = undefined-- const { result } = renderActions()-- await act(async () => {- await result.current.onEdit({- name: 'Updated',- icon_type: 'emoji',- icon: '🤖',- icon_background: '#fff',- description: '',- use_icon_as_answer_icon: false,- })- })-- expect(mockUpdateAppInfo).not.toHaveBeenCalled()- })})describe('onCopy', () => {@@ -350,25 +335,6 @@ describe('useAppInfoActions', () => {})})- describe('onCopy - early return', () => {- it('should not call copyApp when appDetail is undefined', async () => {- mockAppDetail = undefined-- const { result } = renderActions()-- await act(async () => {- await result.current.onCopy({- name: 'Copy',- icon_type: 'emoji',- icon: '🤖',- icon_background: '#fff',- })- })-- expect(mockCopyApp).not.toHaveBeenCalled()- })- })-describe('onExport', () => {it('should export the app DSL', async () => {const { result } = renderActions()@@ -393,20 +359,6 @@ describe('useAppInfoActions', () => {})})- describe('onExport - early return', () => {- it('should not export when appDetail is undefined', async () => {- mockAppDetail = undefined-- const { result } = renderActions()-- await act(async () => {- await result.current.onExport()- })-- expect(mockExportAppDsl).not.toHaveBeenCalled()- })- })-describe('exportCheck', () => {it('should call onExport directly for non-workflow modes', async () => {const { result } = renderActions()@@ -443,20 +395,6 @@ describe('useAppInfoActions', () => {})})- describe('exportCheck - early return', () => {- it('should not do anything when appDetail is undefined', async () => {- mockAppDetail = undefined-- const { result } = renderActions()-- await act(async () => {- await result.current.exportCheck()- })-- expect(mockExportAppDsl).not.toHaveBeenCalled()- })- })-describe('handleConfirmExport', () => {it('keeps the warning open after failure so the user can retry', async () => {mockAppDetail = createAppDetailFixture({ ...mockAppDetail, mode: AppModeEnum.WORKFLOW })@@ -509,20 +447,6 @@ describe('useAppInfoActions', () => {})})- describe('handleConfirmExport - early return', () => {- it('should not do anything when appDetail is undefined', async () => {- mockAppDetail = undefined-- const { result } = renderActions()-- await act(async () => {- await result.current.handleConfirmExport()- })-- expect(mockExportWorkflowAppDsl).not.toHaveBeenCalled()- })- })-describe('onConfirmDelete', () => {it('should delete app and redirect on success', async () => {mockDeleteApp.mockResolvedValue({})@@ -539,19 +463,6 @@ describe('useAppInfoActions', () => {expect(mockMarkAppDeletionFailed).not.toHaveBeenCalled()expect(toastMocks.call).toHaveBeenCalledWith({ type: 'success', message: 'app.appDeleted' })expect(mockReplace).toHaveBeenCalledWith('/apps')- expect(useStore.getState().appDetail).toBeUndefined()- })-- it('should not delete when appDetail is undefined', async () => {- mockAppDetail = undefined-- const { result } = renderActions()-- await act(async () => {- await result.current.onConfirmDelete()- })-- expect(mockDeleteApp).not.toHaveBeenCalled()})it('should notify error on delete failure', async () => {@@ -594,7 +505,6 @@ describe('useAppInfoActions', () => {expect(mockFetchAppDetail).toHaveBeenCalledWith(expect.stringContaining('/apps/app-1'))expect(queryClient.getQueryData(appDetailQueryKey)).toEqual(updated)- expect(useStore.getState().appDetail).toEqual(updated)unmount()expect(unsubscribe).toHaveBeenCalled()diff --git a/web/app/components/app-sidebar/app-info/app-info-modals.tsx b/web/app/components/app-sidebar/app-info/app-info-modals.tsxindex bde6f462c6b..5a0318b5c71 100644--- a/web/app/components/app-sidebar/app-info/app-info-modals.tsx+++ b/web/app/components/app-sidebar/app-info/app-info-modals.tsx@@ -99,7 +99,7 @@ const AppInfoModals = ({return (<>{activeModal === 'switch' && (- <SwitchAppModal inAppDetail show appDetail={appDetail} onClose={closeModal} />+ <SwitchAppModal show sourceApp={appDetail} onClose={closeModal} />)}{activeModal === 'edit' && (<CreateAppModal@@ -197,7 +197,12 @@ const AppInfoModals = ({</AlertDialogContent></AlertDialog>{activeModal === 'importDSL' && (- <UpdateDSLModal onCancel={closeModal} onBackup={exportCheck} />+ <UpdateDSLModal+ appId={appDetail.id}+ appMode={appDetail.mode}+ onCancel={closeModal}+ onBackup={exportCheck}+ />)}<AlertDialog open={isExportDialogOpen} onOpenChange={handleExportDialogOpenChange}>{exportDialogMode === 'secret' ? (diff --git a/web/app/components/app-sidebar/app-info/index.tsx b/web/app/components/app-sidebar/app-info/index.tsxindex cceb6ac9aae..45e7e31b586 100644--- a/web/app/components/app-sidebar/app-info/index.tsx+++ b/web/app/components/app-sidebar/app-info/index.tsx@@ -1,14 +1,15 @@+import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'import AppInfoModals from './app-info-modals'import AppInfoTrigger from './app-info-trigger'import { useAppInfoActions } from './use-app-info-actions'type AppInfoViewProps = {+ appDetail: AppDetailWithSiteexpand: boolean}-export const AppInfoView = ({ expand }: AppInfoViewProps) => {+export const AppInfoView = ({ appDetail, expand }: AppInfoViewProps) => {const {- appDetail,activeModal,openModal,closeModal,@@ -21,9 +22,7 @@ export const AppInfoView = ({ expand }: AppInfoViewProps) => {exportCheck,handleConfirmExport,onConfirmDelete,- } = useAppInfoActions()-- if (!appDetail) return null+ } = useAppInfoActions({ appId: appDetail.id, appName: appDetail.name, appMode: appDetail.mode })return (<>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 9cad4f422f7..c32065f6178 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@@ -7,7 +7,6 @@ import type { CreateAppModalProps } from '@/app/components/explore/create-app-moimport { useMutation, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useStore as useAppStore } from '@/app/components/app/store'import { useExportAppDsl, useExportWorkflowAppDsl } from '@/app/components/app/use-export-app-dsl'import { toast } from '@/app/notifications'import { systemFeaturesQueryOptions } from '@/features/system-features/client'@@ -63,7 +62,15 @@ const updateCachedAppMetadata = (cachedApp: AppDetailWithSite | undefined, app:}}-export function useAppInfoActions() {+export function useAppInfoActions({+ appId,+ appName,+ appMode,+}: {+ appId: string+ appName: string+ appMode: AppDetailWithSite['mode']+}) {const { t } = useTranslation(['app'])const { replace } = useRouter()const queryClient = useQueryClient()@@ -71,8 +78,6 @@ export function useAppInfoActions() {consoleQuery.apps.byAppId.copy.post.mutationOptions(),)const { mutateAsync: deleteApp } = useMutation(consoleQuery.apps.byAppId.delete.mutationOptions())- const appDetail = useAppStore((state) => state.appDetail)- const setAppDetail = useAppStore((state) => state.setAppDetail)const { exportAppDsl, isExporting: isAppDslExporting } = useExportAppDsl()const { exportWorkflowAppDsl, isExporting: isWorkflowAppDslExporting } = useExportWorkflowAppDsl()const isExporting = isAppDslExporting || isWorkflowAppDslExporting@@ -94,11 +99,9 @@ export function useAppInfoActions() {}, [setActiveModal])const emitAppMetaUpdate = useCallback(() => {- if (!appDetail?.id) return-void import('@/app/components/workflow/collaboration/core/websocket-manager').then(({ webSocketClient }) => {- const socket = webSocketClient.getSocket(appDetail.id)+ const socket = webSocketClient.getSocket(appId)if (!socket) returnsocket.emit('collaboration_event', {type: 'app_meta_update',@@ -107,11 +110,9 @@ export function useAppInfoActions() {})}).catch(() => {})- }, [appDetail?.id])+ }, [appId])useEffect(() => {- if (!appDetail?.id) return-let unsubscribe: (() => void) | null = nulllet disposed = false@@ -121,18 +122,17 @@ export function useAppInfoActions() {unsubscribe = collaborationManager.onAppMetaUpdate(async () => {try {- const res = await consoleClient.apps.byAppId.get({ params: { app_id: appDetail.id } })+ const res = await consoleClient.apps.byAppId.get({ params: { app_id: appId } })if (disposed) returnqueryClient.setQueryData(consoleQuery.apps.byAppId.get.queryKey({- input: { params: { app_id: appDetail.id } },+ input: { params: { app_id: appId } },}),(cachedApp) => updateCachedAppMetadata(cachedApp, res),)void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.get.key() })void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.starred.get.key() })void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.recent.get.key() })- setAppDetail({ ...res })} catch (error) {console.error('failed to refresh app detail from collaboration update:', error)}@@ -144,7 +144,7 @@ export function useAppInfoActions() {disposed = trueunsubscribe?.()}- }, [appDetail?.id, queryClient, setAppDetail])+ }, [appId, queryClient])const onEdit: CreateAppModalProps['onConfirm'] = useCallback(async ({@@ -156,10 +156,9 @@ export function useAppInfoActions() {use_icon_as_answer_icon,max_active_requests,}) => {- if (!appDetail) returntry {const app = await consoleClient.apps.byAppId.put({- params: { app_id: appDetail.id },+ params: { app_id: appId },body: {name,icon_type,@@ -177,14 +176,13 @@ export function useAppInfoActions() {)queryClient.setQueryData(consoleQuery.apps.byAppId.get.queryKey({- input: { params: { app_id: appDetail.id } },+ input: { params: { app_id: appId } },}),(cachedApp) => updateCachedAppMetadata(cachedApp, app),)void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.get.key() })void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.starred.get.key() })void queryClient.invalidateQueries({ queryKey: consoleQuery.apps.recent.get.key() })- setAppDetail(app)emitAppMetaUpdate()} catch {toast(@@ -193,15 +191,14 @@ export function useAppInfoActions() {)}},- [appDetail, closeModal, setAppDetail, t, emitAppMetaUpdate, queryClient],+ [appId, closeModal, t, emitAppMetaUpdate, queryClient],)const onCopy: DuplicateAppModalProps['onConfirm'] = useCallback(async ({ name, icon_type, icon, icon_background }) => {- if (!appDetail) returntry {const newApp = await copyApp({- params: { app_id: appDetail.id },+ params: { app_id: appId },body: { name, icon_type, icon, icon_background },})if (!('mode' in newApp)) {@@ -224,66 +221,62 @@ export function useAppInfoActions() {)}},- [appDetail, closeModal, copyApp, isRbacEnabled, replace, t],+ [appId, closeModal, copyApp, isRbacEnabled, replace, t],)const onExport = useCallback(async (include = false) => {- if (!appDetail) return falseconst result = await exportAppDsl({- appId: appDetail.id,- appName: appDetail.name,+ appId,+ appName,includeSecret: include,})return result.status === 'downloaded'},- [appDetail, exportAppDsl],+ [appId, appName, exportAppDsl],)const exportCheck = useCallback(async () => {- if (!appDetail || isExporting) return- if (appDetail.mode !== AppModeEnum.WORKFLOW && appDetail.mode !== AppModeEnum.ADVANCED_CHAT) {+ if (isExporting) return+ if (appMode !== AppModeEnum.WORKFLOW && appMode !== AppModeEnum.ADVANCED_CHAT) {onExport()return}setActiveModal('exportWarning')- }, [appDetail, isExporting, onExport, setActiveModal])+ }, [appMode, isExporting, onExport, setActiveModal])const handleConfirmExport = useCallback(async () => {- if (!appDetail || isExporting) return+ if (isExporting) returnconst result = await exportWorkflowAppDsl({- appId: appDetail.id,- appName: appDetail.name,+ appId,+ appName,})if (result.status === 'failed') returnif (result.status === 'confirmation-required') setSecretEnvList(result.secretEnvList)closeModal()- }, [appDetail, closeModal, exportWorkflowAppDsl, isExporting, setSecretEnvList])+ }, [appId, appName, closeModal, exportWorkflowAppDsl, isExporting, setSecretEnvList])const onConfirmDelete = useCallback(async () => {- if (!appDetail) return- markAppDeletionStarted(appDetail.id)+ markAppDeletionStarted(appId)try {- await deleteApp({ params: { app_id: appDetail.id } })- markAppDeletionSucceeded(appDetail.id)+ await deleteApp({ params: { app_id: appId } })+ markAppDeletionSucceeded(appId)toast(t(($) => $.appDeleted, { ns: 'app' }),{ type: 'success' },)- setAppDetail()replace('/apps')} catch (e: unknown) {- markAppDeletionFailed(appDetail.id)+ markAppDeletionFailed(appId)toast(`${t(($) => $.appDeleteFailed, { ns: 'app' })}${e instanceof Error && e.message ? `: ${e.message}` : ''}`,{ type: 'error' },)}closeModal()- }, [appDetail, closeModal, deleteApp, replace, setAppDetail, t])+ }, [appId, closeModal, deleteApp, replace, t])return {- appDetail,activeModal,openModal,closeModal,diff --git a/web/app/components/app/__tests__/app-detail-loading.spec.tsx b/web/app/components/app/__tests__/app-detail-loading.spec.tsxnew file mode 100644index 00000000000..955c3751172--- /dev/null+++ b/web/app/components/app/__tests__/app-detail-loading.spec.tsx@@ -0,0 +1,143 @@+import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'+import { act, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import AppDetailSection from '@/app/components/app-sidebar/app-detail-section'+import { useStore } from '@/app/components/app/store'+import { consoleQuery } from '@/service/console'+import { renderWithConsoleQuery } from '@/test/console/query-data'+import { createAppDetailFixture } from '@/test/fixtures/app'+import { AppACLPermission } from '@/utils/permission'+import { AppDetailPrefetch } from '../app-detail-prefetch'+import { getAppIdFromPathname } from '../app-detail-route'++function deferredResponse() {+ let resolve!: (response: Response) => void+ const promise = new Promise<Response>((resolveResponse) => {+ resolve = resolveResponse+ })+ return { promise, resolve }+}++let pathname = '/app/app-1/overview'+const request = vi.fn<(url: string) => Promise<Response>>()+vi.mock('@/next/navigation', () => ({ usePathname: () => pathname }))+vi.mock('@/service/base', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/service/base')>()),+ request: (url: string) => request(url),+}))+vi.mock('@/app/components/app-sidebar/app-info', () => ({+ AppInfoView: ({ appDetail }: { appDetail: AppDetailWithSite }) => <span>{appDetail.name}</span>,+}))+vi.mock('@/app/components/app-sidebar/nav-link', () => ({+ default: ({ name, href }: { name: string; href: string }) => <a href={href}>{name}</a>,+}))++function Route() {+ const appId = getAppIdFromPathname(pathname)+ return (+ <>+ <a href="/apps">Back to Apps</a>+ {appId && <AppDetailPrefetch appId={appId} />}+ <AppDetailSection />+ </>+ )+}+const app = (id: string, name: string) =>+ createAppDetailFixture({+ id,+ name,+ permission_keys: [AppACLPermission.Monitor],+ })++describe('App sidebar route loading', () => {+ beforeEach(() => {+ pathname = '/app/app-1/overview'+ request.mockReset()+ })++ it('keeps the shell visible and consumes the in-flight prefetch without an App Store producer', async () => {+ const pending = deferredResponse()+ request.mockReturnValue(pending.promise)+ const view = renderWithConsoleQuery(<Route />)+ expect(screen.getByRole('link', { name: 'Back to Apps' })).toBeVisible()+ expect(view.container.querySelector('[aria-busy="true"]')).toBeInTheDocument()+ expect(screen.queryByRole('link', { name: 'common.appMenus.overview' })).not.toBeInTheDocument()+ await waitFor(() => expect(request).toHaveBeenCalledTimes(1))+ await act(async () => pending.resolve(Response.json(app('app-1', 'First app'))))+ expect(await screen.findByText('First app')).toBeVisible()+ expect(screen.getByRole('link', { name: 'common.appMenus.overview' })).toHaveAttribute(+ 'href',+ '/app/app-1/overview',+ )+ expect(request).toHaveBeenCalledTimes(1)+ expect(useStore.getState().appDetail).toBeUndefined()+ })++ it('can load without prefetch and retries a failed query inside the sidebar', async () => {+ request.mockRejectedValueOnce(new Error('unavailable'))+ request.mockResolvedValue(Response.json(app('app-1', 'Recovered app')))+ renderWithConsoleQuery(<AppDetailSection />)+ expect(await screen.findByRole('alert')).toBeVisible()+ const user = userEvent.setup()+ await user.click(screen.getByRole('button', { name: 'common.errorBoundary.tryAgain' }))+ expect(await screen.findByText('Recovered app')).toBeVisible()+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()+ })++ it('keeps a late response for A out of B and removes app UI when leaving the route', async () => {+ const a = deferredResponse()+ const b = deferredResponse()+ request.mockImplementation((url) => (url.endsWith('/app-1') ? a.promise : b.promise))+ const view = renderWithConsoleQuery(<Route />)+ await waitFor(() => expect(request).toHaveBeenCalledTimes(1))+ pathname = '/app/app-2/logs'+ view.rerender(<Route />)+ await waitFor(() => expect(request).toHaveBeenCalledTimes(2))+ await act(async () => b.resolve(Response.json(app('app-2', 'Second app'))))+ expect(await screen.findByText('Second app')).toBeVisible()+ await act(async () => a.resolve(Response.json(app('app-1', 'First app'))))+ expect(screen.queryByText('First app')).not.toBeInTheDocument()+ expect(screen.getByRole('link', { name: 'common.appMenus.overview' })).toHaveAttribute(+ 'href',+ '/app/app-2/overview',+ )+ pathname = '/apps'+ view.rerender(<Route />)+ expect(screen.queryByText('Second app')).not.toBeInTheDocument()+ expect(request).toHaveBeenCalledTimes(2)+ })++ it('shares cached data between sections and reacts to metadata and permission changes', async () => {+ request.mockResolvedValue(Response.json(app('app-1', 'First app')))+ const view = renderWithConsoleQuery(<Route />)+ await screen.findByText('First app')+ pathname = '/app/app-1/logs'+ view.rerender(<Route />)+ expect(screen.getByText('First app')).toBeVisible()+ expect(request).toHaveBeenCalledTimes(1)+ await act(async () => {+ view.queryClient.setQueryData(+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),+ {+ ...app('app-1', 'Renamed app'),+ permission_keys: [],+ },+ )+ })+ expect(await screen.findByText('Renamed app')).toBeVisible()+ expect(screen.queryByRole('link', { name: 'common.appMenus.overview' })).not.toBeInTheDocument()+ })++ it.each([+ '/apps',+ '/agents/agent-1',+ '/datasets/data-1',+ '/snippets/snippet-1',+ '/app/',+ '/app//workflow',+ ])('does not request App Detail at %s', (path) => {+ pathname = path+ renderWithConsoleQuery(<Route />)+ expect(request).not.toHaveBeenCalled()+ })+})diff --git a/web/app/components/app/app-detail-prefetch.tsx b/web/app/components/app/app-detail-prefetch.tsxnew file mode 100644index 00000000000..cb4ef6e5a92--- /dev/null+++ b/web/app/components/app/app-detail-prefetch.tsx@@ -0,0 +1,13 @@+'use client'++import { usePrefetchQuery } from '@tanstack/react-query'+import { consoleQuery } from '@/service/console'++export function AppDetailPrefetch({ appId }: { appId: string }) {+ usePrefetchQuery(+ consoleQuery.apps.byAppId.get.queryOptions({+ input: { params: { app_id: appId } },+ }),+ )+ return null+}diff --git a/web/app/components/app/app-detail-route.ts b/web/app/components/app/app-detail-route.tsnew file mode 100644index 00000000000..f299b89e41d--- /dev/null+++ b/web/app/components/app/app-detail-route.ts@@ -0,0 +1,4 @@+export function getAppIdFromPathname(pathname: string) {+ const [, section, appId] = pathname.split('/')+ return section === 'app' && appId ? appId : undefined+}diff --git a/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx b/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsxindex 56ad52cd61d..48dd4273682 100644--- a/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/features-wrapper.spec.tsx@@ -100,6 +100,7 @@ describe('FeaturesWrappedAppPublisher', () => {it('should pass current features through to onPublish', async () => {render(<FeaturesWrappedAppPublisher+ appId="app-1"publishedConfig={publishedConfig as any}onPublish={mockOnPublish}/>,@@ -115,6 +116,7 @@ describe('FeaturesWrappedAppPublisher', () => {it('should pass publish notification options through to onPublish', async () => {render(<FeaturesWrappedAppPublisher+ appId="app-1"publishedConfig={publishedConfig as any}onPublish={mockOnPublish}/>,@@ -132,6 +134,7 @@ describe('FeaturesWrappedAppPublisher', () => {it('should restore published features after confirmation', async () => {render(<FeaturesWrappedAppPublisher+ appId="app-1"publishedConfig={publishedConfig as any}resetAppConfig={resetAppConfig}/>,@@ -164,6 +167,7 @@ describe('FeaturesWrappedAppPublisher', () => {it('should close restore confirmation without restoring when cancelled', async () => {render(<FeaturesWrappedAppPublisher+ appId="app-1"publishedConfig={publishedConfig as any}resetAppConfig={resetAppConfig}/>,diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsxindex 57e3daf7abe..e3eb1dc87ae 100644--- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx@@ -6,12 +6,29 @@ import { WorkflowContext } from '@/app/components/workflow/context'import { AccessMode } from '@/models/access-control'import { consoleQuery } from '@/service/console'import { appWorkflowVersionsInfiniteQueryOptions } from '@/service/workflow-queries'-import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'+import {+ createConsoleQueryClient,+ 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'+let mockAppDetail: Record<string, any> | null = null++const renderWithConsoleQuery = (+ ui: React.ReactElement,+ options: Parameters<typeof renderWithQuery>[1] = {},+) => {+ const queryClient = options?.queryClient ?? createConsoleQueryClient()+ const key = consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } })+ if (mockAppDetail) queryClient.setQueryData(key, createAppDetailFixture(mockAppDetail))+ else queryClient.setQueryDefaults(key, { queryFn: () => new Promise(() => {}) })+ return renderWithQuery(ui, { ...options, queryClient })+}+const render = (ui: React.ReactElement,queryClient?: ReturnType<typeof createConsoleQueryClient>,@@ -54,14 +71,8 @@ const collaborationMocks = vi.hoisted(() => ({| undefined,}))-let mockAppDetail: Record<string, any> | null = nulllet mockWorkspacePermissionKeys: string[] = ['tool.manage']-vi.mock('@/app/components/app/store', () => ({- useStore: (selector: (state: { appDetail: Record<string, any> | null }) => unknown) =>- selector({ appDetail: mockAppDetail }),-}))-vi.mock('@/hooks/use-format-time-from-now', () => ({useFormatTimeFromNow: () => ({formatTimeFromNow: () => 'moments ago',@@ -275,7 +286,7 @@ describe('AppPublisher', () => {})it('should enable access permission query when the publish popover opens', async () => {- render(<AppPublisher publishedAt={Date.now()} onToggle={mockOnToggle} />)+ render(<AppPublisher appId="app-1" publishedAt={Date.now()} onToggle={mockOnToggle} />)fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))@@ -292,7 +303,7 @@ describe('AppPublisher', () => {})it('should not render Web app access control in the publish popover', () => {- render(<AppPublisher publishedAt={Date.now()} />)+ render(<AppPublisher appId="app-1" publishedAt={Date.now()} />)fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))@@ -302,7 +313,7 @@ describe('AppPublisher', () => {it('should publish once per open session and reset the lock after reopening', async () => {mockOnPublish.mockResolvedValue(undefined)- render(<AppPublisher publishedAt={Date.now()} onPublish={mockOnPublish} />)+ render(<AppPublisher appId="app-1" publishedAt={Date.now()} onPublish={mockOnPublish} />)fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))fireEvent.click(screen.getByText('publisher-summary-publish'))@@ -351,9 +362,12 @@ describe('AppPublisher', () => {queryClient.setQueryDefaults(environmentsQuery.queryKey, { staleTime: Infinity })queryClient.setQueryData(environmentsQuery.queryKey, { data: [] })- renderWithConsoleQuery(<AppPublisher publishedAt={Date.now()} onPublish={mockOnPublish} />, {- queryClient,- })+ renderWithConsoleQuery(+ <AppPublisher appId="app-1" publishedAt={Date.now()} onPublish={mockOnPublish} />,+ {+ queryClient,+ },+ )await user.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))await user.click(screen.getByText('publisher-summary-publish'))@@ -389,9 +403,12 @@ describe('AppPublisher', () => {}mockOnPublish.mockResolvedValue(undefined)- renderWithConsoleQuery(<AppPublisher publishedAt={Date.now()} onPublish={mockOnPublish} />, {- queryClient,- })+ renderWithConsoleQuery(+ <AppPublisher appId="app-1" publishedAt={Date.now()} onPublish={mockOnPublish} />,+ {+ queryClient,+ },+ )await user.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))await user.click(screen.getByText('publisher-summary-publish'))@@ -415,7 +432,7 @@ describe('AppPublisher', () => {marked_comment: 'Initial notes',}- render(<AppPublisher publishedAt={Date.now()} />)+ render(<AppPublisher appId="app-1" publishedAt={Date.now()} />)await user.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))expect(sectionProps.summary).toEqual(@@ -478,7 +495,7 @@ describe('AppPublisher', () => {queryClient.setQueryDefaults(environmentsQuery.queryKey, { staleTime: Infinity })queryClient.setQueryData(environmentsQuery.queryKey, { data: [] })- renderWithConsoleQuery(<AppPublisher publishedAt={Date.now()} />, {+ renderWithConsoleQuery(<AppPublisher appId="app-1" publishedAt={Date.now()} />, {queryClient,systemFeatures: { webapp_auth: { enabled: true }, enable_app_deploy: false },})@@ -500,7 +517,7 @@ describe('AppPublisher', () => {permission_keys: [],}- renderWithConsoleQuery(<AppPublisher publishedAt={Date.now()} />, {+ renderWithConsoleQuery(<AppPublisher appId="app-1" publishedAt={Date.now()} />, {systemFeatures: { webapp_auth: { enabled: true }, enable_app_deploy: false },})@@ -512,7 +529,7 @@ describe('AppPublisher', () => {})it('should keep the single-environment publisher for unsupported app types', () => {- renderWithConsoleQuery(<AppPublisher publishedAt={Date.now()} />, {+ renderWithConsoleQuery(<AppPublisher appId="app-1" publishedAt={Date.now()} />, {systemFeatures: { webapp_auth: { enabled: true }, enable_app_deploy: true },})@@ -602,10 +619,13 @@ describe('AppPublisher', () => {},],})- const { rerender } = renderWithConsoleQuery(<AppPublisher publishedAt={publishedAt} />, {- queryClient,- systemFeatures: { webapp_auth: { enabled: true }, enable_app_deploy: true },- })+ const { rerender } = renderWithConsoleQuery(+ <AppPublisher appId="app-1" publishedAt={publishedAt} />,+ {+ queryClient,+ systemFeatures: { webapp_auth: { enabled: true }, enable_app_deploy: true },+ },+ )await user.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))await user.click(@@ -628,7 +648,7 @@ describe('AppPublisher', () => {isLoading: false,isSuccess: true,}- rerender(<AppPublisher publishedAt={publishedAt} />)+ rerender(<AppPublisher appId="app-1" publishedAt={publishedAt} />)expect(await screen.findByText(/studio\.accessPoint\.noPublishedTitle/)).toBeInTheDocument()expect(screen.getByText(/studio\.publisher\.noPublishedDescription/)).toBeInTheDocument()@@ -642,7 +662,7 @@ describe('AppPublisher', () => {marked_name: 'Release 5',version: 'v5',}- rerender(<AppPublisher publishedAt={publishedAt} />)+ rerender(<AppPublisher appId="app-1" publishedAt={publishedAt} />)expect(await screen.findByText(/studio\.publisher\.notDeployedYet/)).toBeInTheDocument()expect(screen.queryByText(/studio\.publisher\.noPublishedDescription/)).not.toBeInTheDocument()@@ -730,7 +750,7 @@ describe('AppPublisher', () => {throw new Error(`Unexpected request: ${request.method} ${request.url}`)})- renderWithConsoleQuery(<AppPublisher publishedAt={Date.now()} />, {+ renderWithConsoleQuery(<AppPublisher appId="app-1" publishedAt={Date.now()} />, {queryClient,systemFeatures: { webapp_auth: { enabled: true }, enable_app_deploy: true },})@@ -770,6 +790,7 @@ describe('AppPublisher', () => {it('should collect hidden inputs before opening the web app from its config action', async () => {render(<AppPublisher+ appId="app-1"publishedAt={Date.now()}inputs={[{@@ -814,7 +835,7 @@ describe('AppPublisher', () => {mode: AppModeEnum.WORKFLOW,}- render(<AppPublisher publishedAt={Date.now()} toolPublished />)+ render(<AppPublisher appId="app-1" publishedAt={Date.now()} toolPublished />)fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))expect(sectionProps.actions).toEqual(@@ -839,7 +860,7 @@ describe('AppPublisher', () => {})mockCreateWorkflowToolProvider.mockResolvedValue({})- render(<AppPublisher publishedAt={Date.now()} onPublish={mockOnPublish} />)+ render(<AppPublisher appId="app-1" publishedAt={Date.now()} onPublish={mockOnPublish} />)fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))fireEvent.click(screen.getByText('publisher-workflow-tool'))@@ -862,7 +883,7 @@ describe('AppPublisher', () => {})mockCreateWorkflowToolProvider.mockRejectedValue(new Error('create failed'))- render(<AppPublisher publishedAt={Date.now()} onPublish={mockOnPublish} />)+ render(<AppPublisher appId="app-1" publishedAt={Date.now()} onPublish={mockOnPublish} />)fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))fireEvent.click(screen.getByText('publisher-workflow-tool'))@@ -883,7 +904,7 @@ describe('AppPublisher', () => {}mockOnPublish.mockRejectedValueOnce(new Error('publish failed'))- render(<AppPublisher publishedAt={Date.now()} onPublish={mockOnPublish} />)+ render(<AppPublisher appId="app-1" publishedAt={Date.now()} onPublish={mockOnPublish} />)fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))fireEvent.click(screen.getByText('publisher-workflow-tool'))@@ -904,7 +925,7 @@ describe('AppPublisher', () => {mode: AppModeEnum.WORKFLOW,}- render(<AppPublisher publishedAt={Date.now()} />)+ render(<AppPublisher appId="app-1" publishedAt={Date.now()} />)fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))fireEvent.click(screen.getByText('publisher-workflow-tool'))@@ -914,7 +935,7 @@ describe('AppPublisher', () => {})it('should ignore the trigger when the publish button is disabled', () => {- render(<AppPublisher disabled publishedAt={Date.now()} onToggle={mockOnToggle} />)+ render(<AppPublisher appId="app-1" disabled publishedAt={Date.now()} onToggle={mockOnToggle} />)fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/).parentElement@@ -930,7 +951,12 @@ describe('AppPublisher', () => {mockOnPublish.mockRejectedValueOnce(new Error('publish failed'))render(- <AppPublisher publishedAt={Date.now()} onPublish={mockOnPublish} onRestore={onRestore} />,+ <AppPublisher+ appId="app-1"+ publishedAt={Date.now()}+ onPublish={mockOnPublish}+ onRestore={onRestore}+ />,)fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))@@ -951,9 +977,12 @@ describe('AppPublisher', () => {})const windowOpenSpy = vi.spyOn(window, 'open').mockImplementation(() => null)- renderWithConsoleQuery(<AppPublisher publishedAt={Date.now()} onPublish={mockOnPublish} />, {- systemFeatures: { webapp_auth: { enabled: true }, enable_creators_platform: true },- })+ renderWithConsoleQuery(+ <AppPublisher appId="app-1" publishedAt={Date.now()} onPublish={mockOnPublish} />,+ {+ systemFeatures: { webapp_auth: { enabled: true }, enable_creators_platform: true },+ },+ )fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))expect(sectionProps.actions).toEqual(@@ -978,9 +1007,12 @@ describe('AppPublisher', () => {it('should show toast error when publish to marketplace fails', async () => {mockPublishToCreatorsPlatform.mockRejectedValue(new Error('network error'))- renderWithConsoleQuery(<AppPublisher publishedAt={Date.now()} onPublish={mockOnPublish} />, {- systemFeatures: { webapp_auth: { enabled: true }, enable_creators_platform: true },- })+ renderWithConsoleQuery(+ <AppPublisher appId="app-1" publishedAt={Date.now()} onPublish={mockOnPublish} />,+ {+ systemFeatures: { webapp_auth: { enabled: true }, enable_creators_platform: true },+ },+ )fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))fireEvent.click(screen.getByText(/(?:^|\.)common\.publishToMarketplace(?=$|:)/))@@ -993,7 +1025,7 @@ describe('AppPublisher', () => {})it('should disable marketplace button when not yet published', () => {- renderWithConsoleQuery(<AppPublisher onPublish={mockOnPublish} />, {+ renderWithConsoleQuery(<AppPublisher appId="app-1" onPublish={mockOnPublish} />, {systemFeatures: { webapp_auth: { enabled: true }, enable_creators_platform: true },})@@ -1014,7 +1046,7 @@ describe('AppPublisher', () => {})it('should hide marketplace button when enable_creators_platform is false', () => {- render(<AppPublisher publishedAt={Date.now()} onPublish={mockOnPublish} />)+ render(<AppPublisher appId="app-1" publishedAt={Date.now()} onPublish={mockOnPublish} />)fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))expect(sectionProps.actions?.showMarketplaceAction).toBe(false)@@ -1023,20 +1055,11 @@ describe('AppPublisher', () => {).not.toBeInTheDocument()})- it('should not infer an app mode when app detail is unavailable', async () => {- const user = userEvent.setup()+ it('waits for app details before exposing publishing actions', () => {mockAppDetail = null-- render(<AppPublisher publishedAt={Date.now()} />)-- await user.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))-- expect(sectionProps.summary).toEqual(- expect.objectContaining({- isChatApp: false,- isWorkflowApp: false,- }),- )+ render(<AppPublisher appId="app-1" publishedAt={Date.now()} />)+ expect(screen.queryByText(/(?:^|\.)common\.publish(?=$|:)/)).not.toBeInTheDocument()+ expect(sectionProps.summary).toBeNull()})it('should keep workflow publishing available for an existing published version', async () => {@@ -1053,6 +1076,7 @@ describe('AppPublisher', () => {mockOnPublish.mockResolvedValue(undefined)render(<AppPublisher+ appId="app-1"draftUpdatedAt={1_710_000_200_000}onPublish={mockOnPublish}publishedAt={1_710_000_100_000}@@ -1091,7 +1115,7 @@ describe('AppPublisher', () => {render(<WorkflowContext value={workflowStore as any}>- <AppPublisher publishedAt={1_710_000_100_000} />+ <AppPublisher appId="app-1" publishedAt={1_710_000_100_000} /></WorkflowContext>,queryClient,)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 84066d87d5c..b9196155f7e 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@@ -37,7 +37,8 @@ function PublisherPanelHarness({<PublisherPanelbuiltInPublisher={{actions: {- appDetail: { id: 'app-1', mode: AppModeEnum.CHAT },+ appId: 'app-1',+ appMode: AppModeEnum.CHAT,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 d9623a7e44a..7acbe20d41c 100644--- a/web/app/components/app/app-publisher/__tests__/sections.spec.tsx+++ b/web/app/components/app/app-publisher/__tests__/sections.spec.tsx@@ -534,10 +534,8 @@ describe('app-publisher sections', () => {render(<PublisherActionsSection- appDetail={{- id: 'workflow-app',- mode: AppModeEnum.WORKFLOW,- }}+ appId={'workflow-app'}+ appMode={AppModeEnum.WORKFLOW}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButton={false}@@ -596,10 +594,8 @@ describe('app-publisher sections', () => {render(<PublisherActionsSection- appDetail={{- id: 'workflow-app',- mode: AppModeEnum.WORKFLOW,- }}+ appId={'workflow-app'}+ appMode={AppModeEnum.WORKFLOW}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButton={false}@@ -629,10 +625,8 @@ describe('app-publisher sections', () => {it('should show the disabled reason below setup and configured workflow tool actions', () => {const commonProps = {- appDetail: {- id: 'workflow-app',- mode: AppModeEnum.WORKFLOW,- },+ appId: 'workflow-app',+ appMode: AppModeEnum.WORKFLOW,appURL: 'https://example.com/app',canViewAccessPoint: true,disabledFunctionButton: false,@@ -671,10 +665,8 @@ describe('app-publisher sections', () => {const user = userEvent.setup()const onConfigureWorkflowTool = vi.fn()const commonProps = {- appDetail: {- id: 'workflow-app',- mode: AppModeEnum.WORKFLOW,- },+ appId: 'workflow-app',+ appMode: AppModeEnum.WORKFLOW,appURL: 'https://example.com/app',canViewAccessPoint: true,disabledFunctionButton: false,@@ -717,10 +709,8 @@ describe('app-publisher sections', () => {it('should keep Access Point and Deploy available for trigger workflows', () => {render(<PublisherActionsSection- appDetail={{- id: 'trigger-app',- mode: AppModeEnum.WORKFLOW,- }}+ appId={'trigger-app'}+ appMode={AppModeEnum.WORKFLOW}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButton={false}@@ -749,7 +739,8 @@ describe('app-publisher sections', () => {it('should hide the Access Point publisher entry without view permission', () => {render(<PublisherActionsSection- appDetail={{ id: 'workflow-app', mode: AppModeEnum.WORKFLOW }}+ appId={'workflow-app'}+ appMode={AppModeEnum.WORKFLOW}appURL="https://example.com/app"canViewAccessPoint={false}disabledFunctionButton={false}@@ -773,7 +764,8 @@ describe('app-publisher sections', () => {it('should expose unavailable quick links as disabled buttons before the first publish', () => {render(<PublisherActionsSection- appDetail={{ id: 'workflow-app', mode: AppModeEnum.WORKFLOW }}+ appId={'workflow-app'}+ appMode={AppModeEnum.WORKFLOW}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButton@@ -802,7 +794,8 @@ describe('app-publisher sections', () => {render(<PublisherActionsSection- appDetail={{ id: 'workflow-app', mode: AppModeEnum.WORKFLOW }}+ appId={'workflow-app'}+ appMode={AppModeEnum.WORKFLOW}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButton@@ -828,7 +821,8 @@ describe('app-publisher sections', () => {render(<PublisherActionsSection- appDetail={{ id: 'workflow-app', mode: AppModeEnum.WORKFLOW }}+ appId={'workflow-app'}+ appMode={AppModeEnum.WORKFLOW}appURL="https://example.com/app"canViewAccessPointdisabledFunctionButtondiff --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 533b7dc4c19..6328556effd 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@@ -11,7 +11,8 @@ type PublisherActionsSectionProps = Pick<AppPublisherProps,'hasHumanInputNode' | 'hasTriggerNode' | 'publishedAt' | 'toolPublished' | 'workflowToolAvailable'> & {- appDetail: Partial<Pick<AppDetailWithSite, 'id' | 'mode'>> | null | undefined+ appId: string+ appMode: AppDetailWithSite['mode']appURL: stringcanViewAccessPoint: booleandisabledFunctionButton: boolean@@ -30,7 +31,8 @@ type PublisherActionsSectionProps = Pick<}export function PublisherActionsSection({- appDetail,+ appId,+ appMode,appURL,canViewAccessPoint,disabledFunctionButton,@@ -54,13 +56,10 @@ export function PublisherActionsSection({}: PublisherActionsSectionProps) {const { t } = useTranslation(['common', 'workflow'])- const appId = appDetail?.idconst hasPublishedVersion = Boolean(publishedAt)const showOpenWebApp = !hasTriggerNode- const showDeploy = Boolean(showDeployAction && appId)- const showWorkflowTool =- appDetail?.mode === AppModeEnum.WORKFLOW && !hasHumanInputNode && !hasTriggerNode- const navigationDisabled = !hasPublishedVersion || !appId+ const showWorkflowTool = appMode === AppModeEnum.WORKFLOW && !hasHumanInputNode && !hasTriggerNode+ const navigationDisabled = !hasPublishedVersionconst workflowToolDisabled =!hasPublishedVersion || !workflowToolAvailable || (toolPublished && workflowToolIsLoading)@@ -110,13 +109,13 @@ export function PublisherActionsSection({<SuggestedActiondisabled={navigationDisabled}description={t(($) => $['common.accessPointDescription'], { ns: 'workflow' })}- link={appId ? `/app/${appId}/access-point` : undefined}+ link={`/app/${appId}/access-point`}icon={<span className="i-custom-vender-agent-v2-access-point size-4" />}>{t(($) => $['appMenus.accessPoint'], { ns: 'common' })}</SuggestedAction>)}- {showDeploy && (+ {showDeployAction && (<SuggestedActiondisabled={navigationDisabled}description={t(($) => $['common.deployDescription'], { ns: 'workflow' })}diff --git a/web/app/components/app/app-publisher/index.tsx b/web/app/components/app/app-publisher/index.tsxindex 49d626233ed..23d87ec2d09 100644--- a/web/app/components/app/app-publisher/index.tsx+++ b/web/app/components/app/app-publisher/index.tsx@@ -1,38 +1,52 @@import type { AppPublisherProps } from './types'-import { useSuspenseQuery } from '@tanstack/react-query'+import { useSuspenseQueries } from '@tanstack/react-query'import { useAtom, useAtomValue } from 'jotai'-import { useStore as useAppStore } from '@/app/components/app/store'+import { Suspense } from 'react'+import { SkeletonRectangle } from '@/app/components/base/skeleton'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) {+ return (+ <Suspense fallback={<SkeletonRectangle className="h-8 w-20" />}>+ <AppPublisherContent {...props} />+ </Suspense>+ )+}++function AppPublisherContent(props: AppPublisherProps) {const [open, setOpen] = useAtom(appPublisherOpenAtom)- const appDetail = useAppStore((state) => state.appDetail)- const { data: currentUserId } = useSuspenseQuery({- ...userProfileQueryOptions(),- select: (data) => data.profile.id,+ const { appId } = props+ const [{ data: appDetail }, { data: profile }] = useSuspenseQueries({+ queries: [+ consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),+ userProfileQueryOptions(),+ ],})+ const currentUserId = profile.profile.idconst workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)- const { canDeploy, canViewAccessPoint } = getAppACLCapabilities(appDetail?.permission_keys, {+ const { canDeploy, canViewAccessPoint } = getAppACLCapabilities(appDetail.permission_keys, {currentUserId,- resourceMaintainer: appDetail?.maintainer,+ resourceMaintainer: appDetail.maintainer,workspacePermissionKeys,})const supportsMultiEnvironment =- (appDetail?.mode === AppModeEnum.WORKFLOW || appDetail?.mode === AppModeEnum.ADVANCED_CHAT) &&+ (appDetail.mode === AppModeEnum.WORKFLOW || appDetail.mode === AppModeEnum.ADVANCED_CHAT) &&canDeployreturn (<AppPublisherStateBoundary- appId={appDetail?.id}+ appId={appDetail.id}environmentQueryEnabled={supportsMultiEnvironment}><PublisherContent{...props}+ appDetail={appDetail}canViewAccessPoint={canViewAccessPoint}open={open}supportsMultiEnvironment={supportsMultiEnvironment}diff --git a/web/app/components/app/app-publisher/publisher-content/index.tsx b/web/app/components/app/app-publisher/publisher-content/index.tsxindex c9ed780a0b5..2730959d904 100644--- a/web/app/components/app/app-publisher/publisher-content/index.tsx+++ b/web/app/components/app/app-publisher/publisher-content/index.tsx@@ -1,9 +1,9 @@+import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'import type { AppPublisherProps } from '../types'import { useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue, useSetAtom } from 'jotai'import { useTranslation } from 'react-i18next'import { toDeploymentVersion } from '@/app/components/app/deploy/utils/version'-import { useStore as useAppStore } from '@/app/components/app/store'import { WorkflowToolDrawer } from '@/app/components/tools/workflow-tool'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'@@ -33,6 +33,7 @@ import { useWorkflowLaunch } from './use-workflow-launch'import { useWorkflowTool } from './use-workflow-tool'type PublisherContentProps = AppPublisherProps & {+ appDetail: AppDetailWithSitecanViewAccessPoint: booleanopen: booleansupportsMultiEnvironment: boolean@@ -40,6 +41,7 @@ type PublisherContentProps = AppPublisherProps & {}export function PublisherContent({+ appDetail,canViewAccessPoint,crossAxisOffset = 0,debugWithMultipleModel = false,@@ -65,7 +67,6 @@ export function PublisherContent({workflowToolAvailable = true,}: PublisherContentProps) {const { t } = useTranslation(['app', 'workflow', 'workflowHistory'])- const appDetail = useAppStore((state) => state.appDetail)const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const { formatTimeFromNow } = useFormatTimeFromNow()const environments = useAtomValue(appPublisherEnvironmentsAtom)@@ -82,16 +83,16 @@ export function PublisherContent({const addEnvironment = useSetAtom(addPublisherEnvironmentAtom)const selectEnvironment = useSetAtom(selectedPublisherEnvironmentIdAtom)- useRefreshAppEnvironmentsAfterPublisherDeploymentPolling(appDetail?.id)+ useRefreshAppEnvironmentsAfterPublisherDeploymentPolling(appDetail.id)function closePublisher() {onOpenStateChange(false)}const publish = usePublishController({- appId: appDetail?.id,- appMode: appDetail?.mode,- appName: appDetail?.name,+ appId: appDetail.id,+ appMode: appDetail.mode,+ appName: appDetail.name,onClose: closePublisher,onPublish,onRestore,@@ -111,21 +112,21 @@ export function PublisherContent({}const workflowLaunch = useWorkflowLaunch(inputs)- const marketplace = useMarketplacePublish(appDetail?.id)+ const marketplace = useMarketplacePublish(appDetail.id)const versionInfo = useVersionInfo({- appId: appDetail?.id,- appMode: appDetail?.mode,+ appId: appDetail.id,+ appMode: appDetail.mode,publishedWorkflow: publish.publishedWorkflow,onClosePublisher: closePublisher,})const workflowTool = useWorkflowTool({- appDescription: appDetail?.description,- appIcon: appDetail?.icon,- appIconBackground: appDetail?.icon_background,- appIconType: appDetail?.icon_type,- appId: appDetail?.id,- appMode: appDetail?.mode,- appName: appDetail?.name,+ appDescription: appDetail.description,+ appIcon: appDetail.icon,+ appIconBackground: appDetail.icon_background,+ appIconType: appDetail.icon_type,+ appId: appDetail.id,+ appMode: appDetail.mode,+ appName: appDetail.name,appPublished: publish.published,hasHumanInputNode,hasPublishedVersion: publish.hasPublishedVersion,@@ -138,22 +139,21 @@ export function PublisherContent({toolPublished,workflowToolAvailable,})- const { app_base_url: appBaseURL = '', access_token: accessToken = '' } = appDetail?.site ?? {}+ const { app_base_url: appBaseURL = '', access_token: accessToken = '' } = appDetail.site ?? {}const appURL = getPublisherAppUrl({appBaseUrl: appBaseURL,accessToken: accessToken ?? '',- mode: appDetail?.mode,+ mode: appDetail.mode,})const shouldLoadUserCanAccessApp = Boolean(- appDetail?.id && open && systemFeatures.webapp_auth.enabled,+ appDetail.id && open && systemFeatures.webapp_auth.enabled,)const { data: userCanAccessApp } = useGetUserCanAccessApp({- appId: appDetail?.id,+ appId: appDetail.id,enabled: shouldLoadUserCanAccessApp,})const noAccessPermission = Boolean(systemFeatures.webapp_auth.enabled &&- appDetail &&appDetail.access_mode !== AccessMode.EXTERNAL_MEMBERS &&!userCanAccessApp?.result,)@@ -213,7 +213,8 @@ export function PublisherContent({versionInfo: publish.publishedWorkflow,},actions: {- appDetail,+ appId: appDetail.id,+ appMode: appDetail.mode,appURL,canViewAccessPoint,disabledFunctionButton,@@ -239,7 +240,7 @@ export function PublisherContent({crossAxisOffset={crossAxisOffset}disabled={disabled}environmentPublisher={{- appId: appDetail?.id,+ appId: appDetail.id,canViewAccessPoint,deployment: selectedEnvironmentDeployment,environmentId: selectedEnvironmentId,diff --git a/web/app/components/app/app-publisher/types.ts b/web/app/components/app/app-publisher/types.tsindex bf457fdc1f7..89a7ac58887 100644--- a/web/app/components/app/app-publisher/types.ts+++ b/web/app/components/app/app-publisher/types.ts@@ -19,6 +19,7 @@ type AppPublisherPublishHandler =type AppPublisherRestoreHandler = () => Promise<unknown> | unknownexport type AppPublisherProps = {+ appId: stringdisabled?: booleanpublishDisabled?: booleanpublishedAt?: numberdiff --git a/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx b/web/app/components/app/configuration/__tests__/configuration-view.spec.tsxindex 7e9586c2560..caa35d672ea 100644--- a/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx+++ b/web/app/components/app/configuration/__tests__/configuration-view.spec.tsx@@ -243,6 +243,7 @@ const createViewModel = (overrides: Partial<ConfigurationViewModel> = {},): ConfigurationViewModel => ({appPublisherProps: {+ appId: 'app-1',publishDisabled: false,publishedAt: 0,debugWithMultipleModel: false,diff --git a/web/app/components/app/configuration/hooks/use-configuration.ts b/web/app/components/app/configuration/hooks/use-configuration.tsindex e5c0e67e0a8..ba65d4a62b8 100644--- a/web/app/components/app/configuration/hooks/use-configuration.ts+++ b/web/app/components/app/configuration/hooks/use-configuration.ts@@ -394,6 +394,7 @@ export const useConfiguration = (): ConfigurationViewModel => {return {appPublisherProps: {+ appId,disabled: !appACLCapabilities.canReleaseAndVersion,publishDisabled: cannotPublish || !appACLCapabilities.canReleaseAndVersion,publishedAt: (serverLatestPublishedAt || 0) * 1000,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 72939daaa33..96e16a1c575 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@@ -3,7 +3,6 @@ import type { ReactElement } from 'react'import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'-import { useStore as useAppStore } from '@/app/components/app/store'import { renderWithConsoleQuery } from '@/test/console/query-data'import { mockEmojiData } from '@/test/emoji-picker'import { AppModeEnum } from '@/types/app'@@ -127,7 +126,7 @@ const renderComponent = (overrides: Partial<React.ComponentProps<typeof SwitchApconst appDetail = createMockApp()const utils = render(- <SwitchAppModal show appDetail={appDetail} onClose={onClose} {...overrides} />,+ <SwitchAppModal show sourceApp={appDetail} onClose={onClose} {...overrides} />,)return {@@ -138,8 +137,6 @@ const renderComponent = (overrides: Partial<React.ComponentProps<typeof SwitchAp}}-const setAppDetailSpy = vi.fn()-function render(ui: ReactElement) {return renderWithConsoleQuery(ui, {systemFeatures: { deployment_edition: deploymentEdition },@@ -152,12 +149,6 @@ describe('SwitchAppModal', () => {vi.clearAllMocks()mockConvertToWorkflow.mockReset()mockDeleteOriginalApp.mockReset()- // Spy on setAppDetail- const originalSetAppDetail = useAppStore.getState().setAppDetail- setAppDetailSpy.mockImplementation((...args: Parameters<typeof originalSetAppDetail>) => {- originalSetAppDetail(...args)- })- useAppStore.setState({ setAppDetail: setAppDetailSpy as typeof originalSetAppDetail })deploymentEdition = 'COMMUNITY'mockPlan = {type: 'sandbox',@@ -359,7 +350,7 @@ describe('SwitchAppModal', () => {it('should delete the original app and use replace when remove original is confirmed', async () => {const user = userEvent.setup()// Arrange- const { appDetail } = renderComponent({ inAppDetail: true })+ const { appDetail } = renderComponent()mockConvertToWorkflow.mockResolvedValueOnce({new_app_id: 'new-app-002',permission_keys: ['app.acl.view_layout'],@@ -379,7 +370,6 @@ describe('SwitchAppModal', () => {})expect(mockReplace).toHaveBeenCalledWith('/app/new-app-002/workflow')expect(mockPush).not.toHaveBeenCalled()- expect(setAppDetailSpy).toHaveBeenCalledTimes(1)})it('should notify error when switch app fails', async () => {diff --git a/web/app/components/app/switch-app-modal/index.tsx b/web/app/components/app/switch-app-modal/index.tsxindex c3c43174e3a..0aa57a1cc76 100644--- a/web/app/components/app/switch-app-modal/index.tsx+++ b/web/app/components/app/switch-app-modal/index.tsx@@ -19,7 +19,6 @@ import { Input } from '@langgenius/dify-ui/input'import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useId, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useStore as useAppStore } from '@/app/components/app/store'import AppIcon from '@/app/components/base/app-icon'import { IconPickerDialog } from '@/app/components/base/icon-picker'import AppsFull from '@/app/components/billing/apps-full-in-dialog'@@ -32,19 +31,17 @@ import { getRedirection } from '@/utils/app-redirection'type SwitchAppModalProps = {show: boolean- appDetail: Pick<+ sourceApp: Pick<AppPartial,'icon' | 'icon_background' | 'icon_type' | 'icon_url' | 'id' | 'mode' | 'name'>onClose: () => void- inAppDetail?: boolean}-const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onClose }: SwitchAppModalProps) => {+const SwitchAppModal = ({ show, sourceApp, onClose }: SwitchAppModalProps) => {const { push, replace } = useRouter()const nameInputId = useId()const { t } = useTranslation(['app', 'common'])- const setAppDetail = useAppStore((s) => s.setAppDetail)const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const isRbacEnabled = systemFeatures.rbac_enabled@@ -64,18 +61,18 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onClose }: SwitcappQuota.size >= appQuota.limitconst [showIconPicker, setShowIconPicker] = useState(false)- const appIconType = zIconType.safeParse(appDetail.icon_type).data+ const appIconType = zIconType.safeParse(sourceApp.icon_type).dataconst [appIcon, setAppIcon] = useState(appIconType === 'image'- ? { type: 'image' as const, url: appDetail.icon_url ?? '', fileId: appDetail.icon ?? '' }+ ? { type: 'image' as const, url: sourceApp.icon_url ?? '', fileId: sourceApp.icon ?? '' }: {type: 'emoji' as const,- icon: appDetail.icon ?? '',- background: appDetail.icon_background,+ icon: sourceApp.icon ?? '',+ background: sourceApp.icon_background,},)- const [name, setName] = useState(`${appDetail.name}(copy)`)+ const [name, setName] = useState(`${sourceApp.name}(copy)`)const [removeOriginal, setRemoveOriginal] = useState<boolean>(false)const [showConfirmDelete, setShowConfirmDelete] = useState(false)const { mutateAsync: convertToWorkflow } = useMutation(@@ -89,7 +86,7 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onClose }: Switcif (isAppQuotaUnavailable || isAppsFull) returntry {const { new_app_id: newAppID, permission_keys } = await convertToWorkflow({- params: { app_id: appDetail.id },+ params: { app_id: sourceApp.id },body: {name,icon_type: appIcon.type,@@ -99,16 +96,15 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onClose }: Switc})onClose()toast.success(t(($) => $['newApp.appCreated'], { ns: 'app' }))- if (inAppDetail) setAppDetail()if (removeOriginal)await deleteOriginalApp({- params: { app_id: appDetail.id },+ params: { app_id: sourceApp.id },})getRedirection({id: newAppID,mode:- appDetail.mode === AppModeEnum.COMPLETION+ sourceApp.mode === AppModeEnum.COMPLETION? AppModeEnum.WORKFLOW: AppModeEnum.ADVANCED_CHAT,permission_keys,diff --git a/web/app/components/apps/app-card/interactions.tsx b/web/app/components/apps/app-card/interactions.tsxindex 85e82ff5a0b..313d6d56936 100644--- a/web/app/components/apps/app-card/interactions.tsx+++ b/web/app/components/apps/app-card/interactions.tsx@@ -678,7 +678,7 @@ export function AppCardInteractions({/>)}{activeDialog === 'switch' && (- <SwitchAppModal show appDetail={app} onClose={() => setActiveDialog(null)} />+ <SwitchAppModal show sourceApp={app} onClose={() => setActiveDialog(null)} />)}<AlertDialog open={activeDialog === 'delete'} onOpenChange={onDeleteDialogOpenChange}><AlertDialogContent>diff --git a/web/app/components/main-nav/layout.tsx b/web/app/components/main-nav/layout.tsxindex 0a6a0950e9c..97c07d2be67 100644--- a/web/app/components/main-nav/layout.tsx+++ b/web/app/components/main-nav/layout.tsx@@ -9,6 +9,8 @@ import { useHydrateAtoms } from 'jotai/utils'import { useEffect } from 'react'import { useTranslation } from 'react-i18next'import { useShallow } from 'zustand/react/shallow'+import { AppDetailPrefetch } from '@/app/components/app/app-detail-prefetch'+import { getAppIdFromPathname } from '@/app/components/app/app-detail-route'import { useStore as useAppStore } from '@/app/components/app/store'import { detailSidebarModeAtom } from '@/app/components/detail-sidebar/state'import { isCurrentWorkspaceDatasetOperatorAtom } from '@/context/workspace-state'@@ -54,6 +56,7 @@ const MainNavLayout = ({const { t } = useTranslation(['common'])const pathname = usePathname()const isCurrentWorkspaceDatasetOperator = useAtomValue(isCurrentWorkspaceDatasetOperatorAtom)+ const appId = getAppIdFromPathname(pathname)const useResponsiveNavigation =pathname === '/agents' ||pathname === '/datasets/create' ||@@ -72,6 +75,7 @@ const MainNavLayout = ({)}><SkipNav>{t(($) => $['navigation.skipToMain'])}</SkipNav>+ {appId && <AppDetailPrefetch appId={appId} />}<AppDetailStoreCleanup />{hideMainNavigation ? null : useDetailSidebar ? (detailSidebardiff --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 e1fdafd8c72..99fecac063d 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@@ -6,6 +6,7 @@ import { BlockEnum } from '@/app/components/workflow/types'import WorkflowChildren from '../workflow-children'type WorkflowStoreState = {+ appId?: stringshowFeaturesPanel: booleanshowImportDSLModal: booleansetShowImportDSLModal: (show: boolean) => void@@ -334,6 +335,7 @@ describe('WorkflowChildren', () => {beforeEach(() => {vi.clearAllMocks()workflowStoreState = {+ appId: 'app-1',showFeaturesPanel: false,showImportDSLModal: false,setShowImportDSLModal: mockSetShowImportDSLModal,diff --git a/web/app/components/workflow-app/components/workflow-children.tsx b/web/app/components/workflow-app/components/workflow-children.tsxindex c780fee44ae..cb2bf2786b7 100644--- a/web/app/components/workflow-app/components/workflow-children.tsx+++ b/web/app/components/workflow-app/components/workflow-children.tsx@@ -20,6 +20,7 @@ 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'@@ -62,6 +63,8 @@ const getTriggerPluginNodeData = (}const WorkflowChildren = () => {+ const appId = useStore((s) => s.appId)+ const isChatMode = useIsChatMode()const { eventEmitter } = useEventEmitterContextContext()const [secretEnvList, setSecretEnvList] = useState<ExportSecretEnvironmentVariable[]>([])const showFeaturesPanel = useStore((s) => s.showFeaturesPanel)@@ -170,8 +173,10 @@ const WorkflowChildren = () => {onSelectStartNode={handleSelectStartNode}/>)}- {canImportExportDSL && showImportDSLModal && (+ {appId && canImportExportDSL && showImportDSLModal && (<UpdateDSLModal+ appId={appId}+ appMode={isChatMode ? 'advanced-chat' : 'workflow'}onCancel={() => setShowImportDSLModal(false)}onBackup={exportCheck!}onImport={handlePaneContextmenuCancel}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 0e9b2435adf..d66c59a5326 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@@ -165,10 +165,13 @@ const FeaturesTrigger = () => {const res = await consoleClient.apps.byAppId.get({ params: { app_id: appID } })setAppDetail({ ...res })+ void queryClient.invalidateQueries({+ queryKey: consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: appID } } }),+ })} catch (error) {console.error(error)}- }, [appID, setAppDetail])+ }, [appID, setAppDetail, queryClient])const { mutateAsync: publishWorkflow } = usePublishWorkflow()// const { validateBeforeRun } = useWorkflowRunValidation()@@ -276,6 +279,7 @@ const FeaturesTrigger = () => {</Button>)}<AppPublisher+ appId={appID!}{...{publishedAt,draftUpdatedAt,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 2327337e520..7ea63f2f803 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@@ -3,6 +3,8 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, renderHook, waitFor } from '@testing-library/react'import { createElement } from 'react'import { DSL_EXPORT_CHECK } from '@/app/components/workflow/constants'+import { consoleQuery } from '@/service/console'+import { createAppDetailFixture } from '@/test/fixtures/app'import { useDSLByCanEdit } from '../use-DSL'const toastMocks = vi.hoisted(() => ({@@ -37,7 +39,7 @@ const mockExportAppConfig = vi.fn()const mockFetchEnvironmentVariables = vi.fn()const mockDownloadBlob = vi.fn()-let appStoreState: {+let appQueryFixture: {appDetail?: {id: stringname: string@@ -52,17 +54,21 @@ vi.mock('@/context/event-emitter', () => ({}),}))-vi.mock('@/app/components/app/store', () => ({- useStore: <T>(selector: (state: typeof appStoreState) => T) => selector(appStoreState),+vi.mock('@/service/base', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/service/base')>()),+ request: () => new Promise<Response>(() => {}),}))+vi.mock('@/next/navigation', () => ({ useParams: () => ({ appId: 'app-1' }) }))+vi.mock('../use-nodes-sync-draft', () => ({useNodesSyncDraftByCanEdit: () => ({doSyncWorkflowDraft: mockDoSyncWorkflowDraft,}),}))-vi.mock('@/service/console', () => ({+vi.mock('@/service/console', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/service/console')>()),consoleClient: {apps: {byAppId: {@@ -92,14 +98,25 @@ const createDeferred = <T>() => {}let queryClient: QueryClient-const wrapper = ({ children }: { children: ReactNode }) =>- createElement(QueryClientProvider, { client: queryClient }, children)+const wrapper = ({ children }: { children: ReactNode }) => {+ if (appQueryFixture.appDetail)+ queryClient.setQueryData(+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),+ createAppDetailFixture(appQueryFixture.appDetail),+ )+ return createElement(QueryClientProvider, { client: queryClient }, children)+}describe('useDSLByCanEdit', () => {beforeEach(() => {vi.clearAllMocks()- queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } })- appStoreState = {+ queryClient = new QueryClient({+ defaultOptions: {+ queries: { staleTime: Infinity, retry: false },+ mutations: { retry: false },+ },+ })+ appQueryFixture = {appDetail: {id: 'app-1',name: 'Workflow App',@@ -110,6 +127,25 @@ describe('useDSLByCanEdit', () => {mockFetchEnvironmentVariables.mockResolvedValue({ items: [] })})+ it('exports with the latest name from the detail query', async () => {+ const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })+ const beforeRename = result.current+ act(() => {+ queryClient.setQueryData(+ consoleQuery.apps.byAppId.get.queryKey({ input: { params: { app_id: 'app-1' } } }),+ createAppDetailFixture({ name: 'Renamed workflow' }),+ )+ })+ await waitFor(() => expect(result.current).not.toBe(beforeRename))+ await act(async () => {+ await result.current.handleExportDSL()+ })+ expect(mockDownloadBlob).toHaveBeenCalledWith({+ data: expect.any(Blob),+ fileName: 'Renamed workflow.yml',+ })+ })+it('does not export a stale draft after synchronization reports a failure', async () => {mockDoSyncWorkflowDraft.mockImplementation(async (_options, callback) => {callback.onError()@@ -244,7 +280,7 @@ workflow:})it('should return early when app detail is unavailable', async () => {- appStoreState = {}+ appQueryFixture = {}const { result } = renderHook(() => useDSLByCanEdit(true), { wrapper })diff --git a/web/app/components/workflow-app/hooks/use-DSL.ts b/web/app/components/workflow-app/hooks/use-DSL.tsindex 54aff9eb96b..3d4ddcb2e67 100644--- a/web/app/components/workflow-app/hooks/use-DSL.ts+++ b/web/app/components/workflow-app/hooks/use-DSL.ts@@ -1,15 +1,15 @@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 { useMutation, useQuery } from '@tanstack/react-query'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'-import { useStore as useAppStore } from '@/app/components/app/store'import { getAppTransferErrorMessage } from '@/app/components/app/transfer-error'import { exportAppDslFile } from '@/app/components/app/use-export-app-dsl'import { DSL_EXPORT_CHECK } from '@/app/components/workflow/constants'import { toast } from '@/app/notifications'import { useEventEmitterContextContext } from '@/context/event-emitter'-import { consoleClient } from '@/service/console'+import { useParams } from '@/next/navigation'+import { consoleClient, consoleQuery } from '@/service/console'import { useNodesSyncDraftByCanEdit } from './use-nodes-sync-draft'type DoSyncWorkflowDraft = ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']@@ -18,7 +18,12 @@ const useDSLBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {const { t } = useTranslation(['app'])const { eventEmitter } = useEventEmitterContextContext()- const appDetail = useAppStore((s) => s.appDetail)+ const { appId } = useParams<{ appId: string }>()+ const { data: appDetail } = useQuery(+ consoleQuery.apps.byAppId.get.queryOptions({+ input: { params: { app_id: appId } },+ }),+ )const { mutateAsync: exportWorkflow, isPending: isExporting } = useMutation({mutationFn: async ({ include, workflowId }: { include: boolean; workflowId?: string }) => {diff --git a/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx b/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsxindex 1cf0038673e..34a474e724b 100644--- a/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx+++ b/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx@@ -70,16 +70,6 @@ vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({}),}))-vi.mock('@/app/components/app/store', () => ({- useStore: (selector: (state: { appDetail: { id: string; mode: string } }) => unknown) =>- selector({- appDetail: {- id: 'app-1',- mode: 'chat',- },- }),-}))-vi.mock('@/app/components/app/create-from-dsl-modal/uploader', () => ({Uploader: ({ updateFile }: { updateFile: (file?: File) => void }) => (<input@@ -98,6 +88,8 @@ function render(children: ReactNode) {describe('UpdateDSLModal', () => {const mockToastError = vi.mocked(toast.error)const defaultProps = {+ appId: 'app-1',+ appMode: 'workflow' as const,onCancel: vi.fn(),onBackup: vi.fn(),onImport: vi.fn(),diff --git a/web/app/components/workflow/update-dsl-modal.tsx b/web/app/components/workflow/update-dsl-modal.tsxindex bc420c793dc..e659fe181ed 100644--- a/web/app/components/workflow/update-dsl-modal.tsx+++ b/web/app/components/workflow/update-dsl-modal.tsx@@ -1,6 +1,6 @@'use client'-import type { Import } from '@dify/contracts/api/console/apps/types.gen'+import type { AppDetailWithSite, Import } from '@dify/contracts/api/console/apps/types.gen'import type { MouseEventHandler } from 'react'import { Button } from '@langgenius/dify-ui/button'import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'@@ -10,7 +10,6 @@ import { memo, useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import DSLImportWarningDescription from '@/app/components/app/create-from-dsl-modal/dsl-import-warning-description'import { Uploader } from '@/app/components/app/create-from-dsl-modal/uploader'-import { useStore as useAppStore } from '@/app/components/app/store'import { getAppTransferErrorMessage } from '@/app/components/app/transfer-error'import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'import { toast } from '@/app/notifications'@@ -29,14 +28,15 @@ import {import { initialEdges, initialNodes } from './utils'type UpdateDSLModalProps = {+ appId: string+ appMode: AppDetailWithSite['mode']onCancel: () => voidonBackup: () => voidonImport?: () => void}-const UpdateDSLModal = ({ onCancel, onBackup, onImport }: UpdateDSLModalProps) => {+const UpdateDSLModal = ({ appId, appMode, onCancel, onBackup, onImport }: UpdateDSLModalProps) => {const { t } = useTranslation(['workflow', 'app', 'common'])- const appDetail = useAppStore((s) => s.appDetail)const [currentFile, setCurrentFile] = useState<File>()const { eventEmitter } = useEventEmitterContextContext()const { handleCheckPluginDependencies } = usePluginDependencies()@@ -139,12 +139,11 @@ const UpdateDSLModal = ({ onCancel, onBackup, onImport }: UpdateDSLModalProps) =)const importMutation = useMutation({mutationFn: async (file: File) => {- if (!appDetail) returnif (file.name.toLowerCase().endsWith('.ifpkg'))- return requestImport({ body: { file, app_id: appDetail.id } })+ return requestImport({ body: { file, app_id: appId } })const content = await file.text()- if (!content || !validateDSLContent(content, appDetail.mode)) {+ if (!content || !validateDSLContent(content, appMode)) {toast.error(t(($) => $['common.importFailure'], { ns: 'workflow' }))return}@@ -152,7 +151,7 @@ const UpdateDSLModal = ({ onCancel, onBackup, onImport }: UpdateDSLModalProps) =body: {mode: DSLImportMode.YAML_CONTENT,yaml_content: content,- app_id: appDetail.id,+ app_id: appId,},})},@@ -174,7 +173,7 @@ const UpdateDSLModal = ({ onCancel, onBackup, onImport }: UpdateDSLModalProps) =const isImporting = importMutation.isPending || confirmImportMutation.isPendingconst handleImport: MouseEventHandler = () => {- if (isImporting || !currentFile || !appDetail) return+ if (isImporting || !currentFile) returnimportMutation.mutate(currentFile)}@@ -253,7 +252,7 @@ const UpdateDSLModal = ({ onCancel, onBackup, onImport }: UpdateDSLModalProps) ={t(($) => $['newApp.Cancel'], { ns: 'app' })}</Button><Button- disabled={isImporting || !currentFile || !appDetail}+ disabled={isImporting || !currentFile}variant="primary"tone="destructive"onClick={handleImport}