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(explore): migrate catalog consumers to generated queries (#42702)
yyh67ab35611695
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 368f2d60b24..b9320bb8dde 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -476,11 +476,6 @@"count": 2}},- "web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx": {- "dify/require-disable-directive-description": {- "count": 1- }- },"web/app/components/app/create-app-dialog/app-list/sidebar.tsx": {"react/only-export-components": {"count": 1@@ -4989,11 +4984,6 @@"count": 1}},- "web/service/use-explore.ts": {- "@tanstack/query/prefer-query-options": {- "count": 2- }- },"web/service/use-flow.ts": {"eslint-react/no-unnecessary-use-prefix": {"count": 1diff --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 99611185136..e2b559d17fc 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@@ -1,6 +1,5 @@+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import type { ReactElement } from 'react'-import type { App } from '@/models/explore'-import type { AppIconType } from '@/types/app'import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { trackEvent } from '@/app/components/base/amplitude'@@ -14,18 +13,16 @@ vi.mock('@/app/components/base/amplitude', () => ({ trackEvent: vi.fn() }))const render = (ui: ReactElement) =>renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: 'CLOUD' } })-const app: App = {+const app = {can_trial: true,app: {id: 'app-1',mode: AppModeEnum.CHAT,- icon_type: 'emoji' as AppIconType,+ icon_type: 'emoji',icon: '🤖',icon_background: '#FFEAD5',icon_url: '',name: 'Chat template',- description: 'Template description',- use_icon_as_answer_icon: false,},app_id: 'app-1',description: 'Template description',@@ -35,11 +32,7 @@ const app: App = {categories: ['Assistant'],position: 1,is_listed: true,- install_count: 100,- installed: false,- editable: true,- is_agent: false,-}+} satisfies RecommendedAppResponsedescribe('AppCard', () => {beforeEach(() => {@@ -56,8 +49,9 @@ describe('AppCard', () => {it('creates the template from the primary action', async () => {const onCreate = vi.fn()+ const user = userEvent.setup()render(<AppCard app={app} canCreate onCreate={onCreate} />)- await userEvent.click(screen.getByRole('button', { name: 'app.newApp.useTemplate' }))+ await user.click(screen.getByRole('button', { name: 'app.newApp.useTemplate' }))expect(onCreate).toHaveBeenCalledOnce()})@@ -85,8 +79,9 @@ describe('AppCard', () => {it('tracks and opens template preview in Cloud edition', async () => {const openPreview = vi.fn()+ const user = userEvent.setup()render(- // oxlint-disable-next-line eslint-react/no-context-provider+ // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector requires its Provider API.<AppListContext.Providervalue={{openTryAppPanel: openPreview,@@ -96,12 +91,43 @@ describe('AppCard', () => {</AppListContext.Provider>,)- await userEvent.click(screen.getByRole('button', { name: 'explore.appCard.try' }))+ await user.click(screen.getByRole('button', { name: 'explore.appCard.try' }))expect(trackEvent).toHaveBeenCalledWith('preview_template',expect.objectContaining({ template_id: 'app-1', page: 'studio' }),)- expect(openPreview).toHaveBeenCalledWith({ appId: 'app-1', app })+ expect(openPreview).toHaveBeenCalledWith(app)+ })++ it('allows creation and preview with nullable metadata without normalizing the selection', async () => {+ const nullableApp: RecommendedAppResponse = {+ app_id: 'nullable-app',+ app: null,+ can_trial: false,+ description: null,+ }+ const onCreate = vi.fn()+ const openPreview = vi.fn()+ const user = userEvent.setup()+ render(+ // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector requires its Provider API.+ <AppListContext.Provider value={{ openTryAppPanel: openPreview }}>+ <AppCard app={nullableApp} canCreate onCreate={onCreate} />+ </AppListContext.Provider>,+ )++ await user.click(screen.getByRole('button', { name: 'app.newApp.useTemplate' }))+ expect(onCreate).toHaveBeenCalledOnce()+ await user.click(screen.getByRole('button', { name: 'explore.appCard.try' }))++ expect(openPreview).toHaveBeenCalledWith(nullableApp)+ expect(trackEvent).toHaveBeenCalledWith('preview_template', {+ template_id: 'nullable-app',+ template_name: '',+ template_mode: '',+ template_categories: [],+ page: 'studio',+ })})})diff --git a/web/app/components/app/create-app-dialog/app-card/index.tsx b/web/app/components/app/create-app-dialog/app-card/index.tsxindex 5d14269d72e..8a43d58bdf7 100644--- a/web/app/components/app/create-app-dialog/app-card/index.tsx+++ b/web/app/components/app/create-app-dialog/app-card/index.tsx@@ -1,5 +1,5 @@'use client'-import type { App } from '@/models/explore'+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import { PlusIcon } from '@heroicons/react/20/solid'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'@@ -15,7 +15,7 @@ import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { AppTypeIcon, AppTypeLabel } from '../../type-selector'type AppCardProps = {- app: App+ app: RecommendedAppResponsecanCreate: booleanonCreate: () => void}@@ -27,18 +27,26 @@ const AppCard = ({ app, canCreate, onCreate }: AppCardProps) => {select: ({ deployment_edition }) => deployment_edition,})const { app: appBasicInfo } = app+ const appName = appBasicInfo?.name ?? ''+ const appMode = appBasicInfo?.mode ?? ''+ const appIconType =+ appBasicInfo?.icon_type === 'image' ||+ appBasicInfo?.icon_type === 'emoji' ||+ appBasicInfo?.icon_type === 'link'+ ? appBasicInfo.icon_type+ : nullconst canViewApp = deploymentEdition === 'CLOUD'const openTryAppPanel = useContextSelector(AppListContext, (ctx) => ctx.openTryAppPanel)const handleShowTryAppPanel = useCallback(() => {trackEvent('preview_template', {template_id: app.app_id,- template_name: appBasicInfo.name,- template_mode: appBasicInfo.mode,- template_categories: app.categories,+ template_name: appName,+ template_mode: appMode,+ template_categories: app.categories ?? [],page: 'studio',})- openTryAppPanel({ appId: app.app_id, app })- }, [openTryAppPanel, app, appBasicInfo])+ openTryAppPanel(app)+ }, [openTryAppPanel, app, appName, appMode])return (<divclassName={cn(@@ -49,27 +57,24 @@ const AppCard = ({ app, canCreate, onCreate }: AppCardProps) => {<div className="relative shrink-0"><AppIconsize="large"- iconType={appBasicInfo.icon_type}- icon={appBasicInfo.icon}- background={appBasicInfo.icon_background}- imageUrl={appBasicInfo.icon_url}+ iconType={appIconType}+ icon={appBasicInfo?.icon ?? ''}+ background={appBasicInfo?.icon_background ?? ''}+ imageUrl={appBasicInfo?.icon_url ?? ''}/><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={appBasicInfo.mode}+ type={appMode}/></div><div className="flex grow flex-col gap-1"><div className="line-clamp-1">- <span className="system-md-semibold text-text-secondary" title={appBasicInfo.name}>- {appBasicInfo.name}+ <span className="system-md-semibold text-text-secondary" title={appName}>+ {appName}</span></div>- <AppTypeLabel- className="system-2xs-medium-uppercase text-text-tertiary"- type={app.app.mode}- />+ <AppTypeLabel className="system-2xs-medium-uppercase text-text-tertiary" type={appMode} /></div></div><div className="py-1 system-xs-regular text-text-tertiary">diff --git a/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx b/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsxindex 4ebf8d9aaaa..8c125d076f1 100644--- a/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx+++ b/web/app/components/app/create-app-dialog/app-list/__tests__/index.spec.tsx@@ -1,530 +1,241 @@-import { fireEvent, screen, waitFor } from '@testing-library/react'+import type { Import } from '@dify/contracts/api/console/apps/types.gen'+import type {+ GetExploreAppsResponse,+ RecommendedAppDetailResponse,+ RecommendedAppResponse,+} from '@dify/contracts/api/console/explore/types.gen'+import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { renderWithConsoleQuery as render } from '@/test/console/query-data'-import { AppModeEnum } from '@/types/app'+import { consoleQuery } from '@/service/console'+import {+ createConsoleQueryClient,+ renderWithConsoleQuery as render,+} from '@/test/console/query-data'import Apps from '../index'-const mockUseExploreAppList = vi.fn()-const mockImportDSL = vi.hoisted(() => vi.fn())-const mockFetchAppDetail = vi.fn()-const mockHandleCheckPluginDependencies = vi.fn()-const mockGetRedirection = vi.fn()-const mockPush = vi.fn()-const mockToastSuccess = vi.fn()-const mockToastError = vi.fn()-const mockTrackCreateApp = vi.fn()-let mockWorkspacePermissionKeys: string[] = ['app.create_and_management']-const mockUserProfile = { id: 'user-1' }--vi.mock('@/context/permission-state', async () => {- const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')- return createPermissionStateModuleMock(() => ({- userProfile: mockUserProfile,- workspacePermissionKeys: mockWorkspacePermissionKeys,- }))-})--vi.mock('nuqs', () => ({- useQueryState: () => ['Recommended', vi.fn()],-}))-vi.mock('@/service/use-explore', () => ({- useExploreAppList: () => mockUseExploreAppList(),-}))-vi.mock('@/app/components/app/type-selector', () => ({- default: ({- value,- onChange,- }: {- value: AppModeEnum[]- onChange: (value: AppModeEnum[]) => void- }) => (- <div>- <button data-testid="type-selector-chat" onClick={() => onChange([AppModeEnum.CHAT])}>- {value.join(',')}- </button>- <button- data-testid="type-selector-advanced"- onClick={() => onChange([AppModeEnum.ADVANCED_CHAT])}- >- advanced- </button>- <button data-testid="type-selector-agent" onClick={() => onChange([AppModeEnum.AGENT_CHAT])}>- agent- </button>- <button- data-testid="type-selector-completion"- onClick={() => onChange([AppModeEnum.COMPLETION])}- >- completion- </button>- <button data-testid="type-selector-workflow" onClick={() => onChange([AppModeEnum.WORKFLOW])}>- workflow- </button>- </div>- ),-}))-vi.mock('../../app-card', () => ({- default: ({- app,- canCreate,- onCreate,- }: {- app: { app: { name: string } }- canCreate: boolean- onCreate: () => void- }) => (- <button- type="button"- data-testid="app-card"- data-name={app.app.name}- data-can-create={canCreate ? 'true' : 'false'}- onClick={onCreate}- >- {app.app.name}- </button>- ),-}))-vi.mock('@/app/components/explore/create-app-modal', () => ({- default: ({- onConfirm,- onHide,- show,- }: {- onConfirm: (payload: {- name: string- icon_type: string- icon: string- icon_background: string- description: string- }) => Promise<void>- onHide: () => void- show: boolean- }) =>- show ? (- <div data-testid="create-from-template-modal">- <button- data-testid="confirm-create"- onClick={() =>- onConfirm({- name: 'Created App',- icon_type: 'emoji',- icon: '🙂',- icon_background: '#fff',- description: 'created from template',- })- }- >- confirm-create- </button>- <button data-testid="hide-create-modal" onClick={onHide}>- hide-create-modal- </button>- </div>- ) : null,-}))-vi.mock('@/app/notifications', () => ({- toast: {- success: (...args: unknown[]) => mockToastSuccess(...args),- error: (...args: unknown[]) => mockToastError(...args),- },-}))-vi.mock('@/utils/create-app-tracking', () => ({- trackCreateApp: (...args: unknown[]) => mockTrackCreateApp(...args),-}))-vi.mock('@/service/console', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/service/console')>()-- return {- ...actual,- consoleQuery: {- ...actual.consoleQuery,- account: {- profile: {- get: {- queryKey: () => [['console', 'account', 'profile', 'get'], { type: 'query' }],- },- },- },- systemFeatures: actual.consoleQuery.systemFeatures,- apps: {- ...actual.consoleQuery.apps,- imports: {- ...actual.consoleQuery.apps.imports,- post: {- mutationOptions: () => ({- mutationFn: ({ body }: { body: Record<string, unknown> }) => mockImportDSL(body),- }),- },- },- },- },- }-})-vi.mock('@/service/explore', () => ({- fetchAppDetail: (...args: unknown[]) => mockFetchAppDetail(...args),-}))-vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({- usePluginDependencies: () => ({- handleCheckPluginDependencies: (...args: unknown[]) =>- mockHandleCheckPluginDependencies(...args),+const { request, locale, toast, checkDependencies, redirect, trackCreateApp, push } = vi.hoisted(+ () => ({+ request: vi.fn(),+ locale: { value: 'en-US' },+ toast: { success: vi.fn(), error: vi.fn() },+ checkDependencies: vi.fn(),+ redirect: vi.fn(),+ trackCreateApp: vi.fn(),+ push: vi.fn(),}),+)+vi.mock('@/service/base', () => ({ request }))+vi.mock('#i18n', async (importOriginal) => ({+ ...(await importOriginal<typeof import('#i18n')>()),+ useLocale: () => locale.value,}))-vi.mock('@/utils/app-redirection', () => ({- getRedirection: (...args: unknown[]) => mockGetRedirection(...args),-}))-vi.mock('@/next/navigation', () => ({- useRouter: () => ({ push: mockPush }),+vi.mock('@/app/notifications', () => ({ toast }))+vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({+ usePluginDependencies: () => ({ handleCheckPluginDependencies: checkDependencies }),}))--const createAppEntry = (name: string, category: string) => ({- app_id: name,- categories: [category],+vi.mock('@/utils/app-redirection', () => ({ getRedirection: redirect }))+vi.mock('@/utils/create-app-tracking', () => ({ trackCreateApp }))+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push }), useParams: () => ({}) }))++const createEntry = (+ name: string,+ position: number | null,+ mode = 'chat',+ category = 'Assistant',+): RecommendedAppResponse => ({+ app_id: `catalog-${name}`,app: {- id: name,+ id: `nested-${name}`,name,+ mode,icon_type: 'emoji',icon: '🙂',- icon_background: '#000',+ icon_background: '#fff',icon_url: null,- description: 'desc',- mode: AppModeEnum.CHAT,},+ can_trial: false,+ categories: [category],+ description: 'Catalog description',+ position,})--describe('Apps', () => {- const defaultData = {- allList: [- createAppEntry('Alpha', 'Cat A'),- createAppEntry('Bravo', 'Cat B'),- {- ...createAppEntry('Charlie', 'Cat B'),- app: {- ...createAppEntry('Charlie', 'Cat B').app,- mode: AppModeEnum.COMPLETION,- },- },- {- ...createAppEntry('Delta', 'Cat A'),- app: {- ...createAppEntry('Delta', 'Cat A').app,- mode: AppModeEnum.ADVANCED_CHAT,- },- },- {- ...createAppEntry('Echo', 'Cat C'),- app: {- ...createAppEntry('Echo', 'Cat C').app,- mode: AppModeEnum.AGENT_CHAT,- },- },- {- ...createAppEntry('Foxtrot', 'Cat C'),- app: {- ...createAppEntry('Foxtrot', 'Cat C').app,- mode: AppModeEnum.WORKFLOW,- },- },- ],- categories: ['Cat A', 'Cat B', 'Cat C'],- }-- beforeEach(() => {- vi.clearAllMocks()- mockWorkspacePermissionKeys = ['app.create_and_management']- mockUseExploreAppList.mockReturnValue({- data: defaultData,- isLoading: false,- })- mockFetchAppDetail.mockResolvedValue({- export_data: 'dsl',- mode: AppModeEnum.CHAT,- })- mockImportDSL.mockResolvedValue({- app_id: 'created-app-id',- app_mode: AppModeEnum.CHAT,- permission_keys: ['app.acl.view_layout'],- })- })-- it('renders template cards when data is available', () => {- render(<Apps onClose={vi.fn()} />)-- expect(screen.getAllByTestId('app-card')).toHaveLength(6)- expect(screen.getByText('Alpha'))!.toBeInTheDocument()- expect(screen.getByText('Bravo'))!.toBeInTheDocument()- })-- it('opens create modal when a template card is clicked', () => {- render(<Apps onClose={vi.fn()} />)-- fireEvent.click(screen.getAllByTestId('app-card')[0]!)- expect(screen.getByTestId('create-from-template-modal'))!.toBeInTheDocument()- })-- it('passes app.create_and_management permission to template cards even when user is not a workspace editor', () => {- mockWorkspacePermissionKeys = ['app.create_and_management']-- render(<Apps onClose={vi.fn()} />)-- expect(screen.getAllByTestId('app-card')[0]).toHaveAttribute('data-can-create', 'true')+const catalog: GetExploreAppsResponse = {+ recommended_apps: [+ createEntry('Bravo', 2, 'completion', 'Writing'),+ createEntry('Alpha', null),+ createEntry('Charlie', 1, 'workflow'),+ ],+ categories: ['Writing', 'Empty', 'Assistant'],+}+const detail: RecommendedAppDetailResponse = {+ id: 'catalog-Alpha',+ name: 'Alpha',+ mode: 'chat',+ can_trial: false,+ export_data: 'fresh-dsl',+}+const imported: Import = {+ id: 'import-1',+ status: 'completed',+ app_id: 'created-app',+ app_mode: 'chat',+ permission_keys: ['app.edit'],+}+const catalogKey = (language: string) =>+ consoleQuery.explore.apps.get.queryKey({ input: { query: { language } } })++beforeEach(() => {+ vi.clearAllMocks()+ locale.value = 'en-US'+ request.mockImplementation(async (url: string) => {+ const path = new URL(url).pathname.replace('/console/api', '') + new URL(url).search+ if (path.startsWith('/explore/apps?')) return Response.json(catalog)+ if (path === '/explore/apps/catalog-Alpha') return Response.json(detail)+ if (path === '/apps/imports') return Response.json(imported)+ throw new Error(`Unexpected request: ${url}`)})+})+const renderApps = (response = catalog, permissions = ['app.create_and_management']) => {+ const queryClient = createConsoleQueryClient()+ queryClient.setQueryData(catalogKey('en-US'), response)+ const onClose = vi.fn()+ return {+ ...render(<Apps onClose={onClose} />, { queryClient, workspacePermissionKeys: permissions }),+ onClose,+ }+}+const openFirst = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.click(screen.getAllByRole('button', { name: 'app.newApp.useTemplate' })[0]!)+ return screen.findByRole('dialog')+}++it('reuses the prewarmed canonical locale cache and sorts only the consumer view', () => {+ const { queryClient } = renderApps()+ expect(screen.getAllByTitle(/Alpha|Bravo|Charlie/).map((element) => element.textContent)).toEqual(+ ['Alpha', 'Charlie', 'Bravo'],+ )+ expect(screen.queryByRole('button', { name: 'Empty' })).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Writing' })).toBeInTheDocument()+ expect(request).not.toHaveBeenCalled()+ expect(queryClient.getQueryData(catalogKey('en-US'))).toEqual(catalog)+ expect(catalog.recommended_apps.map((app) => app.app_id)).toEqual([+ 'catalog-Bravo',+ 'catalog-Alpha',+ 'catalog-Charlie',+ ])+})- it('does not allow template creation when app.create_and_management permission is missing', () => {- mockWorkspacePermissionKeys = []-- render(<Apps onClose={vi.fn()} />)-- expect(screen.getAllByTestId('app-card')[0]).toHaveAttribute('data-can-create', 'false')- })-- it('shows no template message when list is empty', () => {- mockUseExploreAppList.mockReturnValueOnce({- data: { allList: [], categories: [] },- isLoading: false,- })-- render(<Apps onClose={vi.fn()} />)-- expect(screen.getByText('app.newApp.noTemplateFound'))!.toBeInTheDocument()- expect(screen.getByText('app.newApp.noTemplateFoundTip'))!.toBeInTheDocument()- })-- it('filters templates by keyword and selected app type', async () => {- render(<Apps onClose={vi.fn()} />)-- fireEvent.change(screen.getByPlaceholderText('app.newAppFromTemplate.searchAllTemplate'), {- target: { value: 'Bravo' },- })-- await waitFor(() => {- expect(screen.getByText('Bravo'))!.toBeInTheDocument()- expect(screen.queryByText('Alpha')).not.toBeInTheDocument()- })-- fireEvent.change(screen.getByPlaceholderText('app.newAppFromTemplate.searchAllTemplate'), {- target: { value: '' },- })- fireEvent.click(screen.getByTestId('type-selector-chat'))-- await waitFor(() => {- expect(screen.getByText('Alpha'))!.toBeInTheDocument()- expect(screen.getByText('Bravo'))!.toBeInTheDocument()- expect(screen.queryByText('Charlie')).not.toBeInTheDocument()- })- })-- it('creates an app from a template and redirects after import succeeds', async () => {- const onClose = vi.fn()-- render(<Apps onClose={onClose} />)-- fireEvent.click(screen.getAllByTestId('app-card')[0]!)- fireEvent.click(screen.getByTestId('confirm-create'))-- await waitFor(() => {- expect(mockFetchAppDetail).toHaveBeenCalledWith('Alpha')- expect(mockImportDSL).toHaveBeenCalledWith(- expect.objectContaining({- yaml_content: 'dsl',- name: 'Created App',- }),- )- })-- expect(mockTrackCreateApp).toHaveBeenCalledWith({- source: 'studio_template_list',- appMode: AppModeEnum.CHAT,- templateId: 'Alpha',- })- expect(mockToastSuccess).toHaveBeenCalledWith('app.newApp.appCreated')- expect(onClose).toHaveBeenCalledTimes(1)- expect(mockHandleCheckPluginDependencies).toHaveBeenCalledWith('created-app-id')- expect(mockGetRedirection).toHaveBeenCalledWith(- {- id: 'created-app-id',- mode: AppModeEnum.CHAT,- permission_keys: ['app.acl.view_layout'],- },- mockPush,- {- currentUserId: 'user-1',- resourceMaintainer: 'user-1',- workspacePermissionKeys: ['app.create_and_management'],- isRbacEnabled: false,- },- )- })-- it('passes creator context when template import response has no permission keys', async () => {- mockImportDSL.mockResolvedValueOnce({- app_id: 'created-without-permissions',- app_mode: AppModeEnum.WORKFLOW,- })-- render(<Apps onClose={vi.fn()} />)-- fireEvent.click(screen.getAllByTestId('app-card')[0]!)- fireEvent.click(screen.getByTestId('confirm-create'))-- await waitFor(() => {- expect(mockGetRedirection).toHaveBeenCalledWith(- {- id: 'created-without-permissions',- mode: AppModeEnum.WORKFLOW,- permission_keys: undefined,- },- mockPush,- {- currentUserId: 'user-1',- resourceMaintainer: 'user-1',- workspacePermissionKeys: ['app.create_and_management'],- isRbacEnabled: false,- },- )- })- })-- it('shows an error toast when importing the template fails', async () => {- mockImportDSL.mockRejectedValueOnce(new Error('failed'))-- render(<Apps onClose={vi.fn()} />)-- fireEvent.click(screen.getAllByTestId('app-card')[0]!)- fireEvent.click(screen.getByTestId('confirm-create'))-- await waitFor(() => {- expect(mockToastError).toHaveBeenCalledWith('app.newApp.appCreateFailed')- })- })-- it('forwards the create-from-blank action from the sidebar', () => {- const onCreateFromBlank = vi.fn()-- render(<Apps onClose={vi.fn()} onCreateFromBlank={onCreateFromBlank} />)-- fireEvent.click(screen.getByText('app.newApp.startFromBlank'))-- expect(onCreateFromBlank).toHaveBeenCalled()- })-- it('should render the loading state while templates are being fetched', () => {- mockUseExploreAppList.mockReturnValueOnce({- data: undefined,- isLoading: true,- })-- render(<Apps onClose={vi.fn()} />)-- expect(screen.getByRole('progressbar'))!.toBeInTheDocument()- })-- it('should handle an undefined template payload by falling back to the empty state', () => {- mockUseExploreAppList.mockReturnValueOnce({- data: undefined,- isLoading: false,- })-- render(<Apps onClose={vi.fn()} />)-- expect(screen.getByText('app.newApp.noTemplateFound'))!.toBeInTheDocument()- })-- it('should filter templates by category and the remaining app modes', async () => {- render(<Apps onClose={vi.fn()} />)-- fireEvent.click(screen.getByText('Cat C'))- expect(screen.queryByText('Alpha')).not.toBeInTheDocument()- expect(screen.getByText('Echo'))!.toBeInTheDocument()- expect(screen.getByText('Foxtrot'))!.toBeInTheDocument()-- fireEvent.click(screen.getByTestId('type-selector-advanced'))- await waitFor(() => {- expect(screen.queryByText('Echo')).not.toBeInTheDocument()- expect(screen.queryByText('Foxtrot')).not.toBeInTheDocument()- })-- fireEvent.click(screen.getByText('app.newApp.startFromBlank'))- fireEvent.click(screen.getByText('Cat C'))- fireEvent.click(screen.getByTestId('type-selector-agent'))- await waitFor(() => {- expect(screen.getByText('Echo'))!.toBeInTheDocument()- expect(screen.queryByText('Foxtrot')).not.toBeInTheDocument()- })-- fireEvent.click(screen.getByTestId('type-selector-workflow'))- await waitFor(() => {- expect(screen.getByText('Foxtrot'))!.toBeInTheDocument()- expect(screen.queryByText('Echo')).not.toBeInTheDocument()- })-- fireEvent.click(screen.getByTestId('type-selector-completion'))- await waitFor(() => {- expect(screen.queryByText('Foxtrot')).not.toBeInTheDocument()- expect(screen.queryByText('Echo')).not.toBeInTheDocument()- })- })-- it('should hide categories without templates even when the API returns them', () => {- mockUseExploreAppList.mockReturnValueOnce({- data: {- categories: ['Cat A', 'v'],- allList: [createAppEntry('Alpha', 'Cat A')],- },- isLoading: false,- })-- render(<Apps onClose={vi.fn()} />)-- expect(screen.getByText('Cat A'))!.toBeInTheDocument()- expect(screen.queryByRole('button', { name: 'v' })).not.toBeInTheDocument()- expect(screen.getByText('Alpha'))!.toBeInTheDocument()- })-- it('should clear the search, hide the sidebar during search, and close the modal when requested', async () => {- render(<Apps onClose={vi.fn()} />)-- const searchInput = screen.getByPlaceholderText('app.newAppFromTemplate.searchAllTemplate')- fireEvent.change(searchInput, {- target: { value: 'Alpha' },- })-- await waitFor(() => {- expect(screen.queryByText('Cat A')).not.toBeInTheDocument()- })-- fireEvent.change(searchInput, {- target: { value: '' },- })-- await waitFor(() => {- expect(screen.getByText('Cat A'))!.toBeInTheDocument()- })-- fireEvent.click(screen.getAllByTestId('app-card')[0]!)- expect(screen.getByTestId('create-from-template-modal'))!.toBeInTheDocument()-- fireEvent.click(screen.getByTestId('hide-create-modal'))+it('requests a separate locale and falls back from a category absent in the new catalog', async () => {+ const user = userEvent.setup()+ const chinese: GetExploreAppsResponse = {+ recommended_apps: [createEntry('中文', 0)],+ categories: ['Assistant'],+ }+ request.mockImplementation(async () => Response.json(chinese))+ const { rerender, queryClient } = renderApps()+ await user.click(screen.getByRole('button', { name: 'Writing' }))+ expect(screen.queryByTitle('Alpha')).not.toBeInTheDocument()+ locale.value = 'zh-Hans'+ rerender(<Apps onClose={vi.fn()} />)+ await screen.findByTitle('中文')+ expect(request).toHaveBeenCalledTimes(1)+ expect(new URL(request.mock.calls[0]![0]).searchParams.get('language')).toBe('zh-Hans')+ expect(queryClient.getQueryData(catalogKey('en-US'))).toEqual(catalog)+ expect(queryClient.getQueryData(catalogKey('zh-Hans'))).toEqual(chinese)+})- expect(screen.queryByTestId('create-from-template-modal')).not.toBeInTheDocument()- })+it('combines real type selection with debounced case-insensitive search and restores focus on clear', async () => {+ const user = userEvent.setup()+ renderApps()+ await user.click(screen.getByRole('button', { name: 'app.typeSelector.all' }))+ await user.click(screen.getByRole('button', { name: 'app.typeSelector.chatbot' }))+ await user.keyboard('{Escape}')+ expect(screen.getByTitle('Alpha')).toBeInTheDocument()+ expect(screen.queryByTitle('Bravo')).not.toBeInTheDocument()+ const search = screen.getByRole('searchbox')+ await user.type(search, 'ALP')+ await waitFor(() =>+ expect(screen.queryByRole('button', { name: 'Assistant' })).not.toBeInTheDocument(),+ )+ expect(screen.getByTitle('Alpha')).toBeInTheDocument()+ await user.click(screen.getAllByRole('button', { name: 'common.operation.clear' })[1]!)+ expect(search).toHaveFocus()+ expect(search).toHaveValue('')+ expect(screen.getByRole('button', { name: 'Assistant' })).toBeInTheDocument()+})- it('clears an active search immediately and returns focus to the searchbox', async () => {- const user = userEvent.setup()- render(<Apps onClose={vi.fn()} />)+it('fetches fresh detail by canonical app_id and submits the actual form with an empty initial description', async () => {+ const user = userEvent.setup()+ const { queryClient, onClose } = renderApps()+ queryClient.setQueryData(+ consoleQuery.explore.apps.byAppId.get.queryKey({+ input: { params: { app_id: 'catalog-Alpha' } },+ }),+ { ...detail, export_data: 'stale-dsl' },+ )+ await openFirst(user)+ expect(screen.getByPlaceholderText('app.newApp.appDescriptionPlaceholder')).toHaveValue('')+ await user.clear(screen.getByPlaceholderText('app.newApp.appNamePlaceholder'))+ await user.type(screen.getByPlaceholderText('app.newApp.appNamePlaceholder'), 'My app')+ await user.click(screen.getByRole('button', { name: /common\.operation\.create/ }))+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce())+ expect(+ request.mock.calls.map(([url]) => new URL(url).pathname.replace('/console/api', '')),+ ).toEqual(['/explore/apps/catalog-Alpha', '/apps/imports'])+ expect(await request.mock.calls[1]![2].request.json()).toMatchObject({+ yaml_content: 'fresh-dsl',+ name: 'My app',+ description: '',+ })+ expect(trackCreateApp).toHaveBeenCalledWith({+ source: 'studio_template_list',+ templateId: 'catalog-Alpha',+ appMode: 'chat',+ })+ expect(checkDependencies).toHaveBeenCalledWith('created-app')+ expect(redirect).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'created-app', permission_keys: ['app.edit'] }),+ push,+ expect.any(Object),+ )+})- const searchInput = screen.getByRole('searchbox', {- name: 'app.newAppFromTemplate.searchAllTemplate',- })+it('closes the submitted modal immediately and reports detail failure without import or navigation', async () => {+ const user = userEvent.setup()+ let rejectDetail: ((reason: Error) => void) | undefined+ request.mockImplementation(+ () =>+ new Promise<Response>((_resolve, reject) => {+ rejectDetail = reject+ }),+ )+ const { onClose } = renderApps()+ await openFirst(user)+ await user.click(screen.getByRole('button', { name: /common\.operation\.create/ }))+ await waitFor(() => expect(request).toHaveBeenCalledOnce())+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ await act(async () => rejectDetail?.(new Error('Unavailable')))+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('app.newApp.appCreateFailed'))+ expect(request).toHaveBeenCalledOnce()+ expect(onClose).not.toHaveBeenCalled()+ expect(trackCreateApp).not.toHaveBeenCalled()+ expect(redirect).not.toHaveBeenCalled()+})- await user.type(searchInput, 'Alpha')- await waitFor(() => {- expect(screen.queryByText('Bravo')).not.toBeInTheDocument()- })- await user.click(screen.getByRole('button', { name: 'common.operation.clear' }))+it('supports nullable metadata without inventing a name and requires a name before importing', async () => {+ const user = userEvent.setup()+ renderApps({+ recommended_apps: [{ app_id: 'null-app', app: null, can_trial: false }],+ categories: [],+ })+ await openFirst(user)+ expect(screen.getByPlaceholderText('app.newApp.appNamePlaceholder')).toHaveValue('')+ expect(screen.getByRole('button', { name: /common\.operation\.create/ })).toBeDisabled()+ expect(request).not.toHaveBeenCalled()+ expect(screen.getByRole('dialog')).toBeInTheDocument()+})- expect(searchInput).toHaveValue('')- expect(searchInput).toHaveFocus()- expect(screen.getByText('Cat A')).toBeInTheDocument()- expect(screen.getAllByTestId('app-card')).toHaveLength(6)- })+it('does not expose creation actions without app management permission', () => {+ renderApps(catalog, [])+ expect(screen.getByTitle('Alpha')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'app.newApp.useTemplate' })).not.toBeInTheDocument()})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 61490d78b04..430a2d2f01d 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,17 +1,18 @@'use client'+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import type { CreateAppModalProps } from '@/app/components/explore/create-app-modal'-import type { App } from '@/models/explore'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'import { Separator } from '@langgenius/dify-ui/separator'-import { useMutation, useSuspenseQuery } from '@tanstack/react-query'+import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useDebouncedValue } from 'foxact/use-debounced-value'import { useAtomValue } from 'jotai'import * as React from 'react'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'+import { useLocale } from '#i18n'import AppTypeSelector from '@/app/components/app/type-selector'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import CreateAppModal from '@/app/components/explore/create-app-modal'@@ -21,9 +22,7 @@ import { workspacePermissionKeysAtom } from '@/context/permission-state'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 { fetchAppDetail } from '@/service/explore'-import { useExploreAppList } from '@/service/use-explore'+import { consoleClient, consoleQuery } from '@/service/console'import { AppModeEnum } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'import { trackCreateApp } from '@/utils/create-app-tracking'@@ -36,13 +35,9 @@ type AppsProps = {onCreateFromBlank?: () => void}-// export enum PageType {-// EXPLORE = 'explore',-// CREATE = 'create',-// }-const Apps = ({ onClose, onCreateFromBlank }: AppsProps) => {const { t } = useTranslation()+ const locale = useLocale()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())const { data: currentUserId } = useSuspenseQuery({...userProfileQueryOptions(),@@ -71,14 +66,22 @@ const Apps = ({ onClose, onCreateFromBlank }: AppsProps) => {const [currentType, setCurrentType] = useState<AppModeEnum[]>([])const [currCategory, setCurrCategory] = useState<AppCategories | string>(allCategoriesEn)- const { data, isLoading } = useExploreAppList()+ const { data, isLoading } = useQuery(+ consoleQuery.explore.apps.get.queryOptions({+ input: { query: { language: locale } },+ }),+ )+ const allList = useMemo(+ () => [...(data?.recommended_apps ?? [])].sort((a, b) => (a.position ?? 0) - (b.position ?? 0)),+ [data?.recommended_apps],+ )const visibleCategories = useMemo(() => {if (!data) return []const categoriesWithApps = new Set<string>()- data.allList.forEach((app) => {- app.categories.forEach((category) => categoriesWithApps.add(category))+ data.recommended_apps.forEach((app) => {+ app.categories?.forEach((category) => categoriesWithApps.add(category))})return data.categories.filter((category) => categoriesWithApps.has(category))@@ -88,28 +91,27 @@ const Apps = ({ onClose, onCreateFromBlank }: AppsProps) => {const filteredList = useMemo(() => {if (!data) return []- const { allList } = dataconst filteredByCategory = allList.filter((item) => {if (activeCategory === allCategoriesEn) return truereturn item.categories?.includes(activeCategory) ?? false})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.CHAT) && item.app?.mode === AppModeEnum.CHAT) return trueif (currentType.includes(AppModeEnum.ADVANCED_CHAT) &&- item.app.mode === AppModeEnum.ADVANCED_CHAT+ item.app?.mode === AppModeEnum.ADVANCED_CHAT)return true- if (currentType.includes(AppModeEnum.AGENT_CHAT) && item.app.mode === AppModeEnum.AGENT_CHAT)+ if (currentType.includes(AppModeEnum.AGENT_CHAT) && item.app?.mode === AppModeEnum.AGENT_CHAT)return true- if (currentType.includes(AppModeEnum.COMPLETION) && item.app.mode === AppModeEnum.COMPLETION)+ if (currentType.includes(AppModeEnum.COMPLETION) && item.app?.mode === AppModeEnum.COMPLETION)return true- if (currentType.includes(AppModeEnum.WORKFLOW) && item.app.mode === AppModeEnum.WORKFLOW)+ if (currentType.includes(AppModeEnum.WORKFLOW) && item.app?.mode === AppModeEnum.WORKFLOW)return truereturn false})- }, [currentType, activeCategory, allCategoriesEn, data])+ }, [currentType, activeCategory, allCategoriesEn, data, allList])const searchFilteredList = useMemo(() => {if (!searchKeywords || !filteredList || filteredList.length === 0) return filteredList@@ -122,7 +124,7 @@ const Apps = ({ onClose, onCreateFromBlank }: AppsProps) => {)}, [searchKeywords, filteredList])- const [currApp, setCurrApp] = React.useState<App | null>(null)+ const [currApp, setCurrApp] = React.useState<RecommendedAppResponse | null>(null)const [isShowCreateModal, setIsShowCreateModal] = React.useState(false)const { handleCheckPluginDependencies } = usePluginDependencies()const onCreate: CreateAppModalProps['onConfirm'] = async ({@@ -132,8 +134,11 @@ const Apps = ({ onClose, onCreateFromBlank }: AppsProps) => {icon_background,description,}) => {- const { export_data, mode } = await fetchAppDetail(currApp?.app.id as string)+ if (!currApp || !canCreateAppFromTemplate) returntry {+ const { export_data, mode } = await consoleClient.explore.apps.byAppId.get({+ params: { app_id: currApp.app_id },+ })const app = await importApp({body: {mode: 'yaml-content',@@ -147,7 +152,7 @@ const Apps = ({ onClose, onCreateFromBlank }: AppsProps) => {})if (!app.app_id || !app.app_mode) throw new Error('Completed import is missing app metadata')- trackCreateApp({ source: 'studio_template_list', appMode: mode, templateId: currApp?.app_id })+ trackCreateApp({ source: 'studio_template_list', appMode: mode, templateId: currApp.app_id })setIsShowCreateModal(false)toast.success(t(($) => $['newApp.appCreated'], { ns: 'app' }))@@ -222,7 +227,7 @@ const Apps = ({ onClose, onCreateFromBlank }: AppsProps) => {{!searchKeywords && (<div className="h-full w-50 p-4"><Sidebar- current={activeCategory as AppCategories}+ current={activeCategory}categories={visibleCategories}onClick={(category) => {setCurrCategory(category)@@ -250,7 +255,7 @@ const Apps = ({ onClose, onCreateFromBlank }: AppsProps) => {) : (<div className="flex h-5.5 items-center"><AppCategoryLabel- category={activeCategory as AppCategories}+ category={activeCategory}className="title-md-semi-bold text-text-primary"/></div>@@ -280,12 +285,16 @@ const Apps = ({ onClose, onCreateFromBlank }: AppsProps) => {</div>{isShowCreateModal && (<CreateAppModal- appIconType={currApp?.app.icon_type || 'emoji'}- appIcon={currApp?.app.icon || ''}- appIconBackground={currApp?.app.icon_background || ''}- appIconUrl={currApp?.app.icon_url}- appName={currApp?.app.name || ''}- appDescription={currApp?.app.description || ''}+ appIconType={+ currApp?.app?.icon_type === 'image' || currApp?.app?.icon_type === 'link'+ ? currApp.app.icon_type+ : 'emoji'+ }+ appIcon={currApp?.app?.icon ?? ''}+ appIconBackground={currApp?.app?.icon_background ?? ''}+ appIconUrl={currApp?.app?.icon_url}+ appName={currApp?.app?.name ?? ''}+ appDescription=""show={isShowCreateModal}onConfirm={onCreate}onHide={() => setIsShowCreateModal(false)}diff --git a/web/app/components/apps/__tests__/app-card.spec.tsx b/web/app/components/apps/__tests__/app-card.spec.tsxindex e164657fe1b..45a08d71293 100644--- a/web/app/components/apps/__tests__/app-card.spec.tsx+++ b/web/app/components/apps/__tests__/app-card.spec.tsx@@ -1,10 +1,10 @@import type { AppPartial } from '@dify/contracts/api/console/apps/types.gen'+import type { InstalledAppListResponse } from '@dify/contracts/api/console/installed-apps/types.gen'import { fireEvent, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'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 * as exploreService from '@/service/explore'import { renderWithConsoleQuery } from '@/test/console/query-data'import { AppModeEnum } from '@/types/app'import { AppACLPermission } from '@/utils/permission'@@ -190,8 +190,14 @@ vi.mock('@/service/apps', () => ({deleteApp: vi.fn(() => Promise.resolve()),}))-vi.mock('@/service/explore', () => ({- fetchInstalledAppList: vi.fn(() => Promise.resolve({ installed_apps: [{ id: 'installed-1' }] })),+const { installedRequest } = vi.hoisted(() => ({+ installedRequest:+ vi.fn<(url: string, init: RequestInit, options: { request: Request }) => Promise<Response>>(),+}))++vi.mock('@/service/base', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/service/base')>()),+ request: installedRequest,}))vi.mock('@/service/access-control', () => ({@@ -214,11 +220,13 @@ vi.mock('@/service/access-control/use-app-access-control', () => ({}),}))-// Mock hooks-const mockOpenAsyncWindow = vi.fn()-vi.mock('@/hooks/use-async-window-open', () => ({- useAsyncWindowOpen: () => mockOpenAsyncWindow,-}))+const popup: {+ location: { href: string }+ opener: Window | null+ close: ReturnType<typeof vi.fn>+} = { location: { href: '' }, opener: null, close: vi.fn() }+let installedApps: InstalledAppListResponse+const openWindow = vi.fn<() => typeof popup | null>()// Mock utilsconst { mockGetRedirection } = vi.hoisted(() => ({@@ -430,7 +438,34 @@ describe('AppCard', () => {beforeEach(() => {vi.clearAllMocks()- mockOpenAsyncWindow.mockReset()+ openWindow.mockReturnValue(popup)+ popup.location.href = ''+ popup.opener = window+ vi.stubGlobal('open', openWindow)+ installedApps = {+ has_more: false,+ next_cursor: null,+ installed_apps: ['installed-1', 'installed-2'].map((id) => ({+ id,+ app_owner_tenant_id: 'workspace-1',+ editable: false,+ is_pinned: false,+ last_used_at: null,+ uninstallable: true,+ app: {+ id: mockApp.id,+ name: mockApp.name,+ description: '',+ mode: 'chat',+ icon: null,+ icon_type: null,+ icon_background: null,+ icon_url: null,+ use_icon_as_answer_icon: false,+ },+ })),+ }+ installedRequest.mockResolvedValue(Response.json(installedApps))mockWebappAuthEnabled = falsemockRbacEnabled = truemockUserCanAccessApp.result = true@@ -449,6 +484,10 @@ describe('AppCard', () => {mockConsoleState.workspacePermissionKeys = ['app.create_and_management']})+ afterEach(() => {+ vi.unstubAllGlobals()+ })+describe('Rendering', () => {it('should render preview-only app card as a dimmed information-only card', () => {const previewOnlyApp = createMockApp({@@ -1439,46 +1478,39 @@ describe('AppCard', () => {})})- it('should handle open in explore via async window', async () => {- let openedUrl = ''- // Configure mockOpenAsyncWindow to actually call the callback- mockOpenAsyncWindow.mockImplementationOnce(async (callback: () => Promise<string>) => {- openedUrl = await callback()+ it('opens the popup before lookup completes and navigates to the first installed app', async () => {+ let resolveResponse!: (response: Response) => void+ const response = new Promise<Response>((resolve) => {+ resolveResponse = resolve})-+ installedRequest.mockReturnValueOnce(response)render(<AppCard app={mockApp} />)-fireEvent.click(getOperationsTrigger())- await waitFor(() => {- const openInExploreBtn = screen.getByText('app.openInExplore')- fireEvent.click(openInExploreBtn)- })-- await waitFor(() => {- expect(exploreService.fetchInstalledAppList).toHaveBeenCalledWith(mockApp.id)- expect(openedUrl).toBe('/installed/installed-1')- })- })-- it('should show string errors from open in explore onError callback', async () => {- mockOpenAsyncWindow.mockImplementationOnce(- async (- _callback: () => Promise<string>,- options?: { onError?: (err: unknown) => void },- ) => {- options?.onError?.('Window failed')- },- )-+ fireEvent.click(await screen.findByRole('menuitem', { name: 'app.openInExplore' }))++ expect(openWindow).toHaveBeenCalledOnce()+ expect(openWindow).toHaveBeenCalledWith('about:blank', '_blank', undefined)+ expect(popup.opener).toBeNull()+ expect(popup.location.href).toBe('')+ await waitFor(() => expect(installedRequest).toHaveBeenCalledOnce())+ const url = new URL(installedRequest.mock.calls[0]![0])+ expect(url.pathname).toBe('/console/api/installed-apps')+ expect(url.searchParams.get('app_id')).toBe(mockApp.id)+ expect(installedRequest.mock.calls[0]![2].request.method).toBe('GET')+ resolveResponse(Response.json(installedApps))+ await waitFor(() => expect(popup.location.href).toBe('/installed/installed-1'))+ expect(popup.close).not.toHaveBeenCalled()+ })++ it('reports a blocked popup without making a request', async () => {+ openWindow.mockReturnValueOnce(null)render(<AppCard app={mockApp} />)-fireEvent.click(getOperationsTrigger())- await waitFor(() => {- fireEvent.click(screen.getByText('app.openInExplore'))- })-- await waitFor(() => {- expect(toastMocks.record).toHaveBeenCalledWith({ type: 'error', message: 'Window failed' })+ fireEvent.click(await screen.findByRole('menuitem', { name: 'app.openInExplore' }))+ expect(installedRequest).not.toHaveBeenCalled()+ expect(toastMocks.record).toHaveBeenCalledWith({+ type: 'error',+ message: 'Failed to open new window',})})})@@ -1527,70 +1559,38 @@ describe('AppCard', () => {fireEvent.click(screen.getByText('app.openInExplore'))- expect(mockOpenAsyncWindow).not.toHaveBeenCalled()- expect(exploreService.fetchInstalledAppList).not.toHaveBeenCalled()+ expect(openWindow).not.toHaveBeenCalled()+ expect(installedRequest).not.toHaveBeenCalled()expect(toastMocks.record).toHaveBeenCalledWith({type: 'error',message: 'app.notPublishedYet',})})- it('should handle case when installed_apps is empty array', async () => {- vi.mocked(exploreService.fetchInstalledAppList).mockResolvedValueOnce({- has_more: false,- installed_apps: [],- next_cursor: null,- })-- // Configure mockOpenAsyncWindow to call the callback and trigger error- mockOpenAsyncWindow.mockImplementationOnce(- async (callback: () => Promise<string>, options?: { onError?: (err: unknown) => void }) => {- try {- await callback()- } catch (err) {- options?.onError?.(err)- }- },+ it('closes the popup and reports an empty installed list', async () => {+ installedRequest.mockResolvedValueOnce(+ Response.json({ has_more: false, installed_apps: [], next_cursor: null }),)-render(<AppCard app={mockApp} />)-fireEvent.click(getOperationsTrigger())- await waitFor(() => {- const openInExploreBtn = screen.getByText('app.openInExplore')- fireEvent.click(openInExploreBtn)- })-- await waitFor(() => {- expect(exploreService.fetchInstalledAppList).toHaveBeenCalled()- expect(toastMocks.record).toHaveBeenCalledWith({- type: 'error',- message: 'app.notPublishedYet',- })+ fireEvent.click(await screen.findByRole('menuitem', { name: 'app.openInExplore' }))+ await waitFor(() => expect(popup.close).toHaveBeenCalledOnce())+ expect(popup.location.href).toBe('')+ expect(toastMocks.record).toHaveBeenCalledWith({+ type: 'error',+ message: 'app.notPublishedYet',})})- it('should handle case when API throws in callback', async () => {- vi.mocked(exploreService.fetchInstalledAppList).mockRejectedValueOnce(- new Error('Network error'),- )-- // Configure mockOpenAsyncWindow to call the callback without catching- mockOpenAsyncWindow.mockImplementationOnce(async (callback: () => Promise<string>) => {- return await callback()- })-+ it('closes the popup and reports a failed lookup without retrying', async () => {+ installedRequest.mockRejectedValueOnce(new Error('Network error'))render(<AppCard app={mockApp} />)-fireEvent.click(getOperationsTrigger())- await waitFor(() => {- const openInExploreBtn = screen.getByText('app.openInExplore')- fireEvent.click(openInExploreBtn)- })-- await waitFor(() => {- expect(exploreService.fetchInstalledAppList).toHaveBeenCalled()- })+ fireEvent.click(await screen.findByRole('menuitem', { name: 'app.openInExplore' }))+ await waitFor(() => expect(popup.close).toHaveBeenCalledOnce())+ expect(installedRequest).toHaveBeenCalledOnce()+ expect(popup.location.href).toBe('')+ expect(toastMocks.record).toHaveBeenCalledWith({ type: 'error', message: 'Network error' })})})@@ -1715,8 +1715,8 @@ describe('AppCard', () => {fireEvent.click(screen.getByText('app.openInExplore'))- expect(mockOpenAsyncWindow).not.toHaveBeenCalled()- expect(exploreService.fetchInstalledAppList).not.toHaveBeenCalled()+ expect(openWindow).not.toHaveBeenCalled()+ expect(installedRequest).not.toHaveBeenCalled()expect(toastMocks.record).toHaveBeenCalledWith({type: 'error',message: 'app.notPublishedYet',diff --git a/web/app/components/apps/__tests__/index.spec.tsx b/web/app/components/apps/__tests__/index.spec.tsxindex 04c21b44538..ccb28f1febf 100644--- a/web/app/components/apps/__tests__/index.spec.tsx+++ b/web/app/components/apps/__tests__/index.spec.tsx@@ -1,202 +1,84 @@-import type { App } from '@/models/explore'-import type { TryAppSelection } from '@/types/try-app'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { fireEvent, screen, waitFor } from '@testing-library/react'+import type { Import } from '@dify/contracts/api/console/apps/types.gen'+import type {+ RecommendedAppDetailResponse,+ RecommendedAppResponse,+} from '@dify/contracts/api/console/explore/types.gen'+import type { QueryClient } from '@tanstack/react-query'+import { zGetFeaturesResponse } from '@dify/contracts/api/console/features/zod.gen'+import { cleanup, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import * as React from 'react'-import { useContextSelector } from 'use-context-selector'-import AppListContext from '@/context/app-list-context'-import { fetchAppDetail } from '@/service/explore'-import { render } from '@/test/console/render'-import { AppModeEnum } from '@/types/app'+import { consoleQuery } from '@/service/console'+import {+ createConsoleQueryClient,+ renderWithConsoleQuery as render,+} from '@/test/console/query-data'import { Apps } from '../index'+const { request, toast, checkDependencies, redirect, trackCreateApp, push, replace, search } =+ vi.hoisted(() => ({+ request: vi.fn(),+ toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn() },+ checkDependencies: vi.fn(),+ redirect: vi.fn(),+ trackCreateApp: vi.fn(),+ push: vi.fn(),+ replace: vi.fn(),+ search: { params: new URLSearchParams() },+ }))+vi.mock('@/service/base', () => ({ request }))+vi.mock('@/app/notifications', () => ({ toast }))+vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({+ usePluginDependencies: () => ({ handleCheckPluginDependencies: checkDependencies }),+}))+vi.mock('@/utils/app-redirection', () => ({ getRedirection: redirect }))+vi.mock('@/utils/create-app-tracking', () => ({ trackCreateApp }))+vi.mock('@/next/navigation', () => ({+ useRouter: () => ({ push, replace }),+ useParams: () => ({}),+ useSearchParams: () => search.params,+}))vi.mock('@/next/dynamic', () => ({default: (loader: () => Promise<{ default: React.ComponentType }>) => {- const LazyComp = React.lazy(loader)- return function DynamicWrapper(props: Record<string, unknown>) {- return React.createElement(- React.Suspense,- { fallback: null },- React.createElement(LazyComp, props),+ const LazyComponent = React.lazy(loader)+ return function Dynamic(props: Record<string, unknown>) {+ return (+ <React.Suspense fallback={null}>+ <LazyComponent {...props} />+ </React.Suspense>)}},}))--let documentTitleCalls: string[] = []-const mockHandleImportDSL = vi.fn()-const mockHandleImportDSLConfirm = vi.fn()-const mockTrackCreateApp = vi.fn()-const mockFetchAppDetail = vi.mocked(fetchAppDetail)-let mockWorkspacePermissionKeys: string[] = ['app.create_and_management']--const mockTemplateApp: App = {- app_id: 'template-1',- categories: ['Assistant'],- app: {- id: 'template-1',- mode: AppModeEnum.CHAT,- icon_type: 'emoji',- icon: '🤖',- icon_background: '#fff',- icon_url: '',- name: 'Sample App',- description: 'Sample App',- use_icon_as_answer_icon: false,- },- description: 'Sample App',- can_trial: true,- copyright: '',- privacy_policy: null,- custom_disclaimer: null,- position: 1,- is_listed: true,- install_count: 0,- installed: false,- editable: false,- is_agent: false,-}--vi.mock('@/hooks/use-document-title', () => ({- default: (title: string) => {- documentTitleCalls.push(title)- },-}))--vi.mock('@/app/education/expire-notice', () => ({- EducationExpireNotice: () => null,-}))--vi.mock('@/context/permission-state', async () => {- const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')- return createPermissionStateModuleMock(() => ({- workspacePermissionKeys: mockWorkspacePermissionKeys,- }))-})--vi.mock('@/hooks/use-import-dsl', () => ({- useImportDSL: () => ({- handleImportDSL: mockHandleImportDSL,- handleImportDSLConfirm: mockHandleImportDSLConfirm,- versions: [],- isFetching: false,- }),-}))--const mockReplace = vi.fn()-let mockSearchParams = new URLSearchParams()--vi.mock('@/next/navigation', () => ({- useRouter: () => ({- replace: mockReplace,- }),- useSearchParams: () => mockSearchParams,-}))--vi.mock('../list', () => {- const MockList = ({- onCreateLearnDify,- onTryLearnDify,- }: {- onCreateLearnDify?: (app: App) => void- onTryLearnDify?: (params: TryAppSelection) => void- }) => {- const openTryAppPanel = useContextSelector(AppListContext, (ctx) => ctx.openTryAppPanel)- return React.createElement(- 'div',- { 'data-testid': 'apps-list' },- React.createElement('span', null, 'Apps List'),- React.createElement(- 'button',- {- 'data-testid': 'open-preview',- onClick: () =>- openTryAppPanel({- appId: mockTemplateApp.app_id,- app: mockTemplateApp,- }),- },- 'Open Preview',- ),- React.createElement(- 'button',- {- type: 'button',- onClick: () => onTryLearnDify?.({ appId: mockTemplateApp.app_id, app: mockTemplateApp }),- },- 'Preview Learn Dify template',- ),- React.createElement(- 'button',- { type: 'button', onClick: () => onCreateLearnDify?.(mockTemplateApp) },- 'Create Learn Dify template',- ),- )+vi.mock('@/app/education/expire-notice', () => ({ EducationExpireNotice: () => null }))+vi.mock('../list', async () => {+ const { default: LearnDify } = await import('@/app/components/explore/learn-dify')+ return {+ List: ({+ onCreateLearnDify,+ onTryLearnDify,+ }: {+ onCreateLearnDify: (app: RecommendedAppResponse) => void+ onTryLearnDify: (app: RecommendedAppResponse) => void+ }) => (+ <LearnDify+ canCreate+ onCreate={onCreateLearnDify}+ onTry={onTryLearnDify}+ dismissible={false}+ />+ ),}-- return { List: MockList }})-+// The running preview and marketplace download are separate feature boundaries.vi.mock('../../explore/try-app', () => ({default: ({ onCreate, onClose }: { onCreate: () => void; onClose: () => void }) => (- <div data-testid="try-app-panel">- <button data-testid="try-app-create" onClick={onCreate}>- Create- </button>- <button data-testid="try-app-close" onClick={onClose}>- Close- </button>- </div>+ <section aria-label="Template preview">+ <button onClick={onCreate}>Create preview</button>+ <button onClick={onClose}>Close preview</button>+ </section>),}))--vi.mock('../../explore/create-app-modal', () => ({- default: ({- show,- onConfirm,- onHide,- }: {- show: boolean- onConfirm: (payload: Record<string, string>) => Promise<void>- onHide: () => void- }) =>- show ? (- <div data-testid="create-app-modal">- <button- data-testid="confirm-create"- onClick={() =>- onConfirm({- name: 'Created App',- icon_type: 'emoji',- icon: '🤖',- icon_background: '#fff',- description: 'created from preview',- })- }- >- Confirm- </button>- <button data-testid="hide-create" onClick={onHide}>- Hide- </button>- </div>- ) : null,-}))--vi.mock('../../app/create-from-dsl-modal/dsl-confirm-modal', () => ({- default: ({ onConfirm, onCancel }: { onConfirm: () => void; onCancel: () => void }) => (- <div data-testid="dsl-confirm-modal">- <button data-testid="confirm-dsl" onClick={onConfirm}>- Confirm DSL- </button>- <button data-testid="cancel-dsl" onClick={onCancel}>- Cancel DSL- </button>- </div>- ),-}))-vi.mock('../import-from-marketplace-template-modal', () => ({default: ({templateId,@@ -207,287 +89,232 @@ vi.mock('../import-from-marketplace-template-modal', () => ({onClose: () => voidonConfirm: (dsl: string) => void}) => (- <div data-testid="marketplace-template-modal">- <span data-testid="template-id">{templateId}</span>- <button data-testid="close-template" onClick={onClose}>- Close Template- </button>- <button data-testid="confirm-template" onClick={() => onConfirm('yaml-dsl-content')}>- Confirm Template- </button>- </div>+ <section aria-label="Marketplace download">+ <span>{templateId}</span>+ <button onClick={onClose}>Close download</button>+ <button onClick={() => onConfirm('marketplace-dsl')}>Import download</button>+ </section>),}))-vi.mock('@/service/explore', () => ({- fetchAppDetail: vi.fn(),-}))--vi.mock('@/utils/create-app-tracking', () => ({- trackCreateApp: (...args: unknown[]) => mockTrackCreateApp(...args),-}))--describe('Apps', () => {- const createQueryClient = () =>- new QueryClient({- defaultOptions: {- queries: {- retry: false,- },- },- })-- const renderWithClient = (ui: React.ReactElement) => {- const queryClient = createQueryClient()- const wrapper = ({ children }: { children: React.ReactNode }) => (- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>- )- return {- queryClient,- ...render(ui, { wrapper }),- }- }-- beforeEach(() => {- vi.clearAllMocks()- documentTitleCalls = []- mockWorkspacePermissionKeys = ['app.create_and_management']- mockSearchParams = new URLSearchParams()- mockReplace.mockClear()- mockFetchAppDetail.mockResolvedValue({- id: 'template-1',- name: 'Sample App',- icon: '🤖',- icon_background: '#fff',- mode: AppModeEnum.CHAT,- export_data: 'yaml-content',- can_trial: true,- })+const template: RecommendedAppResponse = {+ app_id: 'canonical-template',+ app: {+ id: 'different-nested-id',+ name: 'Sample App',+ mode: 'chat',+ icon_type: 'emoji',+ icon: '🤖',+ icon_background: '#fff',+ icon_url: null,+ },+ description: 'Catalog description',+ can_trial: true,+}+const detail: RecommendedAppDetailResponse = {+ id: 'canonical-template',+ name: 'Sample App',+ mode: 'chat',+ can_trial: true,+ export_data: 'fresh-dsl',+}+const completed: Import = {+ id: 'import-1',+ status: 'completed',+ app_id: 'created-app',+ app_mode: 'chat',+ permission_keys: ['app.edit'],+}+let importResponse: Import+let detailFails: boolean+const clients = new Set<QueryClient>()+const features = zGetFeaturesResponse.parse({ apps: { size: 1, limit: 10 } })++beforeEach(() => {+ vi.clearAllMocks()+ localStorage.clear()+ search.params = new URLSearchParams()+ importResponse = completed+ detailFails = false+ request.mockImplementation(async (url: string) => {+ const path = new URL(url).pathname.replace('/console/api', '') + new URL(url).search+ if (path === '/explore/apps/canonical-template')+ return detailFails+ ? Response.json({ message: 'Unavailable' }, { status: 503 })+ : Response.json(detail)+ if (path === '/features') return Response.json(features)+ if (path === '/apps/imports') return Response.json(importResponse)+ if (path === '/apps/imports/import-1/confirm') return Response.json(completed)+ throw new Error(`Unexpected request: ${url}`)})+})- describe('Integration', () => {- it('should track template preview creation after a successful import', async () => {- mockHandleImportDSL.mockImplementation(- async (- _payload: unknown,- options: { onSuccess?: (payload: { app_mode: AppModeEnum }) => void },- ) => {- options.onSuccess?.({ app_mode: AppModeEnum.CHAT })- },- )-- renderWithClient(<Apps />)-- fireEvent.click(screen.getByTestId('open-preview'))- fireEvent.click(await screen.findByTestId('try-app-create'))- fireEvent.click(await screen.findByTestId('confirm-create'))-- await waitFor(() => {- expect(mockFetchAppDetail).toHaveBeenCalledWith('template-1')- expect(mockTrackCreateApp).toHaveBeenCalledWith({- source: 'studio_template_preview',- appMode: AppModeEnum.CHAT,- templateId: 'template-1',- })- })- })-- it('should open the template preview from Learn Dify', async () => {- const user = userEvent.setup()- renderWithClient(<Apps />)-- await user.click(screen.getByRole('button', { name: 'Preview Learn Dify template' }))-- expect(await screen.findByTestId('try-app-panel')).toBeInTheDocument()- })-- it('should close the template preview', async () => {- const user = userEvent.setup()- renderWithClient(<Apps />)-- await user.click(screen.getByTestId('open-preview'))- await user.click(await screen.findByTestId('try-app-close'))-- expect(screen.queryByTestId('try-app-panel')).not.toBeInTheDocument()- })-- it('should open the create modal from Learn Dify', async () => {- const user = userEvent.setup()- renderWithClient(<Apps />)-- await user.click(screen.getByRole('button', { name: 'Create Learn Dify template' }))-- expect(await screen.findByTestId('create-app-modal')).toBeInTheDocument()- })-- it('should track template preview creation after confirming a pending import', async () => {- mockHandleImportDSL.mockImplementation(- async (_payload: unknown, options: { onPending?: () => void }) => {- options.onPending?.()- },- )- mockHandleImportDSLConfirm.mockImplementation(- async (options: { onSuccess?: (payload: { app_mode: AppModeEnum }) => void }) => {- options.onSuccess?.({ app_mode: AppModeEnum.WORKFLOW })- },- )-- renderWithClient(<Apps />)-- fireEvent.click(screen.getByTestId('open-preview'))- fireEvent.click(await screen.findByTestId('try-app-create'))- fireEvent.click(await screen.findByTestId('confirm-create'))-- fireEvent.click(await screen.findByTestId('confirm-dsl'))-- await waitFor(() => {- expect(mockHandleImportDSLConfirm).toHaveBeenCalledTimes(1)- expect(mockTrackCreateApp).toHaveBeenCalledWith({- source: 'studio_template_preview',- appMode: AppModeEnum.WORKFLOW,- templateId: 'template-1',- })- })- })-- it('should close the dsl confirm modal when the pending import is canceled', async () => {- mockHandleImportDSL.mockImplementation(- async (_payload: unknown, options: { onPending?: () => void }) => {- options.onPending?.()- },- )-- renderWithClient(<Apps />)-- fireEvent.click(screen.getByTestId('open-preview'))- fireEvent.click(await screen.findByTestId('try-app-create'))- fireEvent.click(await screen.findByTestId('confirm-create'))-- fireEvent.click(await screen.findByTestId('cancel-dsl'))-- await waitFor(() => {- expect(screen.queryByTestId('dsl-confirm-modal')).not.toBeInTheDocument()- })- expect(mockTrackCreateApp).not.toHaveBeenCalled()- })-- it('should hide the create modal without tracking when the modal closes', async () => {- renderWithClient(<Apps />)-- fireEvent.click(screen.getByTestId('open-preview'))- fireEvent.click(await screen.findByTestId('try-app-create'))-- fireEvent.click(await screen.findByTestId('hide-create'))+afterEach(async () => {+ cleanup()+ await Promise.all([...clients].map((client) => client.cancelQueries()))+ for (const client of clients) client.clear()+ clients.clear()+})- await waitFor(() => {- expect(screen.queryByTestId('create-app-modal')).not.toBeInTheDocument()- })- expect(mockTrackCreateApp).not.toHaveBeenCalled()- })+const setup = ({ cloud = false, permission = true, item = template } = {}) => {+ const queryClient = createConsoleQueryClient()+ clients.add(queryClient)+ queryClient.setQueryData(+ consoleQuery.explore.apps.learnDify.get.queryKey({ input: { query: { language: 'en-US' } } }),+ { recommended_apps: [item] },+ )+ queryClient.setQueryData(+ consoleQuery.explore.apps.byAppId.get.queryKey({+ input: { params: { app_id: template.app_id } },+ }),+ { ...detail, export_data: 'stale-dsl' },+ )+ return render(<Apps />, {+ queryClient,+ workspacePermissionKeys: permission ? ['app.create_and_management'] : [],+ systemFeatures: { deployment_edition: cloud ? 'CLOUD' : 'COMMUNITY', enable_learn_app: true },+ features: { apps: { size: 0, limit: 10 } },})+}+const openCreate = async (user: ReturnType<typeof userEvent.setup>, preview = false) => {+ await user.click(screen.getByRole('button', { name: 'Sample App' }))+ if (preview) await user.click(await screen.findByRole('button', { name: 'Create preview' }))+ return screen.findByRole('dialog')+}+const submit = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.click(screen.getByRole('button', { name: /common\.operation\.create/ }))+}- describe('Marketplace Template', () => {- it('should render the template modal when template-id is in search params', async () => {- mockSearchParams = new URLSearchParams('template-id=tpl-42')- renderWithClient(<Apps />)-- expect(await screen.findByTestId('marketplace-template-modal')).toBeInTheDocument()- expect(screen.getByTestId('template-id')).toHaveTextContent('tpl-42')- })-- it('should not render the template modal without app.create_and_management permission', () => {- mockWorkspacePermissionKeys = []- mockSearchParams = new URLSearchParams('template-id=tpl-42')- renderWithClient(<Apps />)-- expect(screen.queryByTestId('marketplace-template-modal')).not.toBeInTheDocument()- })-- it('should not render the template modal when no template-id is present', () => {- renderWithClient(<Apps />)-- expect(screen.queryByTestId('marketplace-template-modal')).not.toBeInTheDocument()- })-- it('should close the template modal and remove template-id from URL', async () => {- mockSearchParams = new URLSearchParams('template-id=tpl-42')- renderWithClient(<Apps />)-- fireEvent.click(await screen.findByTestId('close-template'))-- expect(mockReplace).toHaveBeenCalledTimes(1)- const replaceArg = mockReplace.mock.calls[0]![0] as string- expect(replaceArg).not.toContain('template-id')- })-- it('should import DSL from marketplace template on confirm', async () => {- mockHandleImportDSL.mockImplementation(- async (- _payload: unknown,- options: { onSuccess?: (payload: { app_mode: AppModeEnum }) => void },- ) => {- options.onSuccess?.({ app_mode: AppModeEnum.CHAT })- },- )- mockSearchParams = new URLSearchParams('template-id=tpl-42')- renderWithClient(<Apps />)-- fireEvent.click(await screen.findByTestId('confirm-template'))-- await waitFor(() => {- expect(mockHandleImportDSL).toHaveBeenCalledWith(- { mode: 'yaml-content', yaml_content: 'yaml-dsl-content' },- expect.objectContaining({ onSuccess: expect.any(Function) }),- )- expect(mockTrackCreateApp).toHaveBeenCalledWith({- source: 'external',- appMode: AppModeEnum.CHAT,- templateId: 'tpl-42',- })- expect(mockReplace).toHaveBeenCalled()- })- })-- it('should not open create modal from template preview without app.create_and_management permission', async () => {- mockWorkspacePermissionKeys = []- renderWithClient(<Apps />)+it('imports fresh canonical detail through the real form and import orchestration', async () => {+ const user = userEvent.setup()+ setup()+ await openCreate(user)+ expect(screen.getByPlaceholderText('app.newApp.appDescriptionPlaceholder')).toHaveValue('')+ await submit(user)+ await waitFor(() => expect(redirect).toHaveBeenCalled())+ expect(+ request.mock.calls+ .map(([url]) => new URL(url).pathname.replace('/console/api', ''))+ .filter((path) => path !== '/features'),+ ).toEqual(['/explore/apps/canonical-template', '/apps/imports'])+ const importRequest = request.mock.calls.find(([url]) =>+ new URL(url).pathname.endsWith('/apps/imports'),+ )+ expect(await importRequest?.[2].request.json()).toMatchObject({+ yaml_content: 'fresh-dsl',+ name: 'Sample App',+ description: '',+ })+ expect(checkDependencies).toHaveBeenCalledWith('created-app')+ expect(toast.success).toHaveBeenCalledWith('app.newApp.appCreated')+})- fireEvent.click(screen.getByTestId('open-preview'))- fireEvent.click(await screen.findByTestId('try-app-create'))+it('tracks successful preview creation and closes the preview', async () => {+ const user = userEvent.setup()+ setup({ cloud: true })+ await openCreate(user, true)+ await submit(user)+ await waitFor(() =>+ expect(trackCreateApp).toHaveBeenCalledWith({+ source: 'studio_template_preview',+ templateId: 'canonical-template',+ appMode: 'chat',+ }),+ )+ expect(screen.queryByRole('region', { name: 'Template preview' })).not.toBeInTheDocument()+})- expect(screen.queryByTestId('create-app-modal')).not.toBeInTheDocument()- })+it('handles detail rejection once without import, navigation, or reopening the submitted modal', async () => {+ const user = userEvent.setup()+ detailFails = true+ setup()+ await openCreate(user)+ await submit(user)+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('app.newApp.appCreateFailed'))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ const paths = request.mock.calls.map(([url]) => new URL(url).pathname.replace('/console/api', ''))+ expect(paths.filter((path) => path === '/explore/apps/canonical-template')).toHaveLength(1)+ expect(paths.some((path) => path.startsWith('/apps/imports'))).toBe(false)+ expect(toast.error).toHaveBeenCalledOnce()+ expect(redirect).not.toHaveBeenCalled()+ expect(trackCreateApp).not.toHaveBeenCalled()+})- it('should track marketplace template creation after confirming a pending import', async () => {- mockHandleImportDSL.mockImplementation(- async (_payload: unknown, options: { onPending?: () => void }) => {- options.onPending?.()- },- )- mockHandleImportDSLConfirm.mockImplementation(- async (options: { onSuccess?: (payload: { app_mode: AppModeEnum }) => void }) => {- options.onSuccess?.({ app_mode: AppModeEnum.WORKFLOW })- },- )- mockSearchParams = new URLSearchParams('template-id=tpl-42')- renderWithClient(<Apps />)+it('keeps the pending import confirmation and tracks only after successful confirmation', async () => {+ const user = userEvent.setup()+ importResponse = {+ id: 'import-1',+ status: 'pending',+ imported_dsl_version: '0.8.0',+ current_dsl_version: '0.6.0',+ }+ setup({ cloud: true })+ await openCreate(user, true)+ await submit(user)+ const dialog = await screen.findByRole('alertdialog')+ expect(within(dialog).getByText('0.8.0')).toBeInTheDocument()+ expect(trackCreateApp).not.toHaveBeenCalled()+ await user.click(within(dialog).getByRole('button', { name: 'app.newApp.Confirm' }))+ await waitFor(() => expect(redirect).toHaveBeenCalled())+ expect(+ request.mock.calls+ .map(([url]) => new URL(url).pathname.replace('/console/api', ''))+ .filter((path) => path !== '/features'),+ ).toEqual(['/explore/apps/canonical-template', '/apps/imports', '/apps/imports/import-1/confirm'])+ expect(trackCreateApp).toHaveBeenCalledWith({+ source: 'studio_template_preview',+ templateId: 'canonical-template',+ appMode: 'chat',+ })+})- fireEvent.click(await screen.findByTestId('confirm-template'))+it('reports import failure without tracking or navigating', async () => {+ const user = userEvent.setup()+ importResponse = { id: 'import-1', status: 'failed' }+ setup({ cloud: true })+ await openCreate(user, true)+ await submit(user)+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('app.newApp.appCreateFailed'))+ expect(redirect).not.toHaveBeenCalled()+ expect(trackCreateApp).not.toHaveBeenCalled()+})- await waitFor(() => {- expect(screen.getByTestId('dsl-confirm-modal')).toBeInTheDocument()- expect(mockReplace).toHaveBeenCalled()- })+it('keeps nullable template metadata editable through the actual modal', async () => {+ const user = userEvent.setup()+ setup({ item: { app_id: 'null-template', app: null, can_trial: false } })+ await user.click(screen.getByRole('button', { name: '' }))+ await screen.findByRole('dialog')+ expect(screen.getByPlaceholderText('app.newApp.appNamePlaceholder')).toHaveValue('')+ expect(screen.getByPlaceholderText('app.newApp.appDescriptionPlaceholder')).toHaveValue('')+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))+ expect(request).not.toHaveBeenCalled()+})- fireEvent.click(screen.getByTestId('confirm-dsl'))+it('does not allow template creation or marketplace import without permission', async () => {+ const user = userEvent.setup()+ search.params = new URLSearchParams('template-id=tpl-42')+ setup({ permission: false })+ await user.click(screen.getByRole('button', { name: 'Sample App' }))+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(screen.queryByRole('region', { name: 'Marketplace download' })).not.toBeInTheDocument()+ expect(request).not.toHaveBeenCalled()+})- await waitFor(() => {- expect(mockTrackCreateApp).toHaveBeenCalledWith({- source: 'external',- appMode: AppModeEnum.WORKFLOW,- templateId: 'tpl-42',- })- })- })+it('preserves marketplace import tracking and removes only its URL parameter', async () => {+ const user = userEvent.setup()+ search.params = new URLSearchParams('template-id=tpl-42&category=chat')+ setup()+ await user.click(await screen.findByRole('button', { name: 'Import download' }))+ await waitFor(() =>+ expect(trackCreateApp).toHaveBeenCalledWith({+ source: 'external',+ templateId: 'tpl-42',+ appMode: 'chat',+ }),+ )+ expect(await request.mock.calls[0]![2].request.json()).toEqual({+ mode: 'yaml-content',+ yaml_content: 'marketplace-dsl',})+ expect(replace).toHaveBeenCalledWith('?category=chat', { scroll: false })})diff --git a/web/app/components/apps/__tests__/list.spec.tsx b/web/app/components/apps/__tests__/list.spec.tsxindex 1ede7a6df6e..d76bf30f0eb 100644--- a/web/app/components/apps/__tests__/list.spec.tsx+++ b/web/app/components/apps/__tests__/list.spec.tsx@@ -1,7 +1,6 @@+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'import type { StepByStepTourSessionState } from '@/app/components/step-by-step-tour/types'-import type { App } from '@/models/explore'-import type { TryAppSelection } from '@/types/try-app'import { keepPreviousData } from '@tanstack/react-query'import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'@@ -54,8 +53,6 @@ const mockLearnDifyApp = vi.hoisted(icon_background: '#fff',icon_url: '',name: 'Learn Dify Template',- description: 'Learn how to build with Dify',- use_icon_as_answer_icon: false,},description: 'Learn how to build with Dify',copyright: '',@@ -64,12 +61,8 @@ const mockLearnDifyApp = vi.hoisted(categories: ['Assistant'],position: 1,is_listed: true,- install_count: 0,- installed: false,- editable: false,- is_agent: false,can_trial: true,- }) satisfies App,+ }) satisfies RecommendedAppResponse,)let mockSearchParams = new URLSearchParams('')@@ -446,8 +439,8 @@ vi.mock('@/app/components/explore/learn-dify', () => ({onTry,}: {title?: string- onCreate?: (app: App) => void- onTry?: (params: TryAppSelection) => void+ onCreate?: (app: RecommendedAppResponse) => void+ onTry?: (app: RecommendedAppResponse) => void}) =>React.createElement('section',@@ -457,7 +450,7 @@ vi.mock('@/app/components/explore/learn-dify', () => ({'button',{type: 'button',- onClick: () => onTry?.({ appId: mockLearnDifyApp.app_id, app: mockLearnDifyApp }),+ onClick: () => onTry?.(mockLearnDifyApp),},'Preview Learn Dify template',),@@ -490,8 +483,8 @@ beforeAll(() => {})type RenderListOptions = {- onCreateLearnDify?: (app: App) => void- onTryLearnDify?: (params: TryAppSelection) => void+ onCreateLearnDify?: (app: RecommendedAppResponse) => void+ onTryLearnDify?: (app: RecommendedAppResponse) => voidsystemFeatures?: Partial<GetSystemFeaturesResponse>}@@ -1020,10 +1013,7 @@ describe('List', () => {})await user.click(screen.getByRole('button', { name: 'Preview Learn Dify template' }))- expect(onTryLearnDify).toHaveBeenCalledWith({- appId: mockLearnDifyApp.app_id,- app: mockLearnDifyApp,- })+ expect(onTryLearnDify).toHaveBeenCalledWith(mockLearnDifyApp)await user.click(screen.getByRole('button', { name: 'Create Learn Dify template' }))expect(onCreateLearnDify).toHaveBeenCalledWith(mockLearnDifyApp)diff --git a/web/app/components/apps/app-card/interactions.tsx b/web/app/components/apps/app-card/interactions.tsxindex c625ba4ef89..9d99dc8f3c3 100644--- a/web/app/components/apps/app-card/interactions.tsx+++ b/web/app/components/apps/app-card/interactions.tsx@@ -58,8 +58,7 @@ import { AccessMode } from '@/models/access-control'import dynamic from '@/next/dynamic'import { useRouter } from '@/next/navigation'import { useGetUserCanAccessApp } from '@/service/access-control/use-app-access-control'-import { consoleQuery } from '@/service/console'-import { fetchInstalledAppList } from '@/service/explore'+import { consoleClient, consoleQuery } from '@/service/console'import { AppModeEnum } from '@/types/app'import { getRedirection } from '@/utils/app-redirection'import { getAppACLCapabilities, hasPermission } from '@/utils/permission'@@ -164,7 +163,9 @@ function AppCardOperationsMenuItems({try {await openAsyncWindow(async () => {- const { installed_apps } = await fetchInstalledAppList(app.id)+ const { installed_apps } = await consoleClient.installedApps.get({+ query: { app_id: app.id },+ })if (installed_apps?.length > 0)return `${basePath}${buildInstalledAppPath(installed_apps[0]!.id)}`throw new Error(t(($) => $.notPublishedYet, { ns: 'app' }))diff --git a/web/app/components/apps/app-list-catalog.tsx b/web/app/components/apps/app-list-catalog.tsxindex 48bad5404eb..ef016678bc8 100644--- a/web/app/components/apps/app-list-catalog.tsx+++ b/web/app/components/apps/app-list-catalog.tsx@@ -5,10 +5,9 @@ import type {AppPartial,GetAppsData,} from '@dify/contracts/api/console/apps/types.gen'+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'import type { RefObject } from 'react'-import type { App } from '@/models/explore'-import type { TryAppSelection } from '@/types/try-app'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { keepPreviousData, useInfiniteQuery, useQuery } from '@tanstack/react-query'@@ -43,11 +42,11 @@ type AppListCatalogProps = Readonly<{dragging: booleanhasActiveFilters: booleanonCreateBlank: () => void- onCreateLearnDify?: (app: App) => void+ onCreateLearnDify?: (app: RecommendedAppResponse) => voidonCreateTemplate: () => voidonImportDSL: () => voidonOpenTagManagement: () => void- onTryLearnDify?: (params: TryAppSelection) => void+ onTryLearnDify?: (app: RecommendedAppResponse) => voidscrollViewportRef: RefObject<HTMLDivElement | null>}>diff --git a/web/app/components/apps/first-empty-state/index.tsx b/web/app/components/apps/first-empty-state/index.tsxindex fe91e64a7f4..b798fde778c 100644--- a/web/app/components/apps/first-empty-state/index.tsx+++ b/web/app/components/apps/first-empty-state/index.tsx@@ -1,8 +1,7 @@'use client'+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import type { ReactNode } from 'react'-import type { App } from '@/models/explore'-import type { TryAppSelection } from '@/types/try-app'import { cn } from '@langgenius/dify-ui/cn'import { useTranslation } from 'react-i18next'import LearnDify from '@/app/components/explore/learn-dify'@@ -26,10 +25,10 @@ type EmptyCreateAction = {type Props = {onCreateBlank: () => void- onCreateLearnDify?: (app: App) => void+ onCreateLearnDify?: (app: RecommendedAppResponse) => voidonCreateTemplate: () => voidonImportDSL: () => void- onTryLearnDify?: (params: TryAppSelection) => void+ onTryLearnDify?: (app: RecommendedAppResponse) => voidshowLearnDify: boolean}diff --git a/web/app/components/apps/index.tsx b/web/app/components/apps/index.tsxindex 00ae6eb7f20..7d0fa6124ab 100644--- a/web/app/components/apps/index.tsx+++ b/web/app/components/apps/index.tsx@@ -1,18 +1,19 @@'use client'+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import type { CreateAppModalProps } from '../explore/create-app-modal'-import type { App } from '@/models/explore'-import type { TryAppSelection } from '@/types/try-app'import type { TrackCreateAppParams } from '@/utils/create-app-tracking'import { useAtomValue } from 'jotai'import { useCallback, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'import { EducationExpireNotice } from '@/app/education/expire-notice'+import { toast } from '@/app/notifications'import AppListContext from '@/context/app-list-context'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { useImportDSL } from '@/hooks/use-import-dsl'import { DSLImportMode } from '@/models/app'import dynamic from '@/next/dynamic'import { useRouter, useSearchParams } from '@/next/navigation'-import { fetchAppDetail } from '@/service/explore'+import { consoleClient } from '@/service/console'import { trackCreateApp } from '@/utils/create-app-tracking'import { hasPermission } from '@/utils/permission'import { List } from './list'@@ -29,6 +30,7 @@ const ImportFromMarketplaceTemplateModal = dynamic(const AppListProvider = AppListContext.Providerconst AppsContent = () => {+ const { t } = useTranslation()const searchParams = useSearchParams()const { replace } = useRouter()const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)@@ -36,32 +38,26 @@ const AppsContent = () => {const templateId = searchParams.get('template-id')const templateDismissedRef = useRef(false)- const [currentTryAppParams, setCurrentTryAppParams] = useState<TryAppSelection | undefined>(- undefined,- )- const currentCreateAppModeRef = useRef<TryAppSelection['app']['app']['mode'] | null>(null)+ const [currApp, setCurrApp] = useState<RecommendedAppResponse | undefined>(undefined)+ const currentCreateAppModeRef = useRef<TrackCreateAppParams['appMode'] | null>(null)const currentCreateAppTrackingRef = useRef<Pick<TrackCreateAppParams,'source' | 'templateId'> | null>(null)- const currApp = currentTryAppParams?.appconst [isShowTryAppPanel, setIsShowTryAppPanel] = useState(false)const hideTryAppPanel = useCallback(() => {setIsShowTryAppPanel(false)}, [])- const openTryAppPanel = useCallback((selection: TryAppSelection) => {- setCurrentTryAppParams(selection)+ const openTryAppPanel = useCallback((app: RecommendedAppResponse) => {+ setCurrApp(app)setIsShowTryAppPanel(true)}, [])const [isShowCreateModal, setIsShowCreateModal] = useState(false)- const handleTryLearnDify = (params: TryAppSelection) => {- openTryAppPanel(params)- }- const handleCreateLearnDify = (app: App) => {+ const handleCreateLearnDify = (app: RecommendedAppResponse) => {if (!canCreateApp) return- setCurrentTryAppParams({ appId: app.app_id, app })+ setCurrApp(app)setIsShowCreateModal(true)}@@ -70,25 +66,22 @@ const AppsContent = () => {currentCreateAppTrackingRef.current = {source: 'studio_template_preview',- templateId: currentTryAppParams?.appId || currentTryAppParams?.app.app_id,+ templateId: currApp?.app_id,}setIsShowCreateModal(true)- }, [canCreateApp, currentTryAppParams?.app.app_id, currentTryAppParams?.appId])- const trackCurrentCreateApp = useCallback(- (appMode?: TryAppSelection['app']['app']['mode'] | null) => {- const currentCreateAppTracking = currentCreateAppTrackingRef.current- const resolvedAppMode = appMode ?? currentCreateAppModeRef.current- if (!resolvedAppMode || !currentCreateAppTracking) return-- trackCreateApp({- ...currentCreateAppTracking,- appMode: resolvedAppMode,- })- currentCreateAppTrackingRef.current = null- currentCreateAppModeRef.current = null- },- [],- )+ }, [canCreateApp, currApp?.app_id])+ const trackCurrentCreateApp = useCallback((appMode?: TrackCreateAppParams['appMode'] | null) => {+ const currentCreateAppTracking = currentCreateAppTrackingRef.current+ const resolvedAppMode = appMode ?? currentCreateAppModeRef.current+ if (!resolvedAppMode || !currentCreateAppTracking) return++ trackCreateApp({+ ...currentCreateAppTracking,+ appMode: resolvedAppMode,+ })+ currentCreateAppTrackingRef.current = null+ currentCreateAppModeRef.current = null+ }, [])const [showDSLConfirmModal, setShowDSLConfirmModal] = useState(false)@@ -141,32 +134,38 @@ const AppsContent = () => {const onCreate: CreateAppModalProps['onConfirm'] = useCallback(async ({ name, icon_type, icon, icon_background, description }) => {- if (!canCreateApp) return+ if (!canCreateApp || !currApp) returnhideTryAppPanel()- const { export_data, mode } = await fetchAppDetail(currApp?.app.id as string)- currentCreateAppModeRef.current = mode- const payload = {- mode: DSLImportMode.YAML_CONTENT,- yaml_content: export_data,- name,- icon_type,- icon,- icon_background,- description,+ try {+ const { export_data, mode } = await consoleClient.explore.apps.byAppId.get({+ params: { app_id: currApp.app_id },+ })+ currentCreateAppModeRef.current = mode+ const payload = {+ mode: DSLImportMode.YAML_CONTENT,+ yaml_content: export_data,+ name,+ icon_type,+ icon,+ icon_background,+ description,+ }+ await handleImportDSL(payload, {+ onSuccess: (response) => {+ trackCurrentCreateApp(response.app_mode)+ setIsShowCreateModal(false)+ },+ onPending: () => {+ setShowDSLConfirmModal(true)+ },+ })+ } catch {+ toast.error(t(($) => $['newApp.appCreateFailed'], { ns: 'app' }))}- await handleImportDSL(payload, {- onSuccess: (response) => {- trackCurrentCreateApp(response.app_mode)- setIsShowCreateModal(false)- },- onPending: () => {- setShowDSLConfirmModal(true)- },- })},- [canCreateApp, currApp?.app.id, handleImportDSL, hideTryAppPanel, trackCurrentCreateApp],+ [canCreateApp, currApp, handleImportDSL, hideTryAppPanel, trackCurrentCreateApp, t],)return (@@ -178,15 +177,9 @@ const AppsContent = () => {}}><div className="relative flex h-0 shrink-0 grow flex-col overflow-hidden bg-background-body">- <List onCreateLearnDify={handleCreateLearnDify} onTryLearnDify={handleTryLearnDify} />- {isShowTryAppPanel && currentTryAppParams && (- <TryApp- appId={currentTryAppParams.appId}- app={currentTryAppParams.app}- categories={currentTryAppParams.app.categories}- onClose={hideTryAppPanel}- onCreate={handleShowFromTryApp}- />+ <List onCreateLearnDify={handleCreateLearnDify} onTryLearnDify={openTryAppPanel} />+ {isShowTryAppPanel && currApp && (+ <TryApp app={currApp} onClose={hideTryAppPanel} onCreate={handleShowFromTryApp} />)}{showDSLConfirmModal && (@@ -200,12 +193,16 @@ const AppsContent = () => {{isShowCreateModal && (<CreateAppModal- appIconType={currApp?.app.icon_type || 'emoji'}- appIcon={currApp?.app.icon || ''}- appIconBackground={currApp?.app.icon_background || ''}- appIconUrl={currApp?.app.icon_url}- appName={currApp?.app.name || ''}- appDescription={currApp?.app.description || ''}+ appIconType={+ currApp?.app?.icon_type === 'image' || currApp?.app?.icon_type === 'link'+ ? currApp.app.icon_type+ : 'emoji'+ }+ appIcon={currApp?.app?.icon ?? ''}+ appIconBackground={currApp?.app?.icon_background ?? ''}+ appIconUrl={currApp?.app?.icon_url}+ appName={currApp?.app?.name ?? ''}+ appDescription=""showonConfirm={onCreate}confirmDisabled={isFetching}diff --git a/web/app/components/apps/list.tsx b/web/app/components/apps/list.tsxindex c09ad1de941..69e9b9ab0c0 100644--- a/web/app/components/apps/list.tsx+++ b/web/app/components/apps/list.tsx@@ -1,10 +1,9 @@'use client'import type { GetAppsData } from '@dify/contracts/api/console/apps/types.gen'+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import type { AppListCreationDialog } from './app-list-creation-modals'import type { AppListUrlQuery } from './query-params'-import type { App } from '@/models/explore'-import type { TryAppSelection } from '@/types/try-app'import {ScrollArea,ScrollAreaContent,@@ -32,8 +31,8 @@ type AppListSortBy = NonNullable<AppListQuery['sort_by']>type AppListCategory = AppListUrlQuery['category']type Props = Readonly<{- onCreateLearnDify?: (app: App) => void- onTryLearnDify?: (params: TryAppSelection) => void+ onCreateLearnDify?: (app: RecommendedAppResponse) => void+ onTryLearnDify?: (app: RecommendedAppResponse) => void}>export function List({ onCreateLearnDify, onTryLearnDify }: Props) {diff --git a/web/app/components/explore/__tests__/category.spec.tsx b/web/app/components/explore/__tests__/category.spec.tsxindex feef68fbb97..d2140497a36 100644--- a/web/app/components/explore/__tests__/category.spec.tsx+++ b/web/app/components/explore/__tests__/category.spec.tsx@@ -1,5 +1,5 @@-import type { AppCategory } from '@/models/explore'-import { fireEvent, render, screen } from '@testing-library/react'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'import Category from '../category'describe('Category', () => {@@ -7,7 +7,7 @@ describe('Category', () => {const renderComponent = (overrides: Partial<React.ComponentProps<typeof Category>> = {}) => {const props: React.ComponentProps<typeof Category> = {- list: ['Writing', 'Recommended'] as AppCategory[],+ list: ['Writing', 'Recommended'],value: allCategoriesEn,onChange: vi.fn(),allCategoriesEn,@@ -36,18 +36,20 @@ describe('Category', () => {})describe('Props', () => {- it('should call onChange with category value when category item is clicked', () => {+ it('should call onChange with category value when category item is clicked', async () => {+ const user = userEvent.setup()const { props } = renderComponent()- fireEvent.click(screen.getByText('explore.category.Writing'))+ await user.click(screen.getByText('explore.category.Writing'))expect(props.onChange).toHaveBeenCalledWith('Writing')})- it('should call onChange with allCategoriesEn when all categories is clicked', () => {+ it('should call onChange with allCategoriesEn when all categories is clicked', async () => {+ const user = userEvent.setup()const { props } = renderComponent({ value: 'Writing' })- fireEvent.click(screen.getByText('explore.apps.allCategories'))+ await user.click(screen.getByText('explore.apps.allCategories'))expect(props.onChange).toHaveBeenCalledWith(allCategoriesEn)})@@ -62,7 +64,7 @@ describe('Category', () => {})it('should render raw category name when i18n key does not exist', () => {- renderComponent({ list: ['CustomCategory', 'Recommended'] as AppCategory[] })+ renderComponent({ list: ['CustomCategory', 'Recommended'] })expect(screen.getByText('CustomCategory')).toBeInTheDocument()})@@ -72,9 +74,9 @@ describe('Category', () => {it('should render categories as a radio group', () => {renderComponent({ value: 'Writing' })- expect(screen.getByRole('radiogroup', { name: 'explore.tryApp.category' })).toHaveClass(- 'bg-transparent',- )+ expect(+ screen.getByRole('radiogroup', { name: 'explore.tryApp.category' }),+ ).toBeInTheDocument()expect(screen.getByRole('radio', { name: /explore\.apps\.allCategories/ })).toHaveAttribute('aria-checked','false',diff --git a/web/app/components/explore/catalog.md b/web/app/components/explore/catalog.mdnew file mode 100644index 00000000000..68adc069f2f--- /dev/null+++ b/web/app/components/explore/catalog.md@@ -0,0 +1,71 @@+# Explore catalog contract++## Ownership and scope++The recommendation catalog is owned by+`api/controllers/console/explore/recommended_app.py`, with query behavior in+`api/services/recommended_app_query_service.py` and source selection/fallback in+`api/services/recommended_app_catalog_gateway.py`. The generated Explore contract+is the frontend request and response owner. Use `RecommendedAppResponse` directly+for card props and selected templates; do not restore the removed Explore DTOs,+normalizers, fetchers, or forwarding hooks.++This module covers recommended apps, Learn Dify apps, recommendation detail, and+the installed-app lookup used by the app-card navigation action. Trial execution,+installed-app management, catalog banners, and DSL import orchestration retain+their own owners.++## Query and action decisions++| Entry point | Policy and reason |+| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Home server prefetch and client list | The generated recommended-app key includes the requested language. Both sides cache the same raw response. Pending dehydration remains owned by the shared QueryClient. |+| Template chooser | Uses the same generated recommended-app options and language input. Inherits the five-minute freshness default, so a fresh Home cache is reused. |+| Learn Dify | Uses the generated Learn Dify operation with explicit language. The feature gate and dismissed section control mounting; hidden content does not fetch. |+| List sorting and filtering | The consuming observer or render owner copies rows before sorting by `position ?? 0`. Learn Dify limits rows after sorting. No consumer rewrites the canonical cache into a view model. |+| Template chooser and Apps create actions | Call the generated detail client each time the user confirms. This preserves the previous always-network behavior without adding a query retry or stale-cache policy. |+| Home create action | Retains its existing generated detail query with `staleTime: 'static'`. This separate call-site decision is unchanged. |+| Open installed app | The generated installed-app client runs inside `openAsyncWindow`'s URL resolver. The window opens during user activation, the published-workflow gate is retained, and the first returned installed ID determines navigation. |++The catalog has no writes and therefore adds no mutation invalidation policy.+Importing a template changes workspace apps, not the recommendation catalog.+Existing DSL import policies continue to refresh the affected app surfaces.+Local confirmation, tracking, toast, and navigation remain with the creation+workflow; they do not override shared import cache behavior.++The two migrated creation actions catch detail and import failures together.+A failed detail request must not import a DSL or navigate. The shared create+modal keeps its existing immediate-close-on-submit behavior; this migration does+not change that component's submission lifecycle. The installed-app action keeps+its existing empty-result and failure feedback.++## TypeScript and display boundaries++The API intentionally permits nullable nested app metadata and arbitrary string+`mode` and `icon_type` values because catalog sources include remote data. Keep+those generated types intact. Use the required top-level `app_id` for detail+identity even when nested app metadata is absent or has another ID.++Narrow icon values where they enter the icon primitive or controlled creation+form. Use optional access and local string defaults for rendered labels and+controlled inputs. Unknown modes remain visible in the unfiltered catalog and+match no specific mode filter. Optional categories are an empty set for filtering;+missing names do not match a nonempty name search. Keep server category order.++The removed normalizer fabricated nested description and answer-icon values.+The template chooser and Apps creation forms preserve their prior empty initial+description and false answer-icon default locally. Home retains its existing+catalog-level description. These are UI decisions, not extra API fields.++Use inference from generated options instead of manually assigning query result+generics, casting server strings to frontend enums, or adding a second transport+response type. Observer `select` may project data for rendering; it must not+change the raw cache contract or mutate the response arrays.++## Verification++Consumer tests exercise locale identity, cache reuse, sorting without mutation,+nullable metadata, selection, and creation/navigation failures through generated+transport and a real QueryClient. Existing Home tests protect its static detail+policy and preview/tour behavior. The backend controller, query service, catalog+router, and repository tests protect fallback and nullability semantics.diff --git a/web/app/components/explore/category.tsx b/web/app/components/explore/category.tsxindex 777d58a9b2d..687b46b6bbe 100644--- a/web/app/components/explore/category.tsx+++ b/web/app/components/explore/category.tsx@@ -1,5 +1,4 @@'use client'-import type { AppCategory } from '@/models/explore'import { cn } from '@langgenius/dify-ui/cn'import { RadioGroup, RadioItem } from '@langgenius/dify-ui/radio-group'import { useTranslation } from 'react-i18next'@@ -7,9 +6,9 @@ import exploreI18n from '@/i18n/locales/en-US/explore.json'type ICategoryProps = {className?: string- list: AppCategory[]+ list: string[]value: string- onChange: (value: AppCategory | string) => void+ onChange: (value: string) => void/*** default value for search param 'category' in en*/@@ -18,10 +17,10 @@ type ICategoryProps = {function Category({ className, list, value, onChange, allCategoriesEn }: ICategoryProps) {const { t } = useTranslation()- const isAllCategories = !list.includes(value as AppCategory) || value === allCategoriesEn+ const isAllCategories = !list.includes(value) || value === allCategoriesEnconst selectedCategory = isAllCategories ? allCategoriesEn : value- const renderCategoryName = (name: AppCategory) => {+ const renderCategoryName = (name: string) => {const categoryKey = `category.${name}` as keyof typeof exploreI18nreturn categoryKey in exploreI18n ? t(($) => $[categoryKey], { ns: 'explore' }) : name}diff --git a/web/app/components/explore/learn-dify/__tests__/index.spec.tsx b/web/app/components/explore/learn-dify/__tests__/index.spec.tsxindex d26cac9b4b5..437c5cac3f4 100644--- a/web/app/components/explore/learn-dify/__tests__/index.spec.tsx+++ b/web/app/components/explore/learn-dify/__tests__/index.spec.tsx@@ -1,104 +1,134 @@-import type { App } from '@/models/explore'-import { render, screen } from '@testing-library/react'+import type {+ GetExploreAppsLearnDifyResponse,+ RecommendedAppResponse,+} from '@dify/contracts/api/console/explore/types.gen'+import { act, screen, waitFor } from '@testing-library/react'import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'-import { createConsoleQueryWrapper } from '@/test/console/query-data'-import { AppModeEnum } from '@/types/app'+import { consoleQuery } from '@/service/console'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'import LearnDify from '../index'import { LEARN_DIFY_HIDDEN_STORAGE_KEY } from '../storage'-let mockLearnDifyApps: App[] = []-let mockLearnDifyLoading = false--vi.mock('@/service/use-explore', () => ({- useLearnDifyAppList: () => ({- data: mockLearnDifyApps,- isLoading: mockLearnDifyLoading,- }),+const { request, locale } = vi.hoisted(() => ({+ request: vi.fn(),+ locale: { value: 'en-US' },+}))+vi.mock('@/service/base', () => ({ request }))+vi.mock('#i18n', async (importOriginal) => ({+ ...(await importOriginal<typeof import('#i18n')>()),+ useLocale: () => locale.value,}))-const createApp = (overrides: Partial<App> = {}): App => ({- app: {- id: overrides.app?.id ?? 'app-basic-id',- mode: overrides.app?.mode ?? AppModeEnum.CHAT,- icon_type: overrides.app?.icon_type ?? 'emoji',- icon: overrides.app?.icon ?? '😀',- icon_background: overrides.app?.icon_background ?? '#fff',- icon_url: overrides.app?.icon_url ?? '',- name: overrides.app?.name ?? 'Learn Dify App',- description: overrides.app?.description ?? 'Learn Dify description',- use_icon_as_answer_icon: overrides.app?.use_icon_as_answer_icon ?? false,- },- can_trial: overrides.can_trial ?? true,- app_id: overrides.app_id ?? 'learn-dify-app',- description: overrides.description ?? 'Learn Dify description',- copyright: overrides.copyright ?? '',- privacy_policy: overrides.privacy_policy ?? null,- custom_disclaimer: overrides.custom_disclaimer ?? null,- categories: overrides.categories ?? ['Writing'],- position: overrides.position ?? 1,- is_listed: overrides.is_listed ?? true,- install_count: overrides.install_count ?? 0,- installed: overrides.installed ?? false,- editable: overrides.editable ?? false,- is_agent: overrides.is_agent ?? false,+const createApp = (name: string, position: number | null = 1): RecommendedAppResponse => ({+ app_id: name,+ app: { id: name, name, icon_url: null },+ can_trial: false,+ position,})-const renderLearnDify = ({- enableLearnApp = true,- forceVisible = false,-}: {- enableLearnApp?: boolean- forceVisible?: boolean-} = {}) => {- const { wrapper } = createConsoleQueryWrapper({- systemFeatures: {- enable_learn_app: enableLearnApp,- },- })-- return render(- <LearnDify forceVisible={forceVisible} stepByStepTourTarget={STEP_BY_STEP_TOUR_TARGETS.home} />,- { wrapper },+beforeEach(() => {+ vi.clearAllMocks()+ localStorage.clear()+ locale.value = 'en-US'+ request.mockImplementation(async () =>+ Response.json({ recommended_apps: [createApp('Learn Dify App')] }),)-}--describe('LearnDify', () => {- beforeEach(() => {- vi.clearAllMocks()- localStorage.clear()- mockLearnDifyApps = [createApp()]- mockLearnDifyLoading = false- })+})- it('should stay hidden when the user hidden preference is set', () => {+describe('Learn Dify catalog', () => {+ it('does not fetch hidden content until the step tour forces it visible', async () => {localStorage.setItem(LEARN_DIFY_HIDDEN_STORAGE_KEY, 'true')-- renderLearnDify()+ const { rerender } = render(<LearnDify />, {+ systemFeatures: { enable_learn_app: true },+ })expect(screen.queryByRole('heading', { name: 'explore.learnDify.title' }),).not.toBeInTheDocument()+ expect(request).not.toHaveBeenCalled()+ rerender(<LearnDify forceVisible stepByStepTourTarget={STEP_BY_STEP_TOUR_TARGETS.home} />)++ const section = await screen.findByRole('region', { name: 'explore.learnDify.title' })+ expect(section).toHaveAttribute('data-step-by-step-tour-target', STEP_BY_STEP_TOUR_TARGETS.home)+ expect(screen.queryByRole('button', { name: 'explore.learnDify.hide' })).not.toBeInTheDocument()+ expect(request).toHaveBeenCalledTimes(1)})- it('should show hidden content when forceVisible is set for the step tour', () => {- localStorage.setItem(LEARN_DIFY_HIDDEN_STORAGE_KEY, 'true')+ it('does not fetch when the system feature is disabled, even if visibility is forced', () => {+ render(<LearnDify forceVisible />, { systemFeatures: { enable_learn_app: false } })- renderLearnDify({ forceVisible: true })+ expect(+ screen.queryByRole('heading', { name: 'explore.learnDify.title' }),+ ).not.toBeInTheDocument()+ expect(request).not.toHaveBeenCalled()+ })- const learnDifyHeading = screen.getByRole('heading', { name: 'explore.learnDify.title' })- expect(learnDifyHeading).toBeInTheDocument()- expect(learnDifyHeading.closest('section')).toHaveAttribute(- 'data-step-by-step-tour-target',- STEP_BY_STEP_TOUR_TARGETS.home,+ it('sorts before limiting visible items while retaining the raw response in the generated cache', async () => {+ const response: GetExploreAppsLearnDifyResponse = {+ recommended_apps: [+ createApp('Last', 5),+ createApp('Null position', null),+ createApp('Zero position', 0),+ createApp('First', -1),+ ],+ }+ request.mockImplementation(async () => Response.json(response))+ const { queryClient } = render(<LearnDify dismissible={false} itemLimit={3} />, {+ systemFeatures: { enable_learn_app: true },+ })++ await screen.findByRole('heading', { name: 'First' })+ expect(+ screen.getAllByRole('heading', { level: 3 }).map((heading) => heading.textContent),+ ).toEqual(['First', 'Null position', 'Zero position'])+ expect(screen.queryByRole('heading', { name: 'Last' })).not.toBeInTheDocument()+ const cached = queryClient.getQueryData(+ consoleQuery.explore.apps.learnDify.get.queryOptions({+ input: { query: { language: 'en-US' } },+ }).queryKey,)- expect(screen.queryByRole('button', { name: 'explore.learnDify.hide' })).not.toBeInTheDocument()+ expect(cached).toEqual(response)})- it('should keep Learn Dify hidden when the system feature is disabled', () => {- localStorage.setItem(LEARN_DIFY_HIDDEN_STORAGE_KEY, 'true')+ it('keeps each requested locale in its own generated cache entry', async () => {+ const requestedLocales: Array<string | null> = []+ request.mockImplementation(async (url: string) => {+ const language = new URL(url).searchParams.get('language')+ requestedLocales.push(language)+ return Response.json({+ recommended_apps: [createApp(language === 'pt-BR' ? 'Português' : 'English')],+ })+ })+ const { rerender } = render(<LearnDify dismissible={false} title="English catalog" />, {+ systemFeatures: { enable_learn_app: true },+ })+ expect(await screen.findByRole('heading', { name: 'English' })).toBeInTheDocument()++ locale.value = 'pt-BR'+ rerender(<LearnDify dismissible={false} title="Portuguese catalog" />)+ expect(await screen.findByRole('heading', { name: 'Português' })).toBeInTheDocument()+ expect(screen.queryByRole('heading', { name: 'English' })).not.toBeInTheDocument()- renderLearnDify({ enableLearnApp: false, forceVisible: true })+ locale.value = 'en-US'+ rerender(<LearnDify dismissible={false} title="English catalog" />)+ expect(await screen.findByRole('heading', { name: 'English' })).toBeInTheDocument()+ expect(requestedLocales).toEqual(['en-US', 'pt-BR'])+ })++ it('shows the supplied loading fallback until the request resolves, then leaves an empty catalog hidden', async () => {+ let resolveResponse!: (response: Response) => void+ request.mockReturnValue(+ new Promise<Response>((resolve) => {+ resolveResponse = resolve+ }),+ )+ render(<LearnDify loadingFallback={<div role="status">Loading lessons</div>} />, {+ systemFeatures: { enable_learn_app: true },+ })+ expect(screen.getByRole('status')).toHaveTextContent('Loading lessons')+ await act(async () => resolveResponse(Response.json({ recommended_apps: [] })))+ await waitFor(() => expect(screen.queryByRole('status')).not.toBeInTheDocument())expect(screen.queryByRole('heading', { name: 'explore.learnDify.title' }),).not.toBeInTheDocument()diff --git a/web/app/components/explore/learn-dify/__tests__/item.spec.tsx b/web/app/components/explore/learn-dify/__tests__/item.spec.tsxindex c3d2f6287e4..f785d5cdcdf 100644--- a/web/app/components/explore/learn-dify/__tests__/item.spec.tsx+++ b/web/app/components/explore/learn-dify/__tests__/item.spec.tsx@@ -1,6 +1,6 @@+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'import type { ReactElement } from 'react'-import type { App } from '@/models/explore'import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { trackEvent } from '@/app/components/base/amplitude'@@ -16,31 +16,22 @@ vi.mock('@/app/components/base/amplitude', () => ({trackEvent: vi.fn(),}))-const createApp = (overrides: Partial<App> = {}): App => ({+const createApp = (overrides: Partial<RecommendedAppResponse> = {}): RecommendedAppResponse => ({app: {- id: overrides.app?.id ?? 'app-basic-id',- mode: overrides.app?.mode ?? AppModeEnum.CHAT,- icon_type: overrides.app?.icon_type ?? 'emoji',- icon: overrides.app?.icon ?? '😀',- icon_background: overrides.app?.icon_background ?? '#fff',- icon_url: overrides.app?.icon_url ?? '',- name: overrides.app?.name ?? 'Learn Dify App',- description: overrides.app?.description ?? 'Learn Dify description',- use_icon_as_answer_icon: overrides.app?.use_icon_as_answer_icon ?? false,+ id: 'app-basic-id',+ mode: AppModeEnum.CHAT,+ icon_type: 'emoji',+ icon: '😀',+ icon_background: '#fff',+ icon_url: '',+ name: 'Learn Dify App',},- can_trial: overrides.can_trial ?? true,- app_id: overrides.app_id ?? 'learn-dify-app',- description: overrides.description ?? 'Learn Dify description',- copyright: overrides.copyright ?? '',- privacy_policy: overrides.privacy_policy ?? null,- custom_disclaimer: overrides.custom_disclaimer ?? null,- categories: overrides.categories ?? ['Writing'],- position: overrides.position ?? 1,- is_listed: overrides.is_listed ?? true,- install_count: overrides.install_count ?? 0,- installed: overrides.installed ?? false,- editable: overrides.editable ?? false,- is_agent: overrides.is_agent ?? false,+ can_trial: true,+ app_id: 'learn-dify-app',+ description: 'Learn Dify description',+ categories: ['Writing'],+ position: 1,+ ...overrides,})describe('LearnDifyItem', () => {@@ -89,11 +80,11 @@ describe('LearnDifyItem', () => {await user.click(screen.getByRole('button', { name: 'Learn Dify App' }))- expect(onTry).toHaveBeenCalledWith({ appId: app.app_id, app })+ expect(onTry).toHaveBeenCalledWith(app)expect(mockTrackEvent).toHaveBeenCalledWith('preview_template', {template_id: app.app_id,- template_name: app.app.name,- template_mode: app.app.mode,+ template_name: app.app?.name,+ template_mode: app.app?.mode,template_categories: app.categories,page: 'explore',})@@ -113,6 +104,29 @@ describe('LearnDifyItem', () => {card.focus()await user.keyboard('{Enter}')- expect(onTry).toHaveBeenCalledWith({ appId: app.app_id, app })+ expect(onTry).toHaveBeenCalledWith(app)+ })++ it('keeps nullable catalog metadata raw when previewing a card', async () => {+ const app: RecommendedAppResponse = {+ app_id: 'nullable-app',+ app: null,+ can_trial: true,+ description: null,+ }+ const onTry = vi.fn()+ const user = userEvent.setup()++ render(<LearnDifyItem canCreate={false} item={app} onTry={onTry} />)+ await user.click(screen.getByRole('button'))++ expect(onTry).toHaveBeenCalledWith(app)+ expect(mockTrackEvent).toHaveBeenCalledWith('preview_template', {+ template_id: 'nullable-app',+ template_name: '',+ template_mode: '',+ template_categories: [],+ page: 'explore',+ })})})diff --git a/web/app/components/explore/learn-dify/index.tsx b/web/app/components/explore/learn-dify/index.tsxindex ef1fb730ea3..4ec7d880206 100644--- a/web/app/components/explore/learn-dify/index.tsx+++ b/web/app/components/explore/learn-dify/index.tsx@@ -1,15 +1,15 @@'use client'-import type { App } from '@/models/explore'-import type { TryAppSelection } from '@/types/try-app'+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import { cn } from '@langgenius/dify-ui/cn'-import { useSuspenseQuery } from '@tanstack/react-query'+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'import * as React from 'react'import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'+import { useLocale } from '#i18n'import { MAIN_NAV_APP_CARD_GRID_CLASS_NAME } from '@/app/components/main-nav/app-card-grid'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import { useLearnDifyAppList } from '@/service/use-explore'+import { consoleQuery } from '@/service/console'import LearnDifyItem from './item'import { useLearnDifyHiddenValue, useSetLearnDifyHidden } from './storage'@@ -20,8 +20,8 @@ type LearnDifyProps = {forceVisible?: booleanitemLimit?: numberloadingFallback?: React.ReactNode- onCreate?: (app: App) => void- onTry?: (params: TryAppSelection) => void+ onCreate?: (app: RecommendedAppResponse) => void+ onTry?: (app: RecommendedAppResponse) => voidshowDescription?: booleanstepByStepTourTarget?: stringtitle?: string@@ -44,11 +44,18 @@ const LearnDifyContent = ({title,}: LearnDifyContentProps) => {const { t } = useTranslation()+ const locale = useLocale()const [isClosing, setIsClosing] = useState(false)const [collapseTransform, setCollapseTransform] = useState<string>()const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)const sectionRef = useRef<HTMLElement>(null)- const { data: learnDifyItems = [], isLoading } = useLearnDifyAppList()+ const { data: learnDifyItems = [], isLoading } = useQuery(+ consoleQuery.explore.apps.learnDify.get.queryOptions({+ input: { query: { language: locale } },+ select: (response) =>+ [...response.recommended_apps].sort((a, b) => (a.position ?? 0) - (b.position ?? 0)),+ }),+ )useEffect(() => {return () => {diff --git a/web/app/components/explore/learn-dify/item.tsx b/web/app/components/explore/learn-dify/item.tsxindex 8d5c6a36f6a..17041b0853b 100644--- a/web/app/components/explore/learn-dify/item.tsx+++ b/web/app/components/explore/learn-dify/item.tsx@@ -1,7 +1,6 @@'use client'-import type { App } from '@/models/explore'-import type { TryAppSelection } from '@/types/try-app'+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import { cn } from '@langgenius/dify-ui/cn'import { useSuspenseQuery } from '@tanstack/react-query'import * as React from 'react'@@ -11,9 +10,9 @@ import { systemFeaturesQueryOptions } from '@/features/system-features/client'type LearnDifyItemProps = {canCreate: boolean- item: App- onCreate?: (app: App) => void- onTry?: (params: TryAppSelection) => void+ item: RecommendedAppResponse+ onCreate?: (app: RecommendedAppResponse) => void+ onTry?: (app: RecommendedAppResponse) => void}const LearnDifyItem = ({ canCreate, item, onCreate, onTry }: LearnDifyItemProps) => {@@ -24,6 +23,14 @@ const LearnDifyItem = ({ canCreate, item, onCreate, onTry }: LearnDifyItemProps)const appNameId = React.useId()const appDescriptionId = React.useId()const appBasicInfo = item.app+ const appName = appBasicInfo?.name ?? ''+ const appMode = appBasicInfo?.mode ?? ''+ const appIconType =+ appBasicInfo?.icon_type === 'image' ||+ appBasicInfo?.icon_type === 'emoji' ||+ appBasicInfo?.icon_type === 'link'+ ? appBasicInfo.icon_type+ : nullconst canViewApp = deploymentEdition === 'CLOUD'const canShowCreate = canCreate && !!onCreateconst isClickable = canViewApp || canShowCreate@@ -31,12 +38,12 @@ const LearnDifyItem = ({ canCreate, item, onCreate, onTry }: LearnDifyItemProps)const handleTryApp = () => {trackEvent('preview_template', {template_id: item.app_id,- template_name: appBasicInfo.name,- template_mode: appBasicInfo.mode,- template_categories: item.categories,+ template_name: appName,+ template_mode: appMode,+ template_categories: item.categories ?? [],page: 'explore',})- onTry?.({ appId: item.app_id, app: item })+ onTry?.(item)}const handleCardClick = () => {if (canViewApp) {@@ -67,13 +74,13 @@ const LearnDifyItem = ({ canCreate, item, onCreate, onTry }: LearnDifyItemProps)<AppIcondecorativesize="large"- iconType={appBasicInfo.icon_type}- icon={appBasicInfo.icon}- background={appBasicInfo.icon_background}- imageUrl={appBasicInfo.icon_url}+ iconType={appIconType}+ icon={appBasicInfo?.icon ?? ''}+ background={appBasicInfo?.icon_background ?? ''}+ imageUrl={appBasicInfo?.icon_url ?? ''}/><h3 id={appNameId} className="w-full truncate system-md-semibold text-text-secondary">- {appBasicInfo.name}+ {appName}</h3></div><pdiff --git a/web/app/components/explore/try-app/__tests__/index.spec.tsx b/web/app/components/explore/try-app/__tests__/index.spec.tsxindex bc67cb08007..dc36dcfc2b5 100644--- a/web/app/components/explore/try-app/__tests__/index.spec.tsx+++ b/web/app/components/explore/try-app/__tests__/index.spec.tsx@@ -1,18 +1,18 @@+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import type { ComponentProps } from 'react'-import type { App as ExploreApp } from '@/models/explore'import type { TryAppInfo } from '@/service/try-app'import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'import TryAppComponent from '../index'import { TypeEnum } from '../types'-const defaultApp = { can_trial: true } as ExploreApp+const defaultApp: RecommendedAppResponse = { app_id: 'test-app-id', can_trial: true }function TryApp({app = defaultApp,...props}: Omit<ComponentProps<typeof TryAppComponent>, 'app'> & {- app?: ExploreApp+ app?: RecommendedAppResponse}) {return <TryAppComponent {...props} app={app} />}@@ -121,7 +121,7 @@ describe('TryApp (main index.tsx)', () => {isLoading: true,})- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp onClose={vi.fn()} onCreate={vi.fn()} />)expect(screen.queryByRole('progressbar')).toBeInTheDocument()})@@ -133,7 +133,7 @@ describe('TryApp (main index.tsx)', () => {error: new Error('App is unavailable'),})- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp onClose={vi.fn()} onCreate={vi.fn()} />)expect(screen.getByText('App is unavailable')).toBeInTheDocument()})@@ -145,7 +145,7 @@ describe('TryApp (main index.tsx)', () => {isError: false,})- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp onClose={vi.fn()} onCreate={vi.fn()} />)expect(screen.getByText('share.common.appUnknownError')).toBeInTheDocument()})@@ -153,17 +153,17 @@ describe('TryApp (main index.tsx)', () => {describe('content rendering', () => {it('uses app trial eligibility as the authoritative default tab', async () => {- const app = { can_trial: true } as ExploreApp+ const app: RecommendedAppResponse = { app_id: 'test-app-id', can_trial: true }- render(<TryApp appId="test-app-id" app={app} onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp app={app} onClose={vi.fn()} onCreate={vi.fn()} />)expect(await screen.findByTestId('app-component')).toBeInTheDocument()})it('defaults to details and disables trial when the app is ineligible', async () => {- const app = { can_trial: false } as ExploreApp+ const app: RecommendedAppResponse = { app_id: 'test-app-id', can_trial: false }- render(<TryApp appId="test-app-id" app={app} onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp app={app} onClose={vi.fn()} onCreate={vi.fn()} />)expect(await screen.findByTestId('preview-component')).toBeInTheDocument()expect(screen.getByRole('tab', { name: 'explore.tryApp.tabHeader.try' })).toHaveAttribute(@@ -173,7 +173,7 @@ describe('TryApp (main index.tsx)', () => {})it('renders Tab component', async () => {- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp onClose={vi.fn()} onCreate={vi.fn()} />)await waitFor(() => {expect(screen.getByText('explore.tryApp.tabHeader.try')).toBeInTheDocument()@@ -182,7 +182,7 @@ describe('TryApp (main index.tsx)', () => {})it('renders App component by default (TRY mode)', async () => {- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp onClose={vi.fn()} onCreate={vi.fn()} />)await waitFor(() => {expect(document.body.querySelector('[data-testid="app-component"]')).toBeInTheDocument()@@ -193,7 +193,7 @@ describe('TryApp (main index.tsx)', () => {})it('renders AppInfo component', async () => {- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp onClose={vi.fn()} onCreate={vi.fn()} />)await waitFor(() => {expect(@@ -203,7 +203,7 @@ describe('TryApp (main index.tsx)', () => {})it('renders close button', async () => {- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp onClose={vi.fn()} onCreate={vi.fn()} />)await waitFor(() => {expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeInTheDocument()@@ -213,7 +213,7 @@ describe('TryApp (main index.tsx)', () => {describe('tab switching', () => {it('switches to Preview when Detail tab is clicked', async () => {- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp onClose={vi.fn()} onCreate={vi.fn()} />)await waitFor(() => {expect(screen.getByText('explore.tryApp.tabHeader.detail')).toBeInTheDocument()@@ -228,7 +228,7 @@ describe('TryApp (main index.tsx)', () => {})it('switches back to App when Try tab is clicked', async () => {- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp onClose={vi.fn()} onCreate={vi.fn()} />)await waitFor(() => {expect(screen.getByText('explore.tryApp.tabHeader.detail')).toBeInTheDocument()@@ -252,7 +252,7 @@ describe('TryApp (main index.tsx)', () => {it('calls onClose when close button is clicked', async () => {const mockOnClose = vi.fn()- render(<TryApp appId="test-app-id" onClose={mockOnClose} onCreate={vi.fn()} />)+ render(<TryApp onClose={mockOnClose} onCreate={vi.fn()} />)await waitFor(() => {expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeInTheDocument()@@ -266,7 +266,7 @@ describe('TryApp (main index.tsx)', () => {it('calls onClose when the dialog requests close', async () => {const mockOnClose = vi.fn()- render(<TryApp appId="test-app-id" onClose={mockOnClose} onCreate={vi.fn()} />)+ render(<TryApp onClose={mockOnClose} onCreate={vi.fn()} />)await waitFor(() => {expect(screen.getByRole('dialog')).toBeInTheDocument()@@ -282,7 +282,7 @@ describe('TryApp (main index.tsx)', () => {it('calls onCreate when create button in AppInfo is clicked', async () => {const mockOnCreate = vi.fn()- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={mockOnCreate} />)+ render(<TryApp onClose={vi.fn()} onCreate={mockOnCreate} />)await waitFor(() => {const createButton = document.body.querySelector('[data-testid="create-button"]')@@ -295,12 +295,11 @@ describe('TryApp (main index.tsx)', () => {})})- describe('categories prop', () => {- it('passes categories to AppInfo when provided', async () => {+ describe('catalog categories', () => {+ it('uses the selected catalog app categories', async () => {render(<TryApp- appId="test-app-id"- categories={['AI Assistant', 'Workflow']}+ app={{ ...defaultApp, categories: ['AI Assistant', 'Workflow'] }}onClose={vi.fn()}onCreate={vi.fn()}/>,@@ -312,19 +311,29 @@ describe('TryApp (main index.tsx)', () => {})})- it('does not pass categories to AppInfo when not provided', async () => {- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ it('uses an empty category list when the catalog does not provide categories', async () => {+ render(<TryApp onClose={vi.fn()} onCreate={vi.fn()} />)await waitFor(() => {const appInfo = document.body.querySelector('[data-testid="app-info-component"]')- expect(appInfo).not.toHaveAttribute('data-categories', expect.any(String))+ expect(appInfo).toHaveAttribute('data-categories', '')})})})describe('hook calls', () => {- it('calls useGetTryAppInfo with correct appId', () => {- render(<TryApp appId="my-specific-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ it('requests the canonical catalog app ID when nested metadata has another ID', () => {+ render(+ <TryApp+ app={{+ ...defaultApp,+ app_id: 'my-specific-app-id',+ app: { id: 'different-nested-id', icon_url: null },+ }}+ onClose={vi.fn()}+ onCreate={vi.fn()}+ />,+ )expect(mockUseGetTryAppInfo).toHaveBeenCalledWith('my-specific-app-id')})@@ -332,7 +341,13 @@ describe('TryApp (main index.tsx)', () => {describe('props passing', () => {it('passes appId to App component', async () => {- render(<TryApp appId="my-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(+ <TryApp+ app={{ ...defaultApp, app_id: 'my-app-id' }}+ onClose={vi.fn()}+ onCreate={vi.fn()}+ />,+ )await waitFor(() => {const appComponent = document.body.querySelector('[data-testid="app-component"]')@@ -341,7 +356,13 @@ describe('TryApp (main index.tsx)', () => {})it('passes appId to Preview component when in Detail mode', async () => {- render(<TryApp appId="my-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(+ <TryApp+ app={{ ...defaultApp, app_id: 'my-app-id' }}+ onClose={vi.fn()}+ onCreate={vi.fn()}+ />,+ )await waitFor(() => {expect(screen.getByText('explore.tryApp.tabHeader.detail')).toBeInTheDocument()@@ -356,7 +377,13 @@ describe('TryApp (main index.tsx)', () => {})it('passes appId to AppInfo component', async () => {- render(<TryApp appId="my-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(+ <TryApp+ app={{ ...defaultApp, app_id: 'my-app-id' }}+ onClose={vi.fn()}+ onCreate={vi.fn()}+ />,+ )await waitFor(() => {const appInfoComponent = document.body.querySelector('[data-testid="app-info-component"]')@@ -365,7 +392,7 @@ describe('TryApp (main index.tsx)', () => {})it('passes appDetail to AppInfo component', async () => {- render(<TryApp appId="test-app-id" onClose={vi.fn()} onCreate={vi.fn()} />)+ render(<TryApp onClose={vi.fn()} onCreate={vi.fn()} />)await waitFor(() => {const appInfoComponent = document.body.querySelector('[data-testid="app-info-component"]')diff --git a/web/app/components/explore/try-app/index.tsx b/web/app/components/explore/try-app/index.tsxindex 99708fba984..4c66b62a99b 100644--- a/web/app/components/explore/try-app/index.tsx+++ b/web/app/components/explore/try-app/index.tsx@@ -15,25 +15,22 @@ import Preview from './preview'import { TypeEnum } from './types'type Props = Readonly<{- appId: stringapp: RecommendedAppResponsecanCreate?: boolean- categories?: string[]createButtonStepByStepTourTarget?: stringonClose: () => voidonCreate: () => void}>function TryApp({- appId,app,canCreate = true,- categories,createButtonStepByStepTourTarget,onClose,onCreate,}: Props) {const { t } = useTranslation()+ const appId = app.app_idconst canUseTryTab = app.can_trialconst [type, setType] = useState<TypeEnum>(() => (canUseTryTab ? TypeEnum.TRY : TypeEnum.DETAIL))const activeType = canUseTryTab ? type : TypeEnum.DETAIL@@ -111,7 +108,7 @@ function TryApp({appDetail={appDetail}appId={appId}canCreate={canCreate}- categories={categories}+ categories={app.categories ?? []}createButtonStepByStepTourTarget={createButtonStepByStepTourTarget}onCreate={onCreate}/>diff --git a/web/context/app-list-context.ts b/web/context/app-list-context.tsindex ed9f548ef34..6d131c75cb2 100644--- a/web/context/app-list-context.ts+++ b/web/context/app-list-context.ts@@ -1,9 +1,9 @@-import type { TryAppSelection } from '@/types/try-app'+import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'import { noop } from 'es-toolkit/function'import { createContext } from 'use-context-selector'type Props = Readonly<{- openTryAppPanel: (selection: TryAppSelection) => void+ openTryAppPanel: (app: RecommendedAppResponse) => void}>const AppListContext = createContext<Props>({diff --git a/web/features/home/home-content/__tests__/home-content.spec.tsx b/web/features/home/home-content/__tests__/home-content.spec.tsxindex ed6f4d83801..7466a7e4cd3 100644--- a/web/features/home/home-content/__tests__/home-content.spec.tsx+++ b/web/features/home/home-content/__tests__/home-content.spec.tsx@@ -1,6 +1,7 @@import type { RecentAppResponse } from '@dify/contracts/api/console/apps/types.gen'import type {BannerResponse,+ RecommendedAppDetailResponse,RecommendedAppInfoResponse,RecommendedAppResponse,} from '@dify/contracts/api/console/explore/types.gen'@@ -23,6 +24,7 @@ import {stepByStepTourSessionAtom,} from '@/app/components/step-by-step-tour/state'import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'+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'@@ -64,7 +66,9 @@ const mockHandleImportDSL = vi.fn()const mockHandleImportDSLConfirm = vi.fn()const mockTrackCreateApp = vi.fn()const mockTrackEvent = vi.hoisted(() => vi.fn())-const mockGetRecommendedApp = vi.hoisted(() => vi.fn())+const mockGetRecommendedApp = vi.hoisted(() =>+ vi.fn<(input: { params: { app_id: string } }) => Promise<RecommendedAppDetailResponse>>(),+)const mockAppQueries = vi.hoisted(() => ({listQueryOptions: vi.fn(),recentQueryOptions: vi.fn(),@@ -207,169 +211,149 @@ vi.mock('@/app/notifications', () => ({toast: toastMocks.api,}))-vi.mock('@/service/use-explore', () => ({- useLearnDifyAppList: () => ({- data: mockLearnDifyApps,- isLoading: mockLearnDifyLoading,- isError: false,- }),+vi.mock('@/service/base', () => ({+ request: async (url: string) => {+ const pathname = new URL(url).pathname+ if (pathname.endsWith('/explore/apps/learn-dify')) {+ if (mockLearnDifyLoading) return new Promise<Response>(() => {})+ return Response.json({ recommended_apps: mockLearnDifyApps })+ }+ if (pathname.endsWith('/explore/apps')) {+ return Response.json({+ categories: mockExploreData?.categories ?? [],+ recommended_apps: mockExploreData?.allList ?? [],+ })+ }+ const appId = pathname.match(/\/explore\/apps\/([^/]+)$/)?.[1]+ if (!appId) throw new Error(`Unexpected request: ${pathname}`)+ return Response.json(+ await mockGetRecommendedApp({ params: { app_id: decodeURIComponent(appId) } }),+ )+ },}))vi.mock('@/app/components/base/amplitude', () => ({trackEvent: mockTrackEvent,}))-vi.mock('@/service/console', () => ({- consoleClient: {- systemFeatures: () => Promise.resolve({}),- },- consoleQuery: {- account: {- profile: {- get: {- queryKey: () => [['console', 'account', 'profile', 'get'], { type: 'query' }],- },- },+vi.mock('@/service/console', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/console')>()+ return {+ consoleClient: {+ systemFeatures: () => Promise.resolve({}),},- systemFeatures: {- get: {- queryKey: () => ['console', 'systemFeatures'],- queryOptions: (options: Record<string, unknown> = {}) => ({- queryKey: ['console', 'systemFeatures'],- ...options,- }),+ consoleQuery: {+ account: {+ profile: {+ get: {+ queryKey: () => [['console', 'account', 'profile', 'get'], { type: 'query' }],+ },+ },},- },- apps: {- get: {- queryOptions: (options: {- input?: { query?: { limit?: number } }- select?: (response: {- data: RecentAppResponse[]- has_more: boolean- limit: number- page: number- total: number- }) => unknown- }) => {- mockAppQueries.listQueryOptions(options)- const limit = options.input?.query?.limit ?? mockWorkspaceApps.length- const response = {- data: mockWorkspaceApps.slice(0, limit),- has_more: false,- limit,- page: 1,- total: mockWorkspaceApps.length,- }- return {- queryKey: ['console', 'apps', 'get', options],- queryFn: () => Promise.resolve(response),- initialData: response,- select: options.select,- }+ systemFeatures: {+ get: {+ queryKey: () => ['console', 'systemFeatures'],+ queryOptions: (options: Record<string, unknown> = {}) => ({+ queryKey: ['console', 'systemFeatures'],+ ...options,+ }),},},- recent: {+ apps: {get: {queryOptions: (options: {input?: { query?: { limit?: number } }- select?: (response: { data: RecentAppResponse[] }) => unknown+ select?: (response: {+ data: RecentAppResponse[]+ has_more: boolean+ limit: number+ page: number+ total: number+ }) => unknown}) => {- mockAppQueries.recentQueryOptions(options)+ mockAppQueries.listQueryOptions(options)const limit = options.input?.query?.limit ?? mockWorkspaceApps.lengthconst response = {data: mockWorkspaceApps.slice(0, limit),+ has_more: false,+ limit,+ page: 1,+ total: mockWorkspaceApps.length,}return {- queryKey: ['console', 'apps', 'recent', 'get', options],+ queryKey: ['console', 'apps', 'get', options],queryFn: () => Promise.resolve(response),initialData: response,select: options.select,}},},- },- },- onboarding: {- stepByStepTour: {- state: {+ recent: {get: {- queryKey: () => mockStepByStepTour.stateQueryKey,- queryOptions: () => ({- queryKey: mockStepByStepTour.stateQueryKey,- queryFn: async () => mockStepByStepTour.state,- }),- },- patch: {- mutationOptions: (options = {}) => ({- mutationFn: mockStepByStepTour.patchState,- ...options,- }),+ queryOptions: (options: {+ input?: { query?: { limit?: number } }+ select?: (response: { data: RecentAppResponse[] }) => unknown+ }) => {+ mockAppQueries.recentQueryOptions(options)+ const limit = options.input?.query?.limit ?? mockWorkspaceApps.length+ const response = {+ data: mockWorkspaceApps.slice(0, limit),+ }+ return {+ queryKey: ['console', 'apps', 'recent', 'get', options],+ queryFn: () => Promise.resolve(response),+ initialData: response,+ select: options.select,+ }+ },},},},- },- explore: {- apps: {- byAppId: {- get: {- queryOptions: (options: { input: { params: { app_id: string } } }) => ({- queryKey: ['console', 'explore', 'apps', 'byAppId', 'get', options.input],- queryFn: () => mockGetRecommendedApp(options.input),- }),+ onboarding: {+ stepByStepTour: {+ state: {+ get: {+ queryKey: () => mockStepByStepTour.stateQueryKey,+ queryOptions: () => ({+ queryKey: mockStepByStepTour.stateQueryKey,+ queryFn: async () => mockStepByStepTour.state,+ }),+ },+ patch: {+ mutationOptions: (options = {}) => ({+ mutationFn: mockStepByStepTour.patchState,+ ...options,+ }),+ },},},- get: {- queryKey: ({ input }: { input?: unknown } = {}) => [- 'console',- 'explore',- 'apps',- 'get',- input,- ],- queryOptions: (options: {- input?: { query?: { language?: string } }- select?: (response: {- categories: string[]- recommended_apps: RecommendedAppResponse[]- }) => unknown- }) => {- const response = {- categories: mockExploreData?.categories ?? [],- recommended_apps: mockExploreData?.allList ?? [],- }- return {- queryKey: ['console', 'explore', 'apps', 'get', options.input],- queryFn: () => Promise.resolve(response),- initialData: response,+ },+ explore: {+ apps: actual.consoleQuery.explore.apps,+ banners: {+ get: {+ queryKey: ({ input }: { input?: unknown } = {}) => [+ 'console',+ 'explore',+ 'banners',+ 'get',+ input,+ ],+ queryOptions: (options: {+ input?: { query?: { language?: string } }+ select?: (response: BannerResponse[]) => unknown+ }) => ({+ queryKey: ['console', 'explore', 'banners', 'get', options.input],+ queryFn: () => Promise.resolve(mockBanners),+ initialData: mockBanners,select: options.select,- }+ }),},},},- banners: {- get: {- queryKey: ({ input }: { input?: unknown } = {}) => [- 'console',- 'explore',- 'banners',- 'get',- input,- ],- queryOptions: (options: {- input?: { query?: { language?: string } }- select?: (response: BannerResponse[]) => unknown- }) => ({- queryKey: ['console', 'explore', 'banners', 'get', options.input],- queryFn: () => Promise.resolve(mockBanners),- initialData: mockBanners,- select: options.select,- }),- },- },},- },-}))+ }+})vi.mock('@/context/workspace-state', async () => {const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture')@@ -544,16 +528,10 @@ type RenderOptions = {}const localeInput = { query: { language: 'en-US' } }-const homeTemplatesQueryKey = ['console', 'explore', 'apps', 'get', localeInput]+const homeTemplatesQueryKey = consoleQuery.explore.apps.get.queryKey({ input: localeInput })const exploreBannersQueryKey = ['console', 'explore', 'banners', 'get', localeInput]-const recommendedAppQueryKey = (appId: string) => [- 'console',- 'explore',- 'apps',- 'byAppId',- 'get',- { params: { app_id: appId } },-]+const recommendedAppQueryKey = (appId: string) =>+ consoleQuery.explore.apps.byAppId.get.queryKey({ input: { params: { app_id: appId } } })const renderHomeContent = ({hasEditPermission = false,@@ -575,6 +553,14 @@ const renderHomeContent = ({recommended_apps: mockExploreData.allList,})}+ if (!mockLearnDifyLoading) {+ queryClient.setQueryData(+ consoleQuery.explore.apps.learnDify.get.queryKey({ input: localeInput }),+ {+ recommended_apps: mockLearnDifyApps,+ },+ )+ }if (options.enableExploreBanner) queryClient.setQueryData(exploreBannersQueryKey, mockBanners)queryClient.setQueryData(mockStepByStepTour.stateQueryKey, mockStepByStepTour.state)@@ -973,6 +959,9 @@ describe('HomeContent', () => {allList: [createApp()],}mockGetRecommendedApp.mockResolvedValue({+ id: 'app-1',+ name: 'Alpha',+ can_trial: true,export_data: 'yaml-content',mode: AppModeEnum.CHAT,})@@ -1018,6 +1007,9 @@ describe('HomeContent', () => {mockHandleImportDSL.mockResolvedValue(undefined)const { queryClient } = renderHomeContent({ hasEditPermission: true })queryClient.setQueryData(recommendedAppQueryKey('app-1'), {+ id: 'app-1',+ name: 'Alpha',+ can_trial: true,export_data: 'cached-yaml',mode: AppModeEnum.CHAT,})@@ -1046,6 +1038,9 @@ describe('HomeContent', () => {allList: [createApp()],}mockGetRecommendedApp.mockResolvedValue({+ id: 'app-1',+ name: 'Alpha',+ can_trial: true,export_data: 'yaml-content',mode: AppModeEnum.CHAT,})@@ -1184,6 +1179,9 @@ describe('HomeContent', () => {minimized: true,})mockGetRecommendedApp.mockResolvedValue({+ id: 'app-1',+ name: 'Alpha',+ can_trial: true,export_data: 'yaml-content',mode: AppModeEnum.CHAT,})@@ -1241,6 +1239,9 @@ describe('HomeContent', () => {})mockStepByStepTour.patchState.mockRejectedValueOnce(new Error('patch failed'))mockGetRecommendedApp.mockResolvedValue({+ id: 'app-1',+ name: 'Alpha',+ can_trial: true,export_data: 'yaml-content',mode: AppModeEnum.CHAT,})@@ -1306,6 +1307,9 @@ describe('HomeContent', () => {minimized: true,})mockGetRecommendedApp.mockResolvedValue({+ id: 'app-1',+ name: 'Alpha',+ can_trial: true,export_data: 'yaml-content',mode: AppModeEnum.CHAT,})@@ -1401,6 +1405,9 @@ describe('HomeContent', () => {allList: [createApp()],}mockGetRecommendedApp.mockResolvedValue({+ id: 'app-1',+ name: 'Alpha',+ can_trial: true,export_data: 'yaml',mode: AppModeEnum.CHAT,})@@ -1423,6 +1430,9 @@ describe('HomeContent', () => {allList: [createApp()],}mockGetRecommendedApp.mockResolvedValue({+ id: 'app-1',+ name: 'Alpha',+ can_trial: true,export_data: 'yaml',mode: AppModeEnum.CHAT,})@@ -1451,6 +1461,9 @@ describe('HomeContent', () => {allList: [createApp()],}mockGetRecommendedApp.mockResolvedValue({+ id: 'app-1',+ name: 'Alpha',+ can_trial: true,export_data: 'yaml',mode: AppModeEnum.CHAT,})@@ -1502,6 +1515,9 @@ describe('HomeContent', () => {allList: [createApp()],}mockGetRecommendedApp.mockResolvedValue({+ id: 'app-1',+ name: 'Alpha',+ can_trial: true,export_data: 'yaml',mode: AppModeEnum.CHAT,})diff --git a/web/features/home/home-content/home-content.tsx b/web/features/home/home-content/home-content.tsxindex 5c56ed34de6..65ffe689b61 100644--- a/web/features/home/home-content/home-content.tsx+++ b/web/features/home/home-content/home-content.tsx@@ -474,10 +474,8 @@ export function HomeContent() {{currentTryApp && (<TryApp- appId={currentTryApp.app_id}app={currentTryApp}canCreate={canCreateApp}- categories={currentTryApp.categories ?? []}createButtonStepByStepTourTarget={canCreateApp && isCurrentTryAppFromLearnDifyRef.current && !isShowCreateModal? STEP_BY_STEP_TOUR_TARGETS.homeTryAppCreatediff --git a/web/features/home/home-content/recommendations.tsx b/web/features/home/home-content/recommendations.tsxindex 10fb32f3ba0..27cbc8249e0 100644--- a/web/features/home/home-content/recommendations.tsx+++ b/web/features/home/home-content/recommendations.tsx@@ -29,7 +29,7 @@ export function HomeRecommendations({className="pb-0"forceVisible={forceShowLearnDify}onCreate={onCreate}- onTry={({ app }) => onTry(app)}+ onTry={onTry}stepByStepTourTarget={STEP_BY_STEP_TOUR_TARGETS.home}/></>diff --git a/web/models/explore.ts b/web/models/explore.tsdeleted file mode 100644index 8d0314dfb81..00000000000--- a/web/models/explore.ts+++ /dev/null@@ -1,32 +0,0 @@-import type { AppIconType } from '@/types/app'--type AppBasicInfo = {- id: string- mode: string- icon_type: AppIconType | null- icon: string- icon_background: string- icon_url: string- name: string- description: string- use_icon_as_answer_icon: boolean-}--export type AppCategory = string--export type App = {- app: AppBasicInfo- app_id: string- description: string- copyright: string- privacy_policy: string | null- custom_disclaimer: string | null- categories: AppCategory[]- position: number- is_listed: boolean- install_count: number- installed: boolean- editable: boolean- is_agent: boolean- can_trial: boolean-}diff --git a/web/service/__tests__/use-explore.spec.tsx b/web/service/__tests__/use-explore.spec.tsxdeleted file mode 100644index 9aba8c4372f..00000000000--- a/web/service/__tests__/use-explore.spec.tsx+++ /dev/null@@ -1,82 +0,0 @@-import type { ReactNode } from 'react'-import type { App } from '@/models/explore'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { renderHook, waitFor } from '@testing-library/react'-import { AppModeEnum } from '@/types/app'-import { fetchAppList } from '../explore'-import { useExploreAppList } from '../use-explore'--vi.mock('../explore', () => ({- fetchAppList: vi.fn(),-}))--const createWrapper = () => {- const queryClient = new QueryClient({- defaultOptions: {- queries: { retry: false },- },- })-- return ({ children }: { children: ReactNode }) => (- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>- )-}--const createApp = (appId: string, position: number): App => ({- app: {- id: appId,- mode: AppModeEnum.CHAT,- icon_type: 'emoji',- icon: 'robot',- icon_background: '#fff',- icon_url: '',- name: appId,- description: '',- use_icon_as_answer_icon: false,- },- app_id: appId,- description: '',- copyright: '',- privacy_policy: null,- custom_disclaimer: null,- categories: [],- position,- is_listed: true,- install_count: 0,- installed: false,- editable: false,- is_agent: false,- can_trial: false,-})--describe('useExploreAppList', () => {- beforeEach(() => {- vi.clearAllMocks()- vi.mocked(fetchAppList).mockResolvedValue({- categories: [],- recommended_apps: [createApp('app-2', 2), createApp('app-1', 1)],- })- })-- // Explore app list can now be disabled by callers.- describe('Queries', () => {- it('should not fetch app list when disabled', () => {- renderHook(() => useExploreAppList({ enabled: false }), { wrapper: createWrapper() })-- expect(fetchAppList).not.toHaveBeenCalled()- })-- it('should fetch localized app list and sort recommended apps by position', async () => {- const { result } = renderHook(() => useExploreAppList({ enabled: true }), {- wrapper: createWrapper(),- })-- await waitFor(() => {- expect(fetchAppList).toHaveBeenCalledWith('en-US')- })- await waitFor(() => {- expect(result.current.data?.allList.map((app) => app.app_id)).toEqual(['app-1', 'app-2'])- })- })- })-})diff --git a/web/service/explore.spec.ts b/web/service/explore.spec.tsdeleted file mode 100644index 2c2af14a39f..00000000000--- a/web/service/explore.spec.ts+++ /dev/null@@ -1,82 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'-import { fetchAppDetail, fetchAppList, fetchInstalledAppList } from './explore'--const mockExploreAppsGet = vi.hoisted(() => vi.fn())-const mockExploreAppDetailGet = vi.hoisted(() => vi.fn())-const mockInstalledAppsGet = vi.hoisted(() => vi.fn())--vi.mock('@/service/console', () => ({- consoleClient: {- explore: {- apps: {- get: mockExploreAppsGet,- byAppId: {- get: mockExploreAppDetailGet,- },- },- },- installedApps: {- get: mockInstalledAppsGet,- },- },-}))--describe('explore service normalizers', () => {- beforeEach(() => {- vi.resetAllMocks()- })-- it('preserves backend app modes that are not part of the legacy frontend enum', async () => {- mockExploreAppsGet.mockResolvedValue({- categories: [],- recommended_apps: [- {- app_id: 'agent-app',- app: {- id: 'agent-app',- name: 'Agent app',- mode: 'agent',- icon: '',- icon_background: '',- },- },- ],- })- mockExploreAppDetailGet.mockResolvedValue({- id: 'pipeline-app',- name: 'Pipeline app',- icon: '',- icon_background: '',- mode: 'rag-pipeline',- export_data: 'kind: app',- can_trial: false,- })-- await expect(fetchAppList()).resolves.toMatchObject({- recommended_apps: [- {- app: {- mode: 'agent',- },- },- ],- })- await expect(fetchAppDetail('pipeline-app')).resolves.toMatchObject({- mode: 'rag-pipeline',- })- })-- it('preserves installed app pagination metadata', async () => {- mockInstalledAppsGet.mockResolvedValue({- installed_apps: [],- has_more: true,- next_cursor: 'next-page',- })-- await expect(fetchInstalledAppList()).resolves.toEqual({- installed_apps: [],- has_more: true,- next_cursor: 'next-page',- })- })-})diff --git a/web/service/explore.ts b/web/service/explore.tsdeleted file mode 100644index 98d50593886..00000000000--- a/web/service/explore.ts+++ /dev/null@@ -1,140 +0,0 @@-import type {- GetExploreAppsLearnDifyResponse,- GetExploreAppsResponse,- RecommendedAppDetailResponse,- RecommendedAppInfoResponse,- RecommendedAppResponse,-} from '@dify/contracts/api/console/explore/types.gen'-import type { App, AppCategory } from '@/models/explore'-import type { AppIconType } from '@/types/app'-import { consoleClient } from '@/service/console'--type ExploreAppsResponse = {- categories: AppCategory[]- recommended_apps: App[]-}--type LearnDifyAppsResponse = {- recommended_apps: App[]-}--type ExploreAppDetailResponse = {- id: string- name: string- icon: string- icon_background: string- mode: string- export_data: string- can_trial: boolean-}--const normalizeAppMode = (value: unknown) => {- return typeof value === 'string' ? value : ''-}--const isAppIconType = (value: unknown): value is AppIconType => {- return value === 'image' || value === 'emoji' || value === 'link'-}--const normalizeAppIconType = (value: unknown) => {- return isAppIconType(value) ? value : null-}--const normalizeAppBasicInfo = (- source: RecommendedAppInfoResponse | null | undefined,- fallbackId: string,-): App['app'] => {- return {- id: source?.id ?? fallbackId,- mode: normalizeAppMode(source?.mode),- icon_type: normalizeAppIconType(source?.icon_type),- icon: source?.icon ?? '',- icon_background: source?.icon_background ?? '',- icon_url: source?.icon_url ?? '',- name: source?.name ?? '',- description: '',- use_icon_as_answer_icon: false,- }-}--const normalizeRecommendedApp = (app: RecommendedAppResponse): App => {- return {- app: normalizeAppBasicInfo(app.app, app.app_id),- app_id: app.app_id,- description: app.description ?? '',- copyright: app.copyright ?? '',- privacy_policy: app.privacy_policy ?? null,- custom_disclaimer: app.custom_disclaimer ?? null,- categories: app.categories ?? [],- position: app.position ?? 0,- is_listed: app.is_listed ?? false,- install_count: 0,- installed: false,- editable: false,- is_agent: false,- can_trial: app.can_trial,- }-}--const normalizeExploreAppsResponse = (response: GetExploreAppsResponse): ExploreAppsResponse => {- return {- categories: response.categories,- recommended_apps: response.recommended_apps.map(normalizeRecommendedApp),- }-}--const normalizeLearnDifyAppsResponse = (- response: GetExploreAppsLearnDifyResponse,-): LearnDifyAppsResponse => {- return {- recommended_apps: response.recommended_apps.map(normalizeRecommendedApp),- }-}--const normalizeAppDetail = (response: RecommendedAppDetailResponse): ExploreAppDetailResponse => {- return {- id: response.id,- name: response.name,- icon: response.icon ?? '',- icon_background: response.icon_background ?? '',- mode: normalizeAppMode(response.mode),- export_data: response.export_data,- can_trial: response.can_trial,- }-}--export const fetchAppList = (language?: string) => {- if (!language) return consoleClient.explore.apps.get({}).then(normalizeExploreAppsResponse)-- return consoleClient.explore.apps- .get({- query: { language },- })- .then(normalizeExploreAppsResponse)-}--export const fetchLearnDifyAppList = (language?: string) => {- if (!language)- return consoleClient.explore.apps.learnDify.get({}).then(normalizeLearnDifyAppsResponse)-- return consoleClient.explore.apps.learnDify- .get({- query: { language },- })- .then(normalizeLearnDifyAppsResponse)-}--export const fetchAppDetail = async (id: string): Promise<ExploreAppDetailResponse> => {- const response = await consoleClient.explore.apps.byAppId.get({- params: { app_id: id },- })- return normalizeAppDetail(response)-}--export const fetchInstalledAppList = (appId?: string | null) => {- if (!appId) return consoleClient.installedApps.get({})-- return consoleClient.installedApps.get({- query: { app_id: appId },- })-}diff --git a/web/service/use-explore.ts b/web/service/use-explore.tsdeleted file mode 100644index 8da10f67f2a..00000000000--- a/web/service/use-explore.ts+++ /dev/null@@ -1,48 +0,0 @@-import type { App, AppCategory } from '@/models/explore'-import { useQuery } from '@tanstack/react-query'-import { useLocale } from '#i18n'-import { consoleQuery } from '@/service/console'-import { fetchAppList, fetchLearnDifyAppList } from './explore'--type ExploreAppListData = {- categories: AppCategory[]- allList: App[]-}--export const useExploreAppList = (options: { enabled?: boolean } = {}) => {- const locale = useLocale()- const exploreAppsInput = locale ? { query: { language: locale } } : {}- const exploreAppsLanguage = exploreAppsInput?.query?.language-- return useQuery<ExploreAppListData>({- queryKey: [- ...consoleQuery.explore.apps.get.queryKey({ input: exploreAppsInput }),- exploreAppsLanguage,- ],- queryFn: async () => {- const { categories, recommended_apps } = await fetchAppList(exploreAppsLanguage)- return {- categories,- allList: [...recommended_apps].sort((a, b) => a.position - b.position),- }- },- enabled: options.enabled,- })-}--export const useLearnDifyAppList = () => {- const locale = useLocale()- const learnDifyAppsInput = locale ? { query: { language: locale } } : {}- const learnDifyAppsLanguage = learnDifyAppsInput?.query?.language-- return useQuery({- queryKey: [- ...consoleQuery.explore.apps.learnDify.get.queryKey({ input: learnDifyAppsInput }),- learnDifyAppsLanguage,- ],- queryFn: async () => {- const { recommended_apps } = await fetchLearnDifyAppList(learnDifyAppsLanguage)- return [...recommended_apps].sort((a, b) => a.position - b.position)- },- })-}diff --git a/web/types/try-app.ts b/web/types/try-app.tsdeleted file mode 100644index 0aa9462371c..00000000000--- a/web/types/try-app.ts+++ /dev/null@@ -1,6 +0,0 @@-import type { App } from '@/models/explore'--export type TryAppSelection = {- appId: string- app: App-}