Skip to content

armgit / dify

Public Imported from GitHub
0

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.

refactor(web): unify app-shell bootstrap on TanStack Query + Next.js route conventions (#35394)

yyhc7641bb1ce0f
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 2d53d97dd09..e16a1be0f7b 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -59,7 +59,7 @@
},
"web/__tests__/embedded-user-id-store.test.tsx": {
"ts/no-explicit-any": {
- "count": 3
+ "count": 1
}
},
"web/__tests__/goto-anything/command-selector.test.tsx": {
@@ -6399,11 +6399,6 @@
"count": 1
}
},
- "web/context/global-public-context.tsx": {
- "react-refresh/only-export-components": {
- "count": 3
- }
- },
"web/context/hooks/use-trigger-events-limit-modal.ts": {
"react/set-state-in-effect": {
"count": 3
diff --git a/web/__tests__/app/app-access-control-flow.test.tsx b/web/__tests__/app/app-access-control-flow.test.tsx
index 63f7fd0378b..e1284bfc5b5 100644
--- a/web/__tests__/app/app-access-control-flow.test.tsx
+++ b/web/__tests__/app/app-access-control-flow.test.tsx
@@ -1,6 +1,6 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import AppPublisher from '@/app/components/app/app-publisher'
import { AccessMode } from '@/models/access-control'
import { AppModeEnum } from '@/types/app'
@@ -24,27 +24,15 @@ let mockAppDetail: {
}
} | null = null
-const createTestQueryClient = () =>
- new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- mutations: {
- retry: false,
+const renderWithQueryClient = (ui: React.ReactElement) =>
+ renderWithSystemFeatures(ui, {
+ systemFeatures: {
+ webapp_auth: {
+ enabled: true,
},
},
})
-const renderWithQueryClient = (ui: React.ReactElement) => {
- const queryClient = createTestQueryClient()
- return render(
- <QueryClientProvider client={queryClient}>
- {ui}
- </QueryClientProvider>,
- )
-}
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, options?: { ns?: string }) => options?.ns ? `${options.ns}.${key}` : key,
@@ -58,16 +46,6 @@ vi.mock('@/app/components/app/store', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: Record<string, unknown>) => unknown) => selector({
- systemFeatures: {
- webapp_auth: {
- enabled: true,
- },
- },
- }),
-}))
-
vi.mock('@/hooks/use-format-time-from-now', () => ({
useFormatTimeFromNow: () => ({
formatTimeFromNow: (value: number) => `ago:${value}`,
diff --git a/web/__tests__/app/app-publisher-flow.test.tsx b/web/__tests__/app/app-publisher-flow.test.tsx
index 9c09acf6a12..d4bf56e7e4e 100644
--- a/web/__tests__/app/app-publisher-flow.test.tsx
+++ b/web/__tests__/app/app-publisher-flow.test.tsx
@@ -1,6 +1,6 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import AppPublisher from '@/app/components/app/app-publisher'
import { AccessMode } from '@/models/access-control'
import { AppModeEnum } from '@/types/app'
@@ -28,27 +28,15 @@ let mockAppDetail: {
}
} | null = null
-const createTestQueryClient = () =>
- new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- mutations: {
- retry: false,
+const renderWithQueryClient = (ui: React.ReactElement) =>
+ renderWithSystemFeatures(ui, {
+ systemFeatures: {
+ webapp_auth: {
+ enabled: true,
},
},
})
-const renderWithQueryClient = (ui: React.ReactElement) => {
- const queryClient = createTestQueryClient()
- return render(
- <QueryClientProvider client={queryClient}>
- {ui}
- </QueryClientProvider>,
- )
-}
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) => key,
@@ -66,16 +54,6 @@ vi.mock('@/app/components/app/store', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: Record<string, unknown>) => unknown) => selector({
- systemFeatures: {
- webapp_auth: {
- enabled: true,
- },
- },
- }),
-}))
-
vi.mock('@/hooks/use-format-time-from-now', () => ({
useFormatTimeFromNow: () => ({
formatTimeFromNow: (value: number) => `ago:${value}`,
diff --git a/web/__tests__/apps/app-card-operations-flow.test.tsx b/web/__tests__/apps/app-card-operations-flow.test.tsx
index 8c3219794dc..b0854072d25 100644
--- a/web/__tests__/apps/app-card-operations-flow.test.tsx
+++ b/web/__tests__/apps/app-card-operations-flow.test.tsx
@@ -10,8 +10,9 @@
* - Access mode icons
*/
import type { App } from '@/types/app'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import AppCard from '@/app/components/apps/app-card'
import { AccessMode } from '@/models/access-control'
import { exportAppConfig, updateAppInfo } from '@/service/apps'
@@ -96,15 +97,6 @@ vi.mock('@/context/app-context', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector?: (state: Record<string, unknown>) => unknown) => {
- const state = { systemFeatures: mockSystemFeatures }
- if (typeof selector === 'function')
- return selector(state)
- return mockSystemFeatures
- },
-}))
-
vi.mock('@/context/provider-context', () => ({
useProviderContext: () => ({
onPlanInfoChanged: mockOnPlanInfoChanged,
@@ -255,7 +247,10 @@ const createMockApp = (overrides: Partial<App> = {}): App => ({
const mockOnRefresh = vi.fn()
const renderAppCard = (app?: Partial<App>) => {
- return render(<AppCard app={createMockApp(app)} onRefresh={mockOnRefresh} />)
+ return renderWithSystemFeatures(
+ <AppCard app={createMockApp(app)} onRefresh={mockOnRefresh} />,
+ { systemFeatures: mockSystemFeatures },
+ )
}
const openOperationsMenu = () => {
diff --git a/web/__tests__/apps/app-list-browsing-flow.test.tsx b/web/__tests__/apps/app-list-browsing-flow.test.tsx
index a5ed79a7bd1..768420f00de 100644
--- a/web/__tests__/apps/app-list-browsing-flow.test.tsx
+++ b/web/__tests__/apps/app-list-browsing-flow.test.tsx
@@ -1,3 +1,4 @@
+import type { ReactElement, ReactNode } from 'react'
/**
* Integration test: App List Browsing Flow
*
@@ -8,11 +9,12 @@
*/
import type { AppListResponse } from '@/models/app'
import type { App } from '@/types/app'
-import { fireEvent, screen } from '@testing-library/react'
+import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { createSystemFeaturesWrapper } from '@/__tests__/utils/mock-system-features'
import List from '@/app/components/apps/list'
import { AccessMode } from '@/models/access-control'
-import { renderWithNuqs } from '@/test/nuqs-testing'
+import { createNuqsTestWrapper } from '@/test/nuqs-testing'
import { AppModeEnum } from '@/types/app'
let mockIsCurrentWorkspaceEditor = true
@@ -64,13 +66,6 @@ vi.mock('@/context/app-context', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector?: (state: Record<string, unknown>) => unknown) => {
- const state = { systemFeatures: mockSystemFeatures }
- return selector ? selector(state) : state
- },
-}))
-
vi.mock('@/context/provider-context', () => ({
useProviderContext: () => ({
onPlanInfoChanged: vi.fn(),
@@ -168,11 +163,21 @@ const createPage = (apps: App[], hasMore = false, page = 1): AppListResponse =>
total: apps.length,
})
-const renderList = (searchParams?: Record<string, string>) => {
- return renderWithNuqs(
- <List controlRefreshList={0} />,
- { searchParams },
+const renderListUI = (ui: ReactElement, searchParams?: Record<string, string>) => {
+ const { wrapper: SysWrapper } = createSystemFeaturesWrapper({
+ systemFeatures: mockSystemFeatures,
+ })
+ const { wrapper: NuqsWrapper, onUrlUpdate } = createNuqsTestWrapper({ searchParams })
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <NuqsWrapper>
+ <SysWrapper>{children}</SysWrapper>
+ </NuqsWrapper>
)
+ return { ...render(ui, { wrapper: Wrapper }), onUrlUpdate }
+}
+
+const renderList = (searchParams?: Record<string, string>) => {
+ return renderListUI(<List controlRefreshList={0} />, searchParams)
}
describe('App List Browsing Flow', () => {
@@ -216,7 +221,7 @@ describe('App List Browsing Flow', () => {
it('should transition from loading to content when data loads', () => {
mockIsLoading = true
- const { rerender } = renderWithNuqs(<List controlRefreshList={0} />)
+ const { rerender } = renderListUI(<List controlRefreshList={0} />)
const skeletonCards = document.querySelectorAll('.animate-pulse')
expect(skeletonCards.length).toBeGreaterThan(0)
@@ -423,7 +428,7 @@ describe('App List Browsing Flow', () => {
it('should call refetch when controlRefreshList increments', () => {
mockPages = [createPage([createMockApp()])]
- const { rerender } = renderWithNuqs(<List controlRefreshList={0} />)
+ const { rerender } = renderListUI(<List controlRefreshList={0} />)
rerender(<List controlRefreshList={1} />)
diff --git a/web/__tests__/apps/create-app-flow.test.tsx b/web/__tests__/apps/create-app-flow.test.tsx
index 9abc870ecf0..e480db06eab 100644
--- a/web/__tests__/apps/create-app-flow.test.tsx
+++ b/web/__tests__/apps/create-app-flow.test.tsx
@@ -1,3 +1,4 @@
+import type { ReactNode } from 'react'
/**
* Integration test: Create App Flow
*
@@ -9,11 +10,12 @@
*/
import type { AppListResponse } from '@/models/app'
import type { App } from '@/types/app'
-import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { createSystemFeaturesWrapper } from '@/__tests__/utils/mock-system-features'
import List from '@/app/components/apps/list'
import { AccessMode } from '@/models/access-control'
-import { renderWithNuqs } from '@/test/nuqs-testing'
+import { createNuqsTestWrapper } from '@/test/nuqs-testing'
import { AppModeEnum } from '@/types/app'
let mockIsCurrentWorkspaceEditor = true
@@ -51,13 +53,6 @@ vi.mock('@/context/app-context', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector?: (state: Record<string, unknown>) => unknown) => {
- const state = { systemFeatures: mockSystemFeatures }
- return selector ? selector(state) : state
- },
-}))
-
vi.mock('@/context/provider-context', () => ({
useProviderContext: () => ({
onPlanInfoChanged: mockOnPlanInfoChanged,
@@ -222,7 +217,16 @@ const createPage = (apps: App[]): AppListResponse => ({
})
const renderList = () => {
- return renderWithNuqs(<List controlRefreshList={0} />)
+ const { wrapper: SysWrapper } = createSystemFeaturesWrapper({
+ systemFeatures: mockSystemFeatures,
+ })
+ const { wrapper: NuqsWrapper, onUrlUpdate } = createNuqsTestWrapper()
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <NuqsWrapper>
+ <SysWrapper>{children}</SysWrapper>
+ </NuqsWrapper>
+ )
+ return { ...render(<List controlRefreshList={0} />, { wrapper: Wrapper }), onUrlUpdate }
}
describe('Create App Flow', () => {
diff --git a/web/__tests__/base/chat-flow.test.tsx b/web/__tests__/base/chat-flow.test.tsx
index 2a02c063fdc..6ede7c766be 100644
--- a/web/__tests__/base/chat-flow.test.tsx
+++ b/web/__tests__/base/chat-flow.test.tsx
@@ -1,8 +1,9 @@
import type { RefObject } from 'react'
import type { ChatConfig } from '@/app/components/base/chat/types'
import type { AppConversationData, AppData, AppMeta, ConversationItem } from '@/models/share'
-import { fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react'
+import { fireEvent, renderHook, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures as render } from '@/__tests__/utils/mock-system-features'
import ChatWithHistory from '@/app/components/base/chat/chat-with-history'
import { useChatWithHistory } from '@/app/components/base/chat/chat-with-history/hooks'
import { useThemeContext } from '@/app/components/base/chat/embedded-chatbot/theme/theme-context'
diff --git a/web/__tests__/embedded-user-id-store.test.tsx b/web/__tests__/embedded-user-id-store.test.tsx
index 04597ccfeb4..7e9eec644bc 100644
--- a/web/__tests__/embedded-user-id-store.test.tsx
+++ b/web/__tests__/embedded-user-id-store.test.tsx
@@ -1,5 +1,6 @@
-import { render, screen, waitFor } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import * as React from 'react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import WebAppStoreProvider, { useWebAppStore } from '@/context/web-app-context'
import { AccessMode } from '@/models/access-control'
@@ -19,44 +20,12 @@ vi.mock('@/service/use-share', () => ({
})),
}))
-// Store the mock implementation in a way that survives hoisting
const mockGetProcessedSystemVariablesFromUrlParams = vi.fn()
vi.mock('@/app/components/base/chat/utils', () => ({
getProcessedSystemVariablesFromUrlParams: (...args: any[]) => mockGetProcessedSystemVariablesFromUrlParams(...args),
}))
-// Use vi.hoisted to define mock state before vi.mock hoisting
-const { mockGlobalStoreState } = vi.hoisted(() => ({
- mockGlobalStoreState: {
- isGlobalPending: false,
- setIsGlobalPending: vi.fn(),
- systemFeatures: {},
- setSystemFeatures: vi.fn(),
- },
-}))
-
-vi.mock('@/context/global-public-context', () => {
- const useGlobalPublicStore = Object.assign(
- (selector?: (state: typeof mockGlobalStoreState) => any) =>
- selector ? selector(mockGlobalStoreState) : mockGlobalStoreState,
- {
- setState: (updater: any) => {
- if (typeof updater === 'function')
- Object.assign(mockGlobalStoreState, updater(mockGlobalStoreState) ?? {})
-
- else
- Object.assign(mockGlobalStoreState, updater)
- },
- __mockState: mockGlobalStoreState,
- },
- )
- return {
- useGlobalPublicStore,
- useIsSystemFeaturesPending: () => false,
- }
-})
-
const TestConsumer = () => {
const embeddedUserId = useWebAppStore(state => state.embeddedUserId)
const embeddedConversationId = useWebAppStore(state => state.embeddedConversationId)
@@ -91,7 +60,6 @@ const initialWebAppStore = (() => {
})()
beforeEach(() => {
- mockGlobalStoreState.isGlobalPending = false
mockGetProcessedSystemVariablesFromUrlParams.mockReset()
useWebAppStore.setState(initialWebAppStore, true)
})
@@ -103,7 +71,7 @@ describe('WebAppStoreProvider embedded user id handling', () => {
conversation_id: 'conversation-456',
})
- render(
+ renderWithSystemFeatures(
<WebAppStoreProvider>
<TestConsumer />
</WebAppStoreProvider>,
@@ -125,7 +93,7 @@ describe('WebAppStoreProvider embedded user id handling', () => {
}))
mockGetProcessedSystemVariablesFromUrlParams.mockResolvedValue({})
- render(
+ renderWithSystemFeatures(
<WebAppStoreProvider>
<TestConsumer />
</WebAppStoreProvider>,
diff --git a/web/__tests__/explore/explore-app-list-flow.test.tsx b/web/__tests__/explore/explore-app-list-flow.test.tsx
index e2c78310182..6af17119be8 100644
--- a/web/__tests__/explore/explore-app-list-flow.test.tsx
+++ b/web/__tests__/explore/explore-app-list-flow.test.tsx
@@ -7,7 +7,8 @@
import type { Mock } from 'vitest'
import type { CreateAppModalProps } from '@/app/components/explore/create-app-modal'
import type { App } from '@/models/explore'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { renderWithSystemFeatures as render } from '@/__tests__/utils/mock-system-features'
import AppList from '@/app/components/explore/app-list'
import { useAppContext } from '@/context/app-context'
import { fetchAppDetail } from '@/service/explore'
diff --git a/web/__tests__/header/account-dropdown-flow.test.tsx b/web/__tests__/header/account-dropdown-flow.test.tsx
index 6a645c7a433..b4a3befea06 100644
--- a/web/__tests__/header/account-dropdown-flow.test.tsx
+++ b/web/__tests__/header/account-dropdown-flow.test.tsx
@@ -1,6 +1,6 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { Plan } from '@/app/components/billing/type'
import AccountDropdown from '@/app/components/header/account-dropdown'
import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'
@@ -52,20 +52,6 @@ vi.mock('@/context/provider-context', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector?: (state: Record<string, unknown>) => unknown) => {
- const state = {
- systemFeatures: {
- branding: {
- enabled: false,
- workspace_logo: null,
- },
- },
- }
- return selector ? selector(state) : state
- },
-}))
-
vi.mock('@/context/modal-context', () => ({
useModalContext: () => ({
setShowAccountSettingModal: mockSetShowAccountSettingModal,
@@ -108,18 +94,14 @@ vi.mock('@/next/link', () => ({
}))
const renderAccountDropdown = () => {
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
+ return renderWithSystemFeatures(<AccountDropdown />, {
+ systemFeatures: {
+ branding: {
+ enabled: false,
+ workspace_logo: '',
+ },
},
})
-
- return render(
- <QueryClientProvider client={queryClient}>
- <AccountDropdown />
- </QueryClientProvider>,
- )
}
describe('Header Account Dropdown Flow', () => {
diff --git a/web/__tests__/plugins/plugin-marketplace-to-install.test.tsx b/web/__tests__/plugins/plugin-marketplace-to-install.test.tsx
index 91e32155e7f..3d08fe9d7cd 100644
--- a/web/__tests__/plugins/plugin-marketplace-to-install.test.tsx
+++ b/web/__tests__/plugins/plugin-marketplace-to-install.test.tsx
@@ -1,16 +1,7 @@
-import { describe, expect, it, vi } from 'vitest'
+import { describe, expect, it } from 'vitest'
import { pluginInstallLimit } from '@/app/components/plugins/install-plugin/hooks/use-install-plugin-limit'
import { InstallationScope } from '@/types/feature'
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: () => ({
- plugin_installation_permission: {
- restrict_to_marketplace_only: false,
- plugin_installation_scope: InstallationScope.ALL,
- },
- }),
-}))
-
describe('Plugin Marketplace to Install Flow', () => {
describe('install permission validation pipeline', () => {
const systemFeaturesAll = {
diff --git a/web/__tests__/plugins/plugin-page-shell-flow.test.tsx b/web/__tests__/plugins/plugin-page-shell-flow.test.tsx
index 9202f647af5..bd089d325c3 100644
--- a/web/__tests__/plugins/plugin-page-shell-flow.test.tsx
+++ b/web/__tests__/plugins/plugin-page-shell-flow.test.tsx
@@ -1,7 +1,9 @@
-import { fireEvent, screen, waitFor } from '@testing-library/react'
+import type { ReactNode } from 'react'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { createSystemFeaturesWrapper } from '@/__tests__/utils/mock-system-features'
import PluginPage from '@/app/components/plugins/plugin-page'
-import { renderWithNuqs } from '@/test/nuqs-testing'
+import { createNuqsTestWrapper } from '@/test/nuqs-testing'
const mockFetchManifestFromMarketPlace = vi.fn()
@@ -35,17 +37,6 @@ vi.mock('@/context/app-context', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: Record<string, unknown>) => unknown) => selector({
- systemFeatures: {
- enable_marketplace: true,
- plugin_installation_permission: {
- restrict_to_marketplace_only: false,
- },
- },
- }),
-}))
-
vi.mock('@/service/use-plugins', () => ({
useReferenceSettings: () => ({
data: {
@@ -104,13 +95,30 @@ vi.mock('@/app/components/plugins/install-plugin/install-from-marketplace', () =
}))
const renderPluginPage = (searchParams = '') => {
- return renderWithNuqs(
- <PluginPage
- plugins={<div data-testid="plugins-view">plugins view</div>}
- marketplace={<div data-testid="marketplace-view">marketplace view</div>}
- />,
- { searchParams },
+ const { wrapper: SysWrapper } = createSystemFeaturesWrapper({
+ systemFeatures: {
+ enable_marketplace: true,
+ plugin_installation_permission: {
+ restrict_to_marketplace_only: false,
+ },
+ },
+ })
+ const { wrapper: NuqsWrapper, onUrlUpdate } = createNuqsTestWrapper({ searchParams })
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <NuqsWrapper>
+ <SysWrapper>{children}</SysWrapper>
+ </NuqsWrapper>
)
+ return {
+ ...render(
+ <PluginPage
+ plugins={<div data-testid="plugins-view">plugins view</div>}
+ marketplace={<div data-testid="marketplace-view">marketplace view</div>}
+ />,
+ { wrapper: Wrapper },
+ ),
+ onUrlUpdate,
+ }
}
describe('Plugin Page Shell Flow', () => {
diff --git a/web/__tests__/share/text-generation-index-flow.test.tsx b/web/__tests__/share/text-generation-index-flow.test.tsx
index 2fec054a47b..638f774c167 100644
--- a/web/__tests__/share/text-generation-index-flow.test.tsx
+++ b/web/__tests__/share/text-generation-index-flow.test.tsx
@@ -1,6 +1,7 @@
import type { AccessMode } from '@/models/access-control'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import TextGeneration from '@/app/components/share/text-generation'
const useSearchParamsMock = vi.fn(() => new URLSearchParams())
@@ -117,7 +118,7 @@ vi.mock('@/service/share', async () => {
const mockSystemFeatures = {
branding: {
enabled: false,
- workspace_logo: null,
+ workspace_logo: '',
},
}
@@ -170,11 +171,6 @@ const mockWebAppState = {
webAppAccessMode: 'public' as AccessMode,
}
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: typeof mockSystemFeatures }) => unknown) =>
- selector({ systemFeatures: mockSystemFeatures }),
-}))
-
vi.mock('@/context/web-app-context', () => ({
useWebAppStore: (selector: (state: typeof mockWebAppState) => unknown) => selector(mockWebAppState),
}))
@@ -189,7 +185,7 @@ describe('TextGeneration', () => {
})
it('should switch between create, batch, and saved tabs after app state loads', async () => {
- render(<TextGeneration />)
+ renderWithSystemFeatures(<TextGeneration />, { systemFeatures: mockSystemFeatures })
await waitFor(() => {
expect(screen.getByTestId('run-once-mock')).toBeInTheDocument()
@@ -212,7 +208,7 @@ describe('TextGeneration', () => {
})
it('should wire single-run stop control and clear it when batch execution starts', async () => {
- render(<TextGeneration />)
+ renderWithSystemFeatures(<TextGeneration />, { systemFeatures: mockSystemFeatures })
await waitFor(() => {
expect(screen.getByTestId('run-once-mock')).toBeInTheDocument()
diff --git a/web/__tests__/tools/provider-list-shell-flow.test.tsx b/web/__tests__/tools/provider-list-shell-flow.test.tsx
index d0d096f072e..afa3f45e9f4 100644
--- a/web/__tests__/tools/provider-list-shell-flow.test.tsx
+++ b/web/__tests__/tools/provider-list-shell-flow.test.tsx
@@ -1,8 +1,10 @@
-import { fireEvent, screen, waitFor } from '@testing-library/react'
+import type { ReactNode } from 'react'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { createSystemFeaturesWrapper } from '@/__tests__/utils/mock-system-features'
import ProviderList from '@/app/components/tools/provider-list'
import { CollectionType } from '@/app/components/tools/types'
-import { renderWithNuqs } from '@/test/nuqs-testing'
+import { createNuqsTestWrapper } from '@/test/nuqs-testing'
const mockInvalidateInstalledPluginList = vi.fn()
@@ -12,14 +14,6 @@ vi.mock('react-i18next', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: Record<string, unknown>) => unknown) => selector({
- systemFeatures: {
- enable_marketplace: true,
- },
- }),
-}))
-
vi.mock('@/app/components/plugins/hooks', () => ({
useTags: () => ({
getTagLabel: (name: string) => name,
@@ -159,7 +153,16 @@ vi.mock('@/app/components/tools/mcp', () => ({
}))
const renderProviderList = (searchParams = '') => {
- return renderWithNuqs(<ProviderList />, { searchParams })
+ const { wrapper: SysWrapper } = createSystemFeaturesWrapper({
+ systemFeatures: { enable_marketplace: true },
+ })
+ const { wrapper: NuqsWrapper, onUrlUpdate } = createNuqsTestWrapper({ searchParams })
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <NuqsWrapper>
+ <SysWrapper>{children}</SysWrapper>
+ </NuqsWrapper>
+ )
+ return { ...render(<ProviderList />, { wrapper: Wrapper }), onUrlUpdate }
}
describe('Tool Provider List Shell Flow', () => {
diff --git a/web/__tests__/tools/tool-browsing-and-filtering.test.tsx b/web/__tests__/tools/tool-browsing-and-filtering.test.tsx
index aa8f59ca31b..b1cc0c13122 100644
--- a/web/__tests__/tools/tool-browsing-and-filtering.test.tsx
+++ b/web/__tests__/tools/tool-browsing-and-filtering.test.tsx
@@ -6,10 +6,10 @@ import type { Collection } from '@/app/components/tools/types'
* Input (search), and card rendering. Verifies that tab switching, keyword
* filtering, and label filtering work together correctly.
*/
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { createSystemFeaturesWrapper } from '@/__tests__/utils/mock-system-features'
import { CollectionType } from '@/app/components/tools/types'
// ---- Mocks ----
@@ -36,10 +36,6 @@ vi.mock('nuqs', async (importOriginal) => {
}
})
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: () => ({ enable_marketplace: false }),
-}))
-
vi.mock('@/app/components/plugins/hooks', () => ({
useTags: () => ({
getTagLabel: (key: string) => key,
@@ -237,12 +233,10 @@ vi.mock('@/app/components/workflow/block-selector/types', () => ({
const { default: ProviderList } = await import('@/app/components/tools/provider-list')
const createWrapper = () => {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false } },
+ const { wrapper } = createSystemFeaturesWrapper({
+ systemFeatures: { enable_marketplace: false },
})
- return ({ children }: { children: React.ReactNode }) => (
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
- )
+ return wrapper
}
describe('Tool Browsing & Filtering Integration', () => {
diff --git a/web/__tests__/utils/mock-system-features.tsx b/web/__tests__/utils/mock-system-features.tsx
new file mode 100644
index 00000000000..6884e682373
--- /dev/null
+++ b/web/__tests__/utils/mock-system-features.tsx
@@ -0,0 +1,127 @@
+import type { RenderHookOptions, RenderHookResult, RenderOptions, RenderResult } from '@testing-library/react'
+import type { ReactElement, ReactNode } from 'react'
+import type { SystemFeatures } from '@/types/feature'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { render, renderHook } from '@testing-library/react'
+import { consoleQuery } from '@/service/client'
+import { defaultSystemFeatures } from '@/types/feature'
+
+type DeepPartial<T> = T extends Array<infer U>
+ ? Array<U>
+ : T extends object
+ ? { [K in keyof T]?: DeepPartial<T[K]> }
+ : T
+
+const buildSystemFeatures = (
+ overrides: DeepPartial<SystemFeatures> = {},
+): SystemFeatures => {
+ const o = overrides as Partial<SystemFeatures>
+ return {
+ ...defaultSystemFeatures,
+ ...o,
+ branding: {
+ ...defaultSystemFeatures.branding,
+ ...(o.branding ?? {}),
+ },
+ webapp_auth: {
+ ...defaultSystemFeatures.webapp_auth,
+ ...(o.webapp_auth ?? {}),
+ sso_config: {
+ ...defaultSystemFeatures.webapp_auth.sso_config,
+ ...(o.webapp_auth?.sso_config ?? {}),
+ },
+ },
+ plugin_installation_permission: {
+ ...defaultSystemFeatures.plugin_installation_permission,
+ ...(o.plugin_installation_permission ?? {}),
+ },
+ license: {
+ ...defaultSystemFeatures.license,
+ ...(o.license ?? {}),
+ },
+ }
+}
+
+/**
+ * Build a QueryClient suitable for tests. Any unseeded query stays in the
+ * "pending" state forever because the default queryFn never resolves; this
+ * mirrors the behaviour of an in-flight network request without touching the
+ * real fetch layer.
+ */
+export const createTestQueryClient = (): QueryClient =>
+ new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ gcTime: 0,
+ staleTime: Infinity,
+ queryFn: () => new Promise(() => {}),
+ },
+ mutations: { retry: false },
+ },
+ })
+
+export const seedSystemFeatures = (
+ queryClient: QueryClient,
+ overrides: DeepPartial<SystemFeatures> = {},
+): SystemFeatures => {
+ const data = buildSystemFeatures(overrides)
+ queryClient.setQueryData(consoleQuery.systemFeatures.queryKey(), data)
+ return data
+}
+
+type SystemFeaturesTestOptions = {
+ /**
+ * Partial overrides for the systemFeatures payload. When omitted, the cache
+ * is seeded with `defaultSystemFeatures` so consumers using
+ * `useSuspenseQuery` resolve immediately. Pass `null` to skip seeding and
+ * keep the systemFeatures query in the pending state.
+ */
+ systemFeatures?: DeepPartial<SystemFeatures> | null
+ queryClient?: QueryClient
+}
+
+type SystemFeaturesWrapper = {
+ queryClient: QueryClient
+ systemFeatures: SystemFeatures | null
+ wrapper: (props: { children: ReactNode }) => ReactElement
+}
+
+export const createSystemFeaturesWrapper = (
+ options: SystemFeaturesTestOptions = {},
+): SystemFeaturesWrapper => {
+ const queryClient = options.queryClient ?? createTestQueryClient()
+ const systemFeatures = options.systemFeatures === null
+ ? null
+ : seedSystemFeatures(queryClient, options.systemFeatures)
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ )
+ return { queryClient, systemFeatures, wrapper }
+}
+
+export const renderWithSystemFeatures = (
+ ui: ReactElement,
+ options: SystemFeaturesTestOptions & Omit<RenderOptions, 'wrapper'> = {},
+): RenderResult & { queryClient: QueryClient, systemFeatures: SystemFeatures | null } => {
+ const { systemFeatures: sf, queryClient: qc, ...renderOptions } = options
+ const { wrapper, queryClient, systemFeatures } = createSystemFeaturesWrapper({
+ systemFeatures: sf,
+ queryClient: qc,
+ })
+ const rendered = render(ui, { wrapper, ...renderOptions })
+ return { ...rendered, queryClient, systemFeatures }
+}
+
+export const renderHookWithSystemFeatures = <Result, Props = void>(
+ callback: (props: Props) => Result,
+ options: SystemFeaturesTestOptions & Omit<RenderHookOptions<Props>, 'wrapper'> = {},
+): RenderHookResult<Result, Props> & { queryClient: QueryClient, systemFeatures: SystemFeatures | null } => {
+ const { systemFeatures: sf, queryClient: qc, ...hookOptions } = options
+ const { wrapper, queryClient, systemFeatures } = createSystemFeaturesWrapper({
+ systemFeatures: sf,
+ queryClient: qc,
+ })
+ const rendered = renderHook(callback, { wrapper, ...hookOptions })
+ return { ...rendered, queryClient, systemFeatures }
+}
diff --git a/web/app/(commonLayout)/error.tsx b/web/app/(commonLayout)/error.tsx
new file mode 100644
index 00000000000..dbc5ded3e95
--- /dev/null
+++ b/web/app/(commonLayout)/error.tsx
@@ -0,0 +1,33 @@
+'use client'
+
+import { Button } from '@langgenius/dify-ui/button'
+import { useTranslation } from 'react-i18next'
+import RootLoading from '@/app/loading'
+import { isLegacyBase401 } from '@/service/use-common'
+
+type Props = {
+ error: Error & { digest?: string }
+ unstable_retry: () => void
+}
+
+export default function CommonLayoutError({ error, unstable_retry }: Props) {
+ const { t } = useTranslation('common')
+
+ // 401 already triggered jumpTo(/signin) inside service/base.ts. Render Loading
+ // until the browser navigation completes, matching main's Splash behavior.
+ // Showing the "Try again" button here would just flash for a few frames before
+ // the page navigates away, and clicking it would 401 again anyway.
+ if (isLegacyBase401(error))
+ return <RootLoading />
+
+ return (
+ <div className="flex h-screen w-screen flex-col items-center justify-center gap-4 bg-background-body">
+ <div className="system-sm-regular text-text-tertiary">
+ {t('errorBoundary.message')}
+ </div>
+ <Button size="small" variant="secondary" onClick={() => unstable_retry()}>
+ {t('errorBoundary.tryAgain')}
+ </Button>
+ </div>
+ )
+}
diff --git a/web/app/(commonLayout)/layout.tsx b/web/app/(commonLayout)/layout.tsx
index 35da7ef7921..2467f35b7bc 100644
--- a/web/app/(commonLayout)/layout.tsx
+++ b/web/app/(commonLayout)/layout.tsx
@@ -14,7 +14,6 @@ import { EventEmitterContextProvider } from '@/context/event-emitter-provider'
import { ModalContextProvider } from '@/context/modal-context-provider'
import { ProviderContextProvider } from '@/context/provider-context-provider'
import PartnerStack from '../components/billing/partner-stack'
-import Splash from '../components/splash'
import RoleRouteGuard from './role-route-guard'
const Layout = ({ children }: { children: ReactNode }) => {
@@ -37,7 +36,6 @@ const Layout = ({ children }: { children: ReactNode }) => {
<PartnerStack />
<ReadmePanel />
<GotoAnything />
- <Splash />
</ModalContextProvider>
</ProviderContextProvider>
</EventEmitterContextProvider>
diff --git a/web/app/(commonLayout)/loading.tsx b/web/app/(commonLayout)/loading.tsx
new file mode 100644
index 00000000000..3a5a14dc252
--- /dev/null
+++ b/web/app/(commonLayout)/loading.tsx
@@ -0,0 +1,9 @@
+import Loading from '@/app/components/base/loading'
+
+export default function CommonLayoutLoading() {
+ return (
+ <div className="flex h-screen w-screen items-center justify-center bg-background-body">
+ <Loading />
+ </div>
+ )
+}
diff --git a/web/app/(shareLayout)/webapp-reset-password/layout.tsx b/web/app/(shareLayout)/webapp-reset-password/layout.tsx
index 1a035bfb443..82749c8641b 100644
--- a/web/app/(shareLayout)/webapp-reset-password/layout.tsx
+++ b/web/app/(shareLayout)/webapp-reset-password/layout.tsx
@@ -1,11 +1,12 @@
'use client'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import Header from '@/app/signin/_header'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
export default function SignInLayout({ children }: any) {
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
return (
<>
<div className={cn('flex min-h-screen w-full justify-center bg-background-default-burn p-6')}>
diff --git a/web/app/(shareLayout)/webapp-signin/components/external-member-sso-auth.tsx b/web/app/(shareLayout)/webapp-signin/components/external-member-sso-auth.tsx
index fe6b157c1e5..003aab4caba 100644
--- a/web/app/(shareLayout)/webapp-signin/components/external-member-sso-auth.tsx
+++ b/web/app/(shareLayout)/webapp-signin/components/external-member-sso-auth.tsx
@@ -1,16 +1,17 @@
'use client'
import { toast } from '@langgenius/dify-ui/toast'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useEffect } from 'react'
import AppUnavailable from '@/app/components/base/app-unavailable'
import Loading from '@/app/components/base/loading'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useRouter, useSearchParams } from '@/next/navigation'
import { fetchWebOAuth2SSOUrl, fetchWebOIDCSSOUrl, fetchWebSAMLSSOUrl } from '@/service/share'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { SSOProtocol } from '@/types/feature'
const ExternalMemberSSOAuth = () => {
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const searchParams = useSearchParams()
const router = useRouter()
diff --git a/web/app/(shareLayout)/webapp-signin/layout.tsx b/web/app/(shareLayout)/webapp-signin/layout.tsx
index 5451b451946..99dd787ceca 100644
--- a/web/app/(shareLayout)/webapp-signin/layout.tsx
+++ b/web/app/(shareLayout)/webapp-signin/layout.tsx
@@ -2,13 +2,14 @@
import type { PropsWithChildren } from 'react'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import useDocumentTitle from '@/hooks/use-document-title'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
export default function SignInLayout({ children }: PropsWithChildren) {
const { t } = useTranslation()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
useDocumentTitle(t('webapp.login', { ns: 'login' }))
return (
<>
diff --git a/web/app/(shareLayout)/webapp-signin/normalForm.tsx b/web/app/(shareLayout)/webapp-signin/normalForm.tsx
index 436c7e64bb3..9b7b64eac57 100644
--- a/web/app/(shareLayout)/webapp-signin/normalForm.tsx
+++ b/web/app/(shareLayout)/webapp-signin/normalForm.tsx
@@ -1,13 +1,14 @@
'use client'
import { cn } from '@langgenius/dify-ui/cn'
import { RiContractLine, RiDoorLockLine, RiErrorWarningFill } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
import { IS_CE_EDITION } from '@/config'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import Link from '@/next/link'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { LicenseStatus } from '@/types/feature'
import MailAndCodeAuth from './components/mail-and-code-auth'
import MailAndPasswordAuth from './components/mail-and-password-auth'
@@ -17,7 +18,7 @@ const NormalForm = () => {
const { t } = useTranslation()
const [isLoading, setIsLoading] = useState(true)
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const [authType, updateAuthType] = useState<'code' | 'password'>('password')
const [showORLine, setShowORLine] = useState(false)
const [allMethodsAreDisabled, setAllMethodsAreDisabled] = useState(false)
diff --git a/web/app/(shareLayout)/webapp-signin/page.tsx b/web/app/(shareLayout)/webapp-signin/page.tsx
index 4b94a7210ff..a1e14ed815c 100644
--- a/web/app/(shareLayout)/webapp-signin/page.tsx
+++ b/web/app/(shareLayout)/webapp-signin/page.tsx
@@ -1,20 +1,21 @@
'use client'
import type { FC } from 'react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import AppUnavailable from '@/app/components/base/app-unavailable'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useWebAppStore } from '@/context/web-app-context'
import { AccessMode } from '@/models/access-control'
import { useRouter, useSearchParams } from '@/next/navigation'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { webAppLogout } from '@/service/webapp-auth'
import ExternalMemberSsoAuth from './components/external-member-sso-auth'
import NormalForm from './normalForm'
const WebSSOForm: FC = () => {
const { t } = useTranslation()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const webAppAccessMode = useWebAppStore(s => s.webAppAccessMode)
const searchParams = useSearchParams()
const router = useRouter()
diff --git a/web/app/account/(commonLayout)/account-page/index.tsx b/web/app/account/(commonLayout)/account-page/index.tsx
index a26fa942db4..09c083b60bc 100644
--- a/web/app/account/(commonLayout)/account-page/index.tsx
+++ b/web/app/account/(commonLayout)/account-page/index.tsx
@@ -7,7 +7,7 @@ import { toast } from '@langgenius/dify-ui/toast'
import {
RiGraduationCapFill,
} from '@remixicon/react'
-import { useQueryClient } from '@tanstack/react-query'
+import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
@@ -15,11 +15,11 @@ import Input from '@/app/components/base/input'
import PremiumBadge from '@/app/components/base/premium-badge'
import Collapse from '@/app/components/header/account-setting/collapse'
import { IS_CE_EDITION, validPassword } from '@/config'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useProviderContext } from '@/context/provider-context'
import { updateUserProfile } from '@/service/common'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useAppList } from '@/service/use-apps'
-import { commonQueryKeys, useUserProfile } from '@/service/use-common'
+import { commonQueryKeys, userProfileQueryOptions } from '@/service/use-common'
import DeleteAccount from '../delete-account'
import AvatarWithEdit from './AvatarWithEdit'
@@ -34,12 +34,13 @@ const descriptionClassName = `
export default function AccountPage() {
const { t } = useTranslation()
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { data: appList } = useAppList({ page: 1, limit: 100, name: '' })
const apps = appList?.data || []
const queryClient = useQueryClient()
- const { data: userProfileResp } = useUserProfile()
- const userProfile = userProfileResp?.profile
+ // Cache is warmed by AppContextProvider's useSuspenseQuery; this hits cache synchronously.
+ const { data: userProfileResp } = useSuspenseQuery(userProfileQueryOptions())
+ const userProfile = userProfileResp.profile
const mutateUserProfile = () => queryClient.invalidateQueries({ queryKey: commonQueryKeys.userProfile })
const { isEducationAccount } = useProviderContext()
const [editNameModalVisible, setEditNameModalVisible] = useState(false)
diff --git a/web/app/account/(commonLayout)/avatar.tsx b/web/app/account/(commonLayout)/avatar.tsx
index 0893b130c45..ccae182c9ab 100644
--- a/web/app/account/(commonLayout)/avatar.tsx
+++ b/web/app/account/(commonLayout)/avatar.tsx
@@ -4,6 +4,7 @@ import { Avatar } from '@langgenius/dify-ui/avatar'
import {
RiGraduationCapFill,
} from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { Fragment } from 'react'
import { useTranslation } from 'react-i18next'
import { resetUser } from '@/app/components/base/amplitude/utils'
@@ -11,13 +12,14 @@ import { LogOut01 } from '@/app/components/base/icons/src/vender/line/general'
import PremiumBadge from '@/app/components/base/premium-badge'
import { useProviderContext } from '@/context/provider-context'
import { useRouter } from '@/next/navigation'
-import { useLogout, useUserProfile } from '@/service/use-common'
+import { useLogout, userProfileQueryOptions } from '@/service/use-common'
export default function AppSelector() {
const router = useRouter()
const { t } = useTranslation()
- const { data: userProfileResp } = useUserProfile()
- const userProfile = userProfileResp?.profile
+ // Cache is warmed by AppContextProvider's useSuspenseQuery; this hits cache synchronously.
+ const { data: userProfileResp } = useSuspenseQuery(userProfileQueryOptions())
+ const userProfile = userProfileResp.profile
const { isEducationAccount } = useProviderContext()
const { mutateAsync: logout } = useLogout()
diff --git a/web/app/account/(commonLayout)/header.tsx b/web/app/account/(commonLayout)/header.tsx
index f0912d45d52..37c1dcdd232 100644
--- a/web/app/account/(commonLayout)/header.tsx
+++ b/web/app/account/(commonLayout)/header.tsx
@@ -1,17 +1,18 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
import { RiArrowRightUpLine, RiRobot2Line } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import DifyLogo from '@/app/components/base/logo/dify-logo'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useRouter } from '@/next/navigation'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import Avatar from './avatar'
const Header = () => {
const { t } = useTranslation()
const router = useRouter()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const goToStudio = useCallback(() => {
router.push('/apps')
diff --git a/web/app/account/oauth/authorize/layout.tsx b/web/app/account/oauth/authorize/layout.tsx
index 9460e7fc542..850fe9c2b5c 100644
--- a/web/app/account/oauth/authorize/layout.tsx
+++ b/web/app/account/oauth/authorize/layout.tsx
@@ -1,20 +1,27 @@
'use client'
import { cn } from '@langgenius/dify-ui/cn'
+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import Loading from '@/app/components/base/loading'
import Header from '@/app/signin/_header'
import { AppContextProvider } from '@/context/app-context-provider'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import useDocumentTitle from '@/hooks/use-document-title'
-import { useIsLogin } from '@/service/use-common'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
+import { isLegacyBase401, userProfileQueryOptions } from '@/service/use-common'
export default function SignInLayout({ children }: any) {
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
useDocumentTitle('')
- const { isLoading, data: loginData } = useIsLogin()
- const isLoggedIn = loginData?.logged_in
+ // Probe login state. 401 stays as `error` (not thrown) so this layout can render
+ // the signin/oauth UI for unauthenticated users; other errors bubble to error.tsx.
+ // (When unauthenticated, service/base.ts's auto-redirect to /signin still fires.)
+ const { isPending, data: userResp, error } = useQuery({
+ ...userProfileQueryOptions(),
+ throwOnError: err => !isLegacyBase401(err),
+ })
+ const isLoggedIn = !!userResp && !error
- if (isLoading) {
+ if (isPending) {
return (
<div className="flex min-h-screen w-full justify-center bg-background-default-burn">
<Loading />
diff --git a/web/app/account/oauth/authorize/page.tsx b/web/app/account/oauth/authorize/page.tsx
index cd035ce16f3..dd95dc04ba6 100644
--- a/web/app/account/oauth/authorize/page.tsx
+++ b/web/app/account/oauth/authorize/page.tsx
@@ -10,6 +10,7 @@ import {
RiMailLine,
RiTranslate2,
} from '@remixicon/react'
+import { useQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
@@ -17,7 +18,7 @@ import Loading from '@/app/components/base/loading'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
import { setPostLoginRedirect } from '@/app/signin/utils/post-login-redirect'
import { useRouter, useSearchParams } from '@/next/navigation'
-import { useIsLogin, useUserProfile } from '@/service/use-common'
+import { isLegacyBase401, userProfileQueryOptions } from '@/service/use-common'
import { useAuthorizeOAuthApp, useOAuthAppInfo } from '@/service/use-oauth'
function buildReturnUrl(pathname: string, search: string) {
@@ -61,15 +62,20 @@ export default function OAuthAuthorize() {
const searchParams = useSearchParams()
const client_id = decodeURIComponent(searchParams.get('client_id') || '')
const redirect_uri = decodeURIComponent(searchParams.get('redirect_uri') || '')
- const { data: userProfileResp } = useUserProfile()
+ // Probe user profile. 401 stays as `error` (legitimate "not logged in" state),
+ // other errors throw to the nearest error.tsx; jumpTo same-pathname guard in
+ // service/base.ts prevents a redirect loop here.
+ const { data: userProfileResp, isPending: isProfileLoading, error: profileError } = useQuery({
+ ...userProfileQueryOptions(),
+ throwOnError: err => !isLegacyBase401(err),
+ })
+ const isLoggedIn = !!userProfileResp && !profileError
const userProfile = userProfileResp?.profile
const { data: authAppInfo, isLoading: isOAuthLoading, isError } = useOAuthAppInfo(client_id, redirect_uri)
const { mutateAsync: authorize, isPending: authorizing } = useAuthorizeOAuthApp()
const hasNotifiedRef = useRef(false)
- const { isLoading: isIsLoginLoading, data: loginData } = useIsLogin()
- const isLoggedIn = loginData?.logged_in
- const isLoading = isOAuthLoading || isIsLoginLoading
+ const isLoading = isOAuthLoading || isProfileLoading
const onLoginSwitchClick = () => {
try {
const returnUrl = buildReturnUrl('/account/oauth/authorize', `?client_id=${encodeURIComponent(client_id)}&redirect_uri=${encodeURIComponent(redirect_uri)}`)
diff --git a/web/app/activate/page.tsx b/web/app/activate/page.tsx
index e7ab413005a..995227ec6eb 100644
--- a/web/app/activate/page.tsx
+++ b/web/app/activate/page.tsx
@@ -1,12 +1,13 @@
'use client'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import Header from '../signin/_header'
import ActivateForm from './activateForm'
const Activate = () => {
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
return (
<div className={cn('flex min-h-screen w-full justify-center bg-background-default-burn p-6')}>
<div className={cn('flex w-full shrink-0 flex-col rounded-2xl border border-effects-highlight bg-background-default-subtle')}>
diff --git a/web/app/components/__tests__/splash.spec.tsx b/web/app/components/__tests__/splash.spec.tsx
deleted file mode 100644
index 296ef48cdb0..00000000000
--- a/web/app/components/__tests__/splash.spec.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import type { MockedFunction } from 'vitest'
-import { render, screen } from '@testing-library/react'
-import { useUserProfile } from '@/service/use-common'
-import Splash from '../splash'
-
-vi.mock('@/service/use-common', () => ({
- useUserProfile: vi.fn(),
-}))
-
-const mockUseUserProfile = useUserProfile as MockedFunction<typeof useUserProfile>
-
-describe('Splash', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('should render the loading indicator while the profile query is pending', () => {
- mockUseUserProfile.mockReturnValue({
- isPending: true,
- isError: false,
- data: undefined,
- } as ReturnType<typeof useUserProfile>)
-
- render(<Splash />)
-
- expect(screen.getByRole('status')).toBeInTheDocument()
- })
-
- it('should not render the loading indicator when the profile query succeeds', () => {
- mockUseUserProfile.mockReturnValue({
- isPending: false,
- isError: false,
- data: {
- profile: { id: 'user-1' },
- meta: {
- currentVersion: '1.13.3',
- currentEnv: 'DEVELOPMENT',
- },
- },
- } as ReturnType<typeof useUserProfile>)
-
- render(<Splash />)
-
- expect(screen.queryByRole('status')).not.toBeInTheDocument()
- })
-
- it('should stop rendering the loading indicator when the profile query errors', () => {
- mockUseUserProfile.mockReturnValue({
- isPending: false,
- isError: true,
- data: undefined,
- error: new Error('profile request failed'),
- } as ReturnType<typeof useUserProfile>)
-
- render(<Splash />)
-
- expect(screen.queryByRole('status')).not.toBeInTheDocument()
- })
-})
diff --git a/web/app/components/app-initializer.tsx b/web/app/components/app-initializer.tsx
index e08ece6666c..2c503125908 100644
--- a/web/app/components/app-initializer.tsx
+++ b/web/app/components/app-initializer.tsx
@@ -8,6 +8,7 @@ import {
EDUCATION_VERIFY_URL_SEARCHPARAMS_ACTION,
EDUCATION_VERIFYING_LOCALSTORAGE_ITEM,
} from '@/app/education-apply/constants'
+import RootLoading from '@/app/loading'
import { usePathname, useRouter, useSearchParams } from '@/next/navigation'
import { sendGAEvent } from '@/utils/gtag'
import { fetchSetupStatusWithCache } from '@/utils/setup-status'
@@ -98,5 +99,5 @@ export const AppInitializer = ({
})()
}, [isSetupFinished, router, pathname, searchParams, oauthNewUser])
- return init ? children : null
+ return init ? children : <RootLoading />
}
diff --git a/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx b/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx
index bbac21942e3..21dd8c5fc2e 100644
--- a/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx
+++ b/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx
@@ -2,8 +2,9 @@
import type { AccessControlAccount, AccessControlGroup, Subject } from '@/models/access-control'
import type { App } from '@/types/app'
import { toast } from '@langgenius/dify-ui/toast'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { renderWithSystemFeatures as render } from '@/__tests__/utils/mock-system-features'
import useAccessControlStore from '@/context/access-control-store'
import { AccessMode, SubjectType } from '@/models/access-control'
import AccessControlDialog from '../access-control-dialog'
diff --git a/web/app/components/app/app-access-control/__tests__/index.spec.tsx b/web/app/components/app/app-access-control/__tests__/index.spec.tsx
index 05b86f0290d..74e7d7046c0 100644
--- a/web/app/components/app/app-access-control/__tests__/index.spec.tsx
+++ b/web/app/components/app/app-access-control/__tests__/index.spec.tsx
@@ -1,17 +1,12 @@
+import type { ReactElement } from 'react'
import type { App } from '@/types/app'
import { toast } from '@langgenius/dify-ui/toast'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import useAccessControlStore from '@/context/access-control-store'
import { AccessMode } from '@/models/access-control'
import AccessControl from '../index'
-const mockMutateAsync = vi.fn()
-const mockUseUpdateAccessMode = vi.fn(() => ({
- isPending: false,
- mutateAsync: mockMutateAsync,
-}))
-const mockUseAppWhiteListSubjects = vi.fn()
-const mockUseSearchForWhiteListCandidates = vi.fn()
let mockWebappAuth = {
enabled: true,
allow_sso: true,
@@ -19,13 +14,17 @@ let mockWebappAuth = {
allow_email_code_login: false,
}
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { webapp_auth: typeof mockWebappAuth } }) => unknown) => selector({
- systemFeatures: {
- webapp_auth: mockWebappAuth,
- },
- }),
+const render = (ui: ReactElement) => renderWithSystemFeatures(ui, {
+ systemFeatures: { webapp_auth: mockWebappAuth },
+})
+
+const mockMutateAsync = vi.fn()
+const mockUseUpdateAccessMode = vi.fn(() => ({
+ isPending: false,
+ mutateAsync: mockMutateAsync,
}))
+const mockUseAppWhiteListSubjects = vi.fn()
+const mockUseSearchForWhiteListCandidates = vi.fn()
vi.mock('@/service/access-control', () => ({
useAppWhiteListSubjects: (...args: unknown[]) => mockUseAppWhiteListSubjects(...args),
diff --git a/web/app/components/app/app-access-control/index.tsx b/web/app/components/app/app-access-control/index.tsx
index 2997d4b4cf8..cff670e10fa 100644
--- a/web/app/components/app/app-access-control/index.tsx
+++ b/web/app/components/app/app-access-control/index.tsx
@@ -5,11 +5,12 @@ import { Description as DialogDescription, DialogTitle } from '@headlessui/react
import { Button } from '@langgenius/dify-ui/button'
import { toast } from '@langgenius/dify-ui/toast'
import { RiBuildingLine, RiGlobalLine, RiVerifiedBadgeLine } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { AccessMode, SubjectType } from '@/models/access-control'
import { useUpdateAccessMode } from '@/service/access-control'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import useAccessControlStore from '../../../../context/access-control-store'
import AccessControlDialog from './access-control-dialog'
import AccessControlItem from './access-control-item'
@@ -24,7 +25,7 @@ type AccessControlProps = {
export default function AccessControl(props: AccessControlProps) {
const { app, onClose, onConfirm } = props
const { t } = useTranslation()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const setAppId = useAccessControlStore(s => s.setAppId)
const specificGroups = useAccessControlStore(s => s.specificGroups)
const specificMembers = useAccessControlStore(s => s.specificMembers)
diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
index 06d91e9400c..aa9cda8e347 100644
--- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
@@ -1,11 +1,16 @@
/* eslint-disable ts/no-explicit-any */
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { AccessMode } from '@/models/access-control'
import { AppModeEnum } from '@/types/app'
import { basePath } from '@/utils/var'
import AppPublisher from '../index'
+const render = (ui: React.ReactElement) => renderWithSystemFeatures(ui, {
+ systemFeatures: { webapp_auth: { enabled: true } },
+})
+
const mockOnPublish = vi.fn()
const mockOnToggle = vi.fn()
const mockSetAppDetail = vi.fn()
@@ -49,16 +54,6 @@ vi.mock('@/app/components/app/store', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { webapp_auth: { enabled: boolean } } }) => unknown) => selector({
- systemFeatures: {
- webapp_auth: {
- enabled: true,
- },
- },
- }),
-}))
-
vi.mock('@/hooks/use-format-time-from-now', () => ({
useFormatTimeFromNow: () => ({
formatTimeFromNow: () => 'moments ago',
diff --git a/web/app/components/app/app-publisher/index.tsx b/web/app/components/app/app-publisher/index.tsx
index 562f2d77595..b85e888557b 100644
--- a/web/app/components/app/app-publisher/index.tsx
+++ b/web/app/components/app/app-publisher/index.tsx
@@ -5,6 +5,7 @@ import type { PublishWorkflowParams } from '@/types/workflow'
import { Button } from '@langgenius/dify-ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { toast } from '@langgenius/dify-ui/toast'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useKeyPress } from 'ahooks'
import {
memo,
@@ -21,13 +22,13 @@ import { trackEvent } from '@/app/components/base/amplitude'
import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'
import { webSocketClient } from '@/app/components/workflow/collaboration/core/websocket-manager'
import { WorkflowContext } from '@/app/components/workflow/context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useAsyncWindowOpen } from '@/hooks/use-async-window-open'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import { AccessMode } from '@/models/access-control'
import { useAppWhiteListSubjects, useGetUserCanAccessApp } from '@/service/access-control'
import { fetchAppDetailDirect } from '@/service/apps'
import { fetchInstalledAppList } from '@/service/explore'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useInvalidateAppWorkflow } from '@/service/use-workflow'
import { fetchPublishedWorkflow } from '@/service/workflow'
import { AppModeEnum } from '@/types/app'
@@ -103,7 +104,7 @@ const AppPublisher = ({
const workflowStore = useContext(WorkflowContext)
const appDetail = useAppStore(state => state.appDetail)
const setAppDetail = useAppStore(s => s.setAppDetail)
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { formatTimeFromNow } = useFormatTimeFromNow()
const { app_base_url: appBaseURL = '', access_token: accessToken = '' } = appDetail?.site ?? {}
diff --git a/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx b/web/app/components/app/create-app-dialog/app-card/__tests__/index.spec.tsx
index 2d76c12b681..16971f77d5b 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,8 +1,9 @@
/* eslint-disable ts/no-explicit-any */
import type { App } from '@/models/explore'
import type { AppIconType } from '@/types/app'
-import { render, screen, within } from '@testing-library/react'
+import { screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { renderWithSystemFeatures as render } from '@/__tests__/utils/mock-system-features'
import { trackEvent } from '@/app/components/base/amplitude'
import AppListContext from '@/context/app-list-context'
import { AppModeEnum } from '@/types/app'
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.tsx
index 65bd74344aa..e710e214367 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
@@ -4,13 +4,14 @@ import { PlusIcon } from '@heroicons/react/20/solid'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { RiInformation2Line } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useContextSelector } from 'use-context-selector'
import { trackEvent } from '@/app/components/base/amplitude'
import AppIcon from '@/app/components/base/app-icon'
import AppListContext from '@/context/app-list-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { AppTypeIcon, AppTypeLabel } from '../../type-selector'
type AppCardProps = {
@@ -26,7 +27,7 @@ const AppCard = ({
}: AppCardProps) => {
const { t } = useTranslation()
const { app: appBasicInfo } = app
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const isTrialApp = app.can_trial && systemFeatures.enable_trial_app
const setShowTryAppPanel = useContextSelector(AppListContext, ctx => ctx.setShowTryAppPanel)
const handleShowTryAppPanel = useCallback(() => {
diff --git a/web/app/components/app/overview/__tests__/app-card.spec.tsx b/web/app/components/app/overview/__tests__/app-card.spec.tsx
index 0f67093e479..43c0887566c 100644
--- a/web/app/components/app/overview/__tests__/app-card.spec.tsx
+++ b/web/app/components/app/overview/__tests__/app-card.spec.tsx
@@ -1,11 +1,16 @@
-import type { ReactNode } from 'react'
+import type { ReactElement, ReactNode } from 'react'
import type { AppDetailResponse } from '@/models/app'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { AccessMode } from '@/models/access-control'
import { AppModeEnum } from '@/types/app'
import { basePath } from '@/utils/var'
import AppCard from '../app-card'
+const render = (ui: ReactElement) => renderWithSystemFeatures(ui, {
+ systemFeatures: { webapp_auth: { enabled: true } },
+})
+
const mockFetchAppDetailDirect = vi.fn()
const mockPush = vi.fn()
const mockSetAppDetail = vi.fn()
@@ -36,16 +41,6 @@ vi.mock('@/context/i18n', () => ({
useDocLink: () => (path: string) => `https://docs.example.com${path}`,
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { webapp_auth: { enabled: boolean } } }) => unknown) => selector({
- systemFeatures: {
- webapp_auth: {
- enabled: true,
- },
- },
- }),
-}))
-
vi.mock('@/app/components/app/store', () => ({
useStore: (selector: (state: { appDetail: AppDetailResponse, setAppDetail: typeof mockSetAppDetail }) => unknown) => selector({
appDetail: mockAppDetail as AppDetailResponse,
diff --git a/web/app/components/app/overview/app-card.tsx b/web/app/components/app/overview/app-card.tsx
index 5cfe3f65ac0..f0502ae918c 100644
--- a/web/app/components/app/overview/app-card.tsx
+++ b/web/app/components/app/overview/app-card.tsx
@@ -3,6 +3,7 @@ import type { ConfigParams } from './settings'
import type { AppDetailResponse } from '@/models/app'
import type { AppSSO } from '@/types/app'
import { Switch } from '@langgenius/dify-ui/switch'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -12,12 +13,12 @@ import Tooltip from '@/app/components/base/tooltip'
import SecretKeyButton from '@/app/components/develop/secret-key/secret-key-button'
import Indicator from '@/app/components/header/indicator'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useDocLink } from '@/context/i18n'
import { AccessMode } from '@/models/access-control'
import { usePathname, useRouter } from '@/next/navigation'
import { useAppWhiteListSubjects } from '@/service/access-control'
import { fetchAppDetailDirect } from '@/service/apps'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useAppWorkflow } from '@/service/use-workflow'
import { AppModeEnum } from '@/types/app'
import { asyncRunSafe } from '@/utils'
@@ -73,7 +74,7 @@ function AppCard({
const [showConfirmDelete, setShowConfirmDelete] = useState(false)
const [showAccessControl, setShowAccessControl] = useState(false)
const { t } = useTranslation()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { data: appAccessSubjects } = useAppWhiteListSubjects(
appDetail?.id,
systemFeatures.webapp_auth.enabled && appDetail?.access_mode === AccessMode.SPECIFIC_GROUPS_MEMBERS,
diff --git a/web/app/components/apps/__tests__/app-card.spec.tsx b/web/app/components/apps/__tests__/app-card.spec.tsx
index 0c80ee000e1..6a71dbac52f 100644
--- a/web/app/components/apps/__tests__/app-card.spec.tsx
+++ b/web/app/components/apps/__tests__/app-card.spec.tsx
@@ -1,7 +1,8 @@
import type { Mock } from 'vitest'
import type { App } from '@/types/app'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { AccessMode } from '@/models/access-control'
import * as appsService from '@/service/apps'
import * as exploreService from '@/service/explore'
@@ -9,6 +10,15 @@ import * as workflowService from '@/service/workflow'
import { AppModeEnum } from '@/types/app'
import AppCard from '../app-card'
+let mockWebappAuthEnabled = false
+
+const render = (ui: React.ReactElement) => renderWithSystemFeatures(ui, {
+ systemFeatures: {
+ webapp_auth: { enabled: mockWebappAuthEnabled },
+ branding: { enabled: false },
+ },
+})
+
// Mock next/navigation
const mockPush = vi.fn()
vi.mock('@/next/navigation', () => ({
@@ -65,16 +75,7 @@ vi.mock('@/context/provider-context', () => ({
}),
}))
-// Mock global public store - allow dynamic configuration
-let mockWebappAuthEnabled = false
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (s: Record<string, unknown>) => unknown) => selector({
- systemFeatures: {
- webapp_auth: { enabled: mockWebappAuthEnabled },
- branding: { enabled: false },
- },
- }),
-}))
+// systemFeatures is seeded into the QueryClient via the local render helper.
vi.mock('@/service/apps', () => ({
deleteApp: vi.fn(() => Promise.resolve()),
diff --git a/web/app/components/apps/__tests__/list.spec.tsx b/web/app/components/apps/__tests__/list.spec.tsx
index eddcb31d604..c3ce96255ab 100644
--- a/web/app/components/apps/__tests__/list.spec.tsx
+++ b/web/app/components/apps/__tests__/list.spec.tsx
@@ -1,5 +1,6 @@
import { act, fireEvent, screen } from '@testing-library/react'
import * as React from 'react'
+import { createSystemFeaturesWrapper } from '@/__tests__/utils/mock-system-features'
import { useStore as useTagStore } from '@/app/components/base/tag-management/store'
import { renderWithNuqs } from '@/test/nuqs-testing'
import { AppModeEnum } from '@/types/app'
@@ -22,14 +23,6 @@ vi.mock('@/context/app-context', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: () => ({
- systemFeatures: {
- branding: { enabled: false },
- },
- }),
-}))
-
const mockSetQuery = vi.fn()
const mockQueryState = {
tagIDs: [] as string[],
@@ -192,9 +185,13 @@ beforeAll(() => {
} as unknown as typeof IntersectionObserver
})
-// Render helper wrapping with shared nuqs testing helper.
+// Render helper wrapping with shared nuqs testing helper plus a seeded
+// systemFeatures cache so List can resolve its useSuspenseQuery.
const renderList = (searchParams = '') => {
- return renderWithNuqs(<List />, { searchParams })
+ const { wrapper: SystemFeaturesWrapper } = createSystemFeaturesWrapper({
+ systemFeatures: { branding: { enabled: false } },
+ })
+ return renderWithNuqs(<SystemFeaturesWrapper><List /></SystemFeaturesWrapper>, { searchParams })
}
describe('List', () => {
@@ -390,7 +387,7 @@ describe('List', () => {
describe('Edge Cases', () => {
it('should handle multiple renders without issues', () => {
- const { unmount } = renderWithNuqs(<List />)
+ const { unmount } = renderList()
expect(screen.getByText('app.types.all'))!.toBeInTheDocument()
unmount()
diff --git a/web/app/components/apps/app-card.tsx b/web/app/components/apps/app-card.tsx
index d0bd9967c48..80aab3ce4dc 100644
--- a/web/app/components/apps/app-card.tsx
+++ b/web/app/components/apps/app-card.tsx
@@ -24,6 +24,7 @@ import {
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
import { toast } from '@langgenius/dify-ui/toast'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useEffect, useId, useMemo, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
@@ -35,7 +36,6 @@ import Tooltip from '@/app/components/base/tooltip'
import { UserAvatarList } from '@/app/components/base/user-avatar-list'
import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useProviderContext } from '@/context/provider-context'
import { useAsyncWindowOpen } from '@/hooks/use-async-window-open'
import { AccessMode } from '@/models/access-control'
@@ -44,6 +44,7 @@ import { useRouter } from '@/next/navigation'
import { useGetUserCanAccessApp } from '@/service/access-control'
import { copyApp, exportAppConfig, updateAppInfo } from '@/service/apps'
import { fetchInstalledAppList } from '@/service/explore'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useDeleteAppMutation } from '@/service/use-apps'
import { fetchWorkflowDraft } from '@/service/workflow'
import { AppModeEnum } from '@/types/app'
@@ -182,7 +183,7 @@ const AppCardOperationsMenu: React.FC<AppCardOperationsMenuProps> = ({
type AppCardOperationsMenuContentProps = Omit<AppCardOperationsMenuProps, 'shouldShowOpenInExploreOption'>
const AppCardOperationsMenuContent: React.FC<AppCardOperationsMenuContentProps> = (props) => {
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { data: userCanAccessApp, isLoading: isGettingUserCanAccessApp } = useGetUserCanAccessApp({
appId: props.app.id,
enabled: systemFeatures.webapp_auth.enabled,
@@ -205,7 +206,7 @@ const AppCardOperationsMenuContent: React.FC<AppCardOperationsMenuContentProps>
const AppCard = ({ app, onlineUsers = [], onRefresh }: AppCardProps) => {
const { t } = useTranslation()
const deleteAppNameInputId = useId()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { isCurrentWorkspaceEditor } = useAppContext()
const { onPlanInfoChanged } = useProviderContext()
const { push } = useRouter()
diff --git a/web/app/components/apps/list.tsx b/web/app/components/apps/list.tsx
index 3b8784ae453..d1bdf533fe1 100644
--- a/web/app/components/apps/list.tsx
+++ b/web/app/components/apps/list.tsx
@@ -3,6 +3,7 @@
import type { FC } from 'react'
import type { WorkflowOnlineUser } from '@/models/app'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useDebounceFn } from 'ahooks'
import { parseAsStringLiteral, useQueryState } from 'nuqs'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
@@ -14,10 +15,10 @@ import TagFilter from '@/app/components/base/tag-management/filter'
import { useStore as useTagStore } from '@/app/components/base/tag-management/store'
import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { CheckModal } from '@/hooks/use-pay'
import dynamic from '@/next/dynamic'
import { fetchWorkflowOnlineUsers } from '@/service/apps'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useInfiniteAppList } from '@/service/use-apps'
import { AppModeEnum, AppModes } from '@/types/app'
import AppCard from './app-card'
@@ -54,7 +55,7 @@ const List: FC<Props> = ({
controlRefreshList = 0,
}) => {
const { t } = useTranslation()
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { isCurrentWorkspaceEditor, isCurrentWorkspaceDatasetOperator, isLoadingCurrentWorkspace } = useAppContext()
const showTagManagementModal = useTagStore(s => s.showTagManagementModal)
const [activeTab, setActiveTab] = useQueryState(
diff --git a/web/app/components/base/chat/chat-with-history/__tests__/header-in-mobile.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/header-in-mobile.spec.tsx
index af58a29fccb..4cbe4ce8d13 100644
--- a/web/app/components/base/chat/chat-with-history/__tests__/header-in-mobile.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/__tests__/header-in-mobile.spec.tsx
@@ -2,8 +2,9 @@ import type { i18n } from 'i18next'
import type { ChatConfig } from '../../types'
import type { ChatWithHistoryContextValue } from '../context'
import type { AppData, AppMeta } from '@/models/share'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import * as ReactI18next from 'react-i18next'
+import { renderWithSystemFeatures as render } from '@/__tests__/utils/mock-system-features'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import { useChatWithHistoryContext } from '../context'
import HeaderInMobile from '../header-in-mobile'
diff --git a/web/app/components/base/chat/chat-with-history/__tests__/index.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/index.spec.tsx
index e3065691408..c9398ee9272 100644
--- a/web/app/components/base/chat/chat-with-history/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/__tests__/index.spec.tsx
@@ -2,7 +2,8 @@ import type { RefObject } from 'react'
import type { ChatConfig } from '../../types'
import type { InstalledApp } from '@/models/explore'
import type { AppConversationData, AppData, AppMeta, ConversationItem } from '@/models/share'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { renderWithSystemFeatures as render } from '@/__tests__/utils/mock-system-features'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import useDocumentTitle from '@/hooks/use-document-title'
import { useChatWithHistory } from '../hooks'
diff --git a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
index 948700c2ced..170f6d7fb5d 100644
--- a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
@@ -1,23 +1,18 @@
+import type { ReactElement } from 'react'
import type { ChatWithHistoryContextValue } from '../../context'
-import { render, screen, waitFor, within } from '@testing-library/react'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import * as ReactI18next from 'react-i18next'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useChatWithHistoryContext } from '../../context'
import Sidebar from '../index'
import RenameModal from '../rename-modal'
-// Type for mocking the global public store selector
-type GlobalPublicStoreMock = {
- systemFeatures: {
- branding: {
- enabled: boolean
- workspace_logo: string | null
- }
- }
- setSystemFeatures?: (features: unknown) => void
-}
+let mockBranding: { enabled: boolean, workspace_logo: string } = { enabled: false, workspace_logo: '' }
+const render = (ui: ReactElement) => renderWithSystemFeatures(ui, {
+ systemFeatures: { branding: { ...mockBranding } },
+})
function mockUseTranslationWithEmptyKeys(emptyKeys: string[]) {
const originalUseTranslation = ReactI18next.useTranslation
@@ -38,19 +33,6 @@ function mockUseTranslationWithEmptyKeys(emptyKeys: string[]) {
})
}
-// Helper to create properly-typed mock store state
-function createMockStoreState(overrides: Partial<GlobalPublicStoreMock>): GlobalPublicStoreMock {
- return {
- systemFeatures: {
- branding: {
- enabled: false,
- workspace_logo: null,
- },
- },
- ...overrides,
- }
-}
-
// Mock List to allow us to trigger operations
vi.mock('../list', () => ({
default: ({ list, onOperate, title, isPin }: { list: Array<{ id: string, name: string }>, onOperate: (type: string, item: { id: string, name: string }) => void, title?: string, isPin?: boolean }) => (
@@ -74,18 +56,6 @@ vi.mock('../../context', () => ({
useChatWithHistoryContext: vi.fn(),
}))
-// Mock global public store
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(selector => selector({
- systemFeatures: {
- branding: {
- enabled: false,
- workspace_logo: null,
- },
- },
- })),
-}))
-
// Mock next/navigation
vi.mock('@/next/navigation', () => ({
useRouter: () => ({ push: vi.fn() }),
@@ -139,8 +109,8 @@ describe('Sidebar Index', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockBranding = { enabled: false, workspace_logo: '' }
vi.mocked(useChatWithHistoryContext).mockReturnValue(mockContextValue)
- vi.mocked(useGlobalPublicStore).mockImplementation(selector => selector(createMockStoreState({}) as never))
})
describe('Basic Rendering', () => {
@@ -658,17 +628,7 @@ describe('Sidebar Index', () => {
})
it('should use system branding logo when enabled', () => {
- const mockStoreState = createMockStoreState({
- systemFeatures: {
- branding: {
- enabled: true,
- workspace_logo: 'http://example.com/workspace-logo.png',
- },
- },
- })
-
- vi.mocked(useGlobalPublicStore).mockClear()
- vi.mocked(useGlobalPublicStore).mockImplementation(selector => selector(mockStoreState as never))
+ mockBranding = { enabled: true, workspace_logo: 'http://example.com/workspace-logo.png' }
vi.mocked(useChatWithHistoryContext).mockReturnValue({
...mockContextValue,
diff --git a/web/app/components/base/chat/chat-with-history/sidebar/index.tsx b/web/app/components/base/chat/chat-with-history/sidebar/index.tsx
index 999f0353012..74efb91e83d 100644
--- a/web/app/components/base/chat/chat-with-history/sidebar/index.tsx
+++ b/web/app/components/base/chat/chat-with-history/sidebar/index.tsx
@@ -15,6 +15,7 @@ import {
RiExpandRightLine,
RiLayoutLeft2Line,
} from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import {
useCallback,
useState,
@@ -26,7 +27,7 @@ import List from '@/app/components/base/chat/chat-with-history/sidebar/list'
import RenameModal from '@/app/components/base/chat/chat-with-history/sidebar/rename-modal'
import DifyLogo from '@/app/components/base/logo/dify-logo'
import MenuDropdown from '@/app/components/share/text-generation/menu-dropdown'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useChatWithHistoryContext } from '../context'
type Props = {
@@ -55,7 +56,7 @@ const Sidebar = ({ isPanel, panelVisible }: Props) => {
isResponding,
} = useChatWithHistoryContext()
const isSidebarCollapsed = sidebarCollapseState
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const [showConfirm, setShowConfirm] = useState<ConversationItem | null>(null)
const [showRename, setShowRename] = useState<ConversationItem | null>(null)
diff --git a/web/app/components/base/chat/embedded-chatbot/__tests__/index.spec.tsx b/web/app/components/base/chat/embedded-chatbot/__tests__/index.spec.tsx
index a87c2064121..0cd22c97be7 100644
--- a/web/app/components/base/chat/embedded-chatbot/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/__tests__/index.spec.tsx
@@ -1,14 +1,20 @@
-import type { RefObject } from 'react'
+import type { ReactElement, RefObject } from 'react'
import type { ChatConfig } from '../../types'
import type { AppData, AppMeta, ConversationItem } from '@/models/share'
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import { vi } from 'vitest'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
-import { defaultSystemFeatures } from '@/types/feature'
import { useEmbeddedChatbot } from '../hooks'
import EmbeddedChatbot from '../index'
+let mockBrandingWorkspaceLogo = ''
+const render = (ui: ReactElement) => renderWithSystemFeatures(ui, {
+ systemFeatures: {
+ branding: { enabled: true, workspace_logo: mockBrandingWorkspaceLogo },
+ },
+})
+
vi.mock('../hooks', () => ({
useEmbeddedChatbot: vi.fn(),
}))
@@ -26,10 +32,6 @@ vi.mock('@/hooks/use-document-title', () => ({
default: vi.fn(),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
vi.mock('../chat-wrapper', () => ({
__esModule: true,
default: () => <div>chat area</div>,
@@ -125,19 +127,9 @@ const createHookReturn = (overrides: Partial<EmbeddedChatbotHookReturn> = {}): E
describe('EmbeddedChatbot index', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockBrandingWorkspaceLogo = ''
vi.mocked(useBreakpoints).mockReturnValue(MediaType.mobile)
vi.mocked(useEmbeddedChatbot).mockReturnValue(createHookReturn())
- vi.mocked(useGlobalPublicStore).mockImplementation(selector => selector({
- systemFeatures: {
- ...defaultSystemFeatures,
- branding: {
- ...defaultSystemFeatures.branding,
- enabled: true,
- workspace_logo: '',
- },
- },
- setSystemFeatures: vi.fn(),
- }))
})
describe('Loading and chat content', () => {
@@ -159,17 +151,7 @@ describe('EmbeddedChatbot index', () => {
describe('Powered by branding', () => {
it('should show workspace logo on mobile when branding is enabled', () => {
- vi.mocked(useGlobalPublicStore).mockImplementation(selector => selector({
- systemFeatures: {
- ...defaultSystemFeatures,
- branding: {
- ...defaultSystemFeatures.branding,
- enabled: true,
- workspace_logo: 'https://example.com/workspace-logo.png',
- },
- },
- setSystemFeatures: vi.fn(),
- }))
+ mockBrandingWorkspaceLogo = 'https://example.com/workspace-logo.png'
render(<EmbeddedChatbot />)
diff --git a/web/app/components/base/chat/embedded-chatbot/header/__tests__/index.spec.tsx b/web/app/components/base/chat/embedded-chatbot/header/__tests__/index.spec.tsx
index 50ba15ae615..3142bcd315e 100644
--- a/web/app/components/base/chat/embedded-chatbot/header/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/header/__tests__/index.spec.tsx
@@ -1,30 +1,25 @@
+import type { ReactElement } from 'react'
import type { EmbeddedChatbotContextValue } from '../../context'
import type { AppData } from '@/models/share'
-import type { SystemFeatures } from '@/types/feature'
-import { act, render, screen, waitFor } from '@testing-library/react'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { useGlobalPublicStore } from '@/context/global-public-context'
-import { InstallationScope, LicenseStatus } from '@/types/feature'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useEmbeddedChatbotContext } from '../../context'
import Header from '../index'
+let mockBranding = { enabled: true, workspace_logo: '' }
+const render = (ui: ReactElement) => renderWithSystemFeatures(ui, {
+ systemFeatures: { branding: { ...mockBranding } },
+})
+
vi.mock('../../context', () => ({
useEmbeddedChatbotContext: vi.fn(),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
vi.mock('@/app/components/base/chat/embedded-chatbot/inputs-form/view-form-dropdown', () => ({
default: () => <div data-testid="view-form-dropdown" />,
}))
-type GlobalPublicStoreMock = {
- systemFeatures: SystemFeatures
- setSystemFeatures: (systemFeatures: SystemFeatures) => void
-}
-
describe('EmbeddedChatbot Header', () => {
const defaultAppData: AppData = {
app_id: 'test-app-id',
@@ -47,48 +42,6 @@ describe('EmbeddedChatbot Header', () => {
allInputsHidden: false,
}
- const defaultSystemFeatures: SystemFeatures = {
- app_dsl_version: '',
- trial_models: [],
- plugin_installation_permission: {
- plugin_installation_scope: InstallationScope.ALL,
- restrict_to_marketplace_only: false,
- },
- sso_enforced_for_signin: false,
- sso_enforced_for_signin_protocol: '',
- sso_enforced_for_web: false,
- sso_enforced_for_web_protocol: '',
- enable_marketplace: false,
- enable_change_email: false,
- enable_email_code_login: false,
- enable_email_password_login: false,
- enable_social_oauth_login: false,
- is_allow_create_workspace: false,
- is_allow_register: false,
- is_email_setup: false,
- license: {
- status: LicenseStatus.NONE,
- expired_at: '',
- },
- branding: {
- enabled: true,
- workspace_logo: '',
- login_page_logo: '',
- favicon: '',
- application_title: '',
- },
- webapp_auth: {
- enabled: false,
- allow_sso: false,
- sso_config: { protocol: '' },
- allow_email_code_login: false,
- allow_email_password_login: false,
- },
- enable_collaboration_mode: false,
- enable_trial_app: false,
- enable_explore_banner: false,
- }
-
const setupIframe = () => {
const mockPostMessage = vi.fn()
const mockTop = { postMessage: mockPostMessage }
@@ -100,11 +53,8 @@ describe('EmbeddedChatbot Header', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockBranding = { enabled: true, workspace_logo: '' }
vi.mocked(useEmbeddedChatbotContext).mockReturnValue(defaultContext as EmbeddedChatbotContextValue)
- vi.mocked(useGlobalPublicStore).mockImplementation((selector: (s: GlobalPublicStoreMock) => unknown) => selector({
- systemFeatures: defaultSystemFeatures,
- setSystemFeatures: vi.fn(),
- }))
Object.defineProperty(window, 'self', { value: window, configurable: true })
Object.defineProperty(window, 'top', { value: window, configurable: true })
@@ -149,16 +99,7 @@ describe('EmbeddedChatbot Header', () => {
})
it('should render workspace logo when branding is enabled and logo exists', () => {
- vi.mocked(useGlobalPublicStore).mockImplementation((selector: (s: GlobalPublicStoreMock) => unknown) => selector({
- systemFeatures: {
- ...defaultSystemFeatures,
- branding: {
- ...defaultSystemFeatures.branding,
- workspace_logo: 'https://example.com/workspace.png',
- },
- },
- setSystemFeatures: vi.fn(),
- }))
+ mockBranding = { enabled: true, workspace_logo: 'https://example.com/workspace.png' }
render(<Header title="Test Chatbot" />)
@@ -167,32 +108,13 @@ describe('EmbeddedChatbot Header', () => {
})
it('should render Dify logo by default when branding enabled is true but no logo provided', () => {
- vi.mocked(useGlobalPublicStore).mockImplementation((selector: (s: GlobalPublicStoreMock) => unknown) => selector({
- systemFeatures: {
- ...defaultSystemFeatures,
- branding: {
- ...defaultSystemFeatures.branding,
- enabled: true,
- workspace_logo: '',
- },
- },
- setSystemFeatures: vi.fn(),
- }))
+ mockBranding = { enabled: true, workspace_logo: '' }
render(<Header title="Test Chatbot" />)
expect(screen.getByAltText('Dify logo')).toBeInTheDocument()
})
it('should render Dify logo when branding is disabled', () => {
- vi.mocked(useGlobalPublicStore).mockImplementation((selector: (s: GlobalPublicStoreMock) => unknown) => selector({
- systemFeatures: {
- ...defaultSystemFeatures,
- branding: {
- ...defaultSystemFeatures.branding,
- enabled: false,
- },
- },
- setSystemFeatures: vi.fn(),
- }))
+ mockBranding = { enabled: false, workspace_logo: '' }
render(<Header title="Test Chatbot" />)
expect(screen.getByAltText('Dify logo')).toBeInTheDocument()
})
diff --git a/web/app/components/base/chat/embedded-chatbot/header/index.tsx b/web/app/components/base/chat/embedded-chatbot/header/index.tsx
index aeec29a477b..598e3068dee 100644
--- a/web/app/components/base/chat/embedded-chatbot/header/index.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/header/index.tsx
@@ -1,6 +1,7 @@
import type { FC } from 'react'
import type { Theme } from '../theme/theme-context'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -9,7 +10,7 @@ import ViewFormDropdown from '@/app/components/base/chat/embedded-chatbot/inputs
import Divider from '@/app/components/base/divider'
import DifyLogo from '@/app/components/base/logo/dify-logo'
import Tooltip from '@/app/components/base/tooltip'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { isClient } from '@/utils/client'
import {
useEmbeddedChatbotContext,
@@ -44,7 +45,7 @@ const Header: FC<IHeaderProps> = ({
const [parentOrigin, setParentOrigin] = useState('')
const [showToggleExpandButton, setShowToggleExpandButton] = useState(false)
const [expanded, setExpanded] = useState(false)
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const handleMessageReceived = useCallback((event: MessageEvent) => {
let currentParentOrigin = parentOrigin
diff --git a/web/app/components/base/chat/embedded-chatbot/index.tsx b/web/app/components/base/chat/embedded-chatbot/index.tsx
index 7c0f2feb7ae..886549ca96f 100644
--- a/web/app/components/base/chat/embedded-chatbot/index.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/index.tsx
@@ -1,6 +1,7 @@
'use client'
import type { AppData } from '@/models/share'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import {
useEffect,
} from 'react'
@@ -10,10 +11,10 @@ import Header from '@/app/components/base/chat/embedded-chatbot/header'
import Loading from '@/app/components/base/loading'
import DifyLogo from '@/app/components/base/logo/dify-logo'
import LogoHeader from '@/app/components/base/logo/logo-embedded-chat-header'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import useDocumentTitle from '@/hooks/use-document-title'
import { AppSourceType } from '@/service/share'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import {
EmbeddedChatbotContext,
useEmbeddedChatbotContext,
@@ -34,7 +35,7 @@ const Chatbot = () => {
themeBuilder,
} = useEmbeddedChatbotContext()
const { t } = useTranslation()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const customConfig = appData?.custom_config
const site = appData?.site
diff --git a/web/app/components/custom/custom-page/__tests__/index.spec.tsx b/web/app/components/custom/custom-page/__tests__/index.spec.tsx
index d6cc15ed2b6..1f3655a9f81 100644
--- a/web/app/components/custom/custom-page/__tests__/index.spec.tsx
+++ b/web/app/components/custom/custom-page/__tests__/index.spec.tsx
@@ -1,9 +1,10 @@
+import type { ReactElement } from 'react'
import type { AppContextValue } from '@/context/app-context'
-import type { SystemFeatures } from '@/types/feature'
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createMockProviderContextValue } from '@/__mocks__/provider-context'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { contactSalesUrl, defaultPlan } from '@/app/components/billing/config'
import { Plan } from '@/app/components/billing/type'
import {
@@ -12,12 +13,19 @@ import {
useAppContext,
userProfilePlaceholder,
} from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useModalContext } from '@/context/modal-context'
import { useProviderContext } from '@/context/provider-context'
-import { defaultSystemFeatures } from '@/types/feature'
import CustomPage from '../index'
+const render = (ui: ReactElement) => renderWithSystemFeatures(ui, {
+ systemFeatures: {
+ branding: {
+ enabled: true,
+ workspace_logo: 'https://example.com/workspace-logo.png',
+ },
+ },
+})
+
const { mockToast } = vi.hoisted(() => {
const mockToast = Object.assign(vi.fn(), {
success: vi.fn(),
@@ -44,9 +52,6 @@ vi.mock('@/context/app-context', async (importOriginal) => {
useAppContext: vi.fn(),
}
})
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
vi.mock('@langgenius/dify-ui/toast', () => ({
toast: mockToast,
}))
@@ -54,7 +59,6 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
const mockUseProviderContext = vi.mocked(useProviderContext)
const mockUseModalContext = vi.mocked(useModalContext)
const mockUseAppContext = vi.mocked(useAppContext)
-const mockUseGlobalPublicStore = vi.mocked(useGlobalPublicStore)
const createProviderContext = ({
enableBilling = false,
@@ -93,15 +97,6 @@ const createAppContextValue = (): AppContextValue => ({
isValidatingCurrentWorkspace: false,
})
-const createSystemFeatures = (): SystemFeatures => ({
- ...defaultSystemFeatures,
- branding: {
- ...defaultSystemFeatures.branding,
- enabled: true,
- workspace_logo: 'https://example.com/workspace-logo.png',
- },
-})
-
describe('CustomPage', () => {
const setShowPricingModal = vi.fn()
@@ -113,10 +108,6 @@ describe('CustomPage', () => {
setShowPricingModal,
} as unknown as ReturnType<typeof useModalContext>)
mockUseAppContext.mockReturnValue(createAppContextValue())
- mockUseGlobalPublicStore.mockImplementation(selector => selector({
- systemFeatures: createSystemFeatures(),
- setSystemFeatures: vi.fn(),
- }))
})
// Integration coverage for the page and its child custom brand section.
diff --git a/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx b/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx
index 3ca7c34b846..99cbc03b329 100644
--- a/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx
+++ b/web/app/components/custom/custom-web-app-brand/hooks/__tests__/use-web-app-brand.spec.tsx
@@ -1,9 +1,10 @@
import type { ChangeEvent } from 'react'
import type { AppContextValue } from '@/context/app-context'
import type { SystemFeatures } from '@/types/feature'
-import { act, renderHook } from '@testing-library/react'
+import { act } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createMockProviderContextValue } from '@/__mocks__/provider-context'
+import { renderHookWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { getImageUploadErrorMessage, imageUpload } from '@/app/components/base/image-uploader/utils'
import { defaultPlan } from '@/app/components/billing/config'
import { Plan } from '@/app/components/billing/type'
@@ -13,12 +14,22 @@ import {
useAppContext,
userProfilePlaceholder,
} from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useProviderContext } from '@/context/provider-context'
import { updateCurrentWorkspace } from '@/service/common'
-import { defaultSystemFeatures } from '@/types/feature'
import useWebAppBrand from '../use-web-app-brand'
+let currentBrandingOverrides: Partial<SystemFeatures['branding']> = {}
+const renderHook = <Result, Props = void>(callback: (props: Props) => Result) =>
+ renderHookWithSystemFeatures(callback, {
+ systemFeatures: {
+ branding: {
+ enabled: true,
+ workspace_logo: 'https://example.com/workspace-logo.png',
+ ...currentBrandingOverrides,
+ },
+ },
+ })
+
const { mockNotify, mockToast } = vi.hoisted(() => {
const mockNotify = vi.fn()
const mockToast = Object.assign(mockNotify, {
@@ -49,9 +60,6 @@ vi.mock('@/context/app-context', async (importOriginal) => {
vi.mock('@/context/provider-context', () => ({
useProviderContext: vi.fn(),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
vi.mock('@/app/components/base/image-uploader/utils', () => ({
imageUpload: vi.fn(),
getImageUploadErrorMessage: vi.fn(),
@@ -60,7 +68,6 @@ vi.mock('@/app/components/base/image-uploader/utils', () => ({
const mockUpdateCurrentWorkspace = vi.mocked(updateCurrentWorkspace)
const mockUseAppContext = vi.mocked(useAppContext)
const mockUseProviderContext = vi.mocked(useProviderContext)
-const mockUseGlobalPublicStore = vi.mocked(useGlobalPublicStore)
const mockImageUpload = vi.mocked(imageUpload)
const mockGetImageUploadErrorMessage = vi.mocked(getImageUploadErrorMessage)
@@ -80,16 +87,6 @@ const createProviderContext = ({
})
}
-const createSystemFeatures = (brandingOverrides: Partial<SystemFeatures['branding']> = {}): SystemFeatures => ({
- ...defaultSystemFeatures,
- branding: {
- ...defaultSystemFeatures.branding,
- enabled: true,
- workspace_logo: 'https://example.com/workspace-logo.png',
- ...brandingOverrides,
- },
-})
-
const createAppContextValue = (overrides: Partial<AppContextValue> = {}): AppContextValue => {
const { currentWorkspace: currentWorkspaceOverride, ...restOverrides } = overrides
const workspaceOverrides: Partial<AppContextValue['currentWorkspace']> = currentWorkspaceOverride ?? {}
@@ -122,21 +119,16 @@ const createAppContextValue = (overrides: Partial<AppContextValue> = {}): AppCon
describe('useWebAppBrand', () => {
let appContextValue: AppContextValue
- let systemFeatures: SystemFeatures
beforeEach(() => {
vi.clearAllMocks()
appContextValue = createAppContextValue()
- systemFeatures = createSystemFeatures()
+ currentBrandingOverrides = {}
mockUpdateCurrentWorkspace.mockResolvedValue(appContextValue.currentWorkspace)
mockUseAppContext.mockImplementation(() => appContextValue)
mockUseProviderContext.mockReturnValue(createProviderContext())
- mockUseGlobalPublicStore.mockImplementation(selector => selector({
- systemFeatures,
- setSystemFeatures: vi.fn(),
- }))
mockGetImageUploadErrorMessage.mockReturnValue('upload error')
})
@@ -174,10 +166,7 @@ describe('useWebAppBrand', () => {
})
it('should fall back to an empty workspace logo when branding is disabled', () => {
- systemFeatures = createSystemFeatures({
- enabled: false,
- workspace_logo: '',
- })
+ currentBrandingOverrides = { enabled: false, workspace_logo: '' }
const { result } = renderHook(() => useWebAppBrand())
diff --git a/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts b/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts
index 145e7ee806c..e24edab4212 100644
--- a/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts
+++ b/web/app/components/custom/custom-web-app-brand/hooks/use-web-app-brand.ts
@@ -1,13 +1,14 @@
import type { ChangeEvent } from 'react'
import { toast } from '@langgenius/dify-ui/toast'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { getImageUploadErrorMessage, imageUpload } from '@/app/components/base/image-uploader/utils'
import { Plan } from '@/app/components/billing/type'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useProviderContext } from '@/context/provider-context'
import { updateCurrentWorkspace } from '@/service/common'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
const MAX_LOGO_FILE_SIZE = 5 * 1024 * 1024
const CUSTOM_CONFIG_URL = '/workspaces/custom-config'
@@ -19,7 +20,7 @@ const useWebAppBrand = () => {
const [fileId, setFileId] = useState('')
const [imgKey, setImgKey] = useState(() => Date.now())
const [uploadProgress, setUploadProgress] = useState(0)
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const isSandbox = enableBilling && plan.type === Plan.sandbox
const uploading = uploadProgress > 0 && uploadProgress < 100
const webappLogo = currentWorkspace.custom_config?.replace_webapp_logo || ''
diff --git a/web/app/components/datasets/create-from-pipeline/list/__tests__/built-in-pipeline-list.spec.tsx b/web/app/components/datasets/create-from-pipeline/list/__tests__/built-in-pipeline-list.spec.tsx
index f40c87b7acd..a34952cde33 100644
--- a/web/app/components/datasets/create-from-pipeline/list/__tests__/built-in-pipeline-list.spec.tsx
+++ b/web/app/components/datasets/create-from-pipeline/list/__tests__/built-in-pipeline-list.spec.tsx
@@ -1,8 +1,14 @@
-import { render, screen } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import BuiltInPipelineList from '../built-in-pipeline-list'
+const render = (ui: ReactElement) => renderWithSystemFeatures(ui, {
+ systemFeatures: { enable_marketplace: true },
+})
+
vi.mock('../create-card', () => ({
default: () => <div data-testid="create-card">CreateCard</div>,
}))
@@ -22,13 +28,6 @@ vi.mock('@/context/i18n', () => ({
useLocale: () => mockLocale,
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn((selector) => {
- const state = { systemFeatures: { enable_marketplace: true } }
- return selector(state)
- }),
-}))
-
const mockUsePipelineTemplateList = vi.fn()
vi.mock('@/service/use-pipeline', () => ({
usePipelineTemplateList: (...args: unknown[]) => mockUsePipelineTemplateList(...args),
diff --git a/web/app/components/datasets/create-from-pipeline/list/built-in-pipeline-list.tsx b/web/app/components/datasets/create-from-pipeline/list/built-in-pipeline-list.tsx
index 31c62758c16..3d14dd2f951 100644
--- a/web/app/components/datasets/create-from-pipeline/list/built-in-pipeline-list.tsx
+++ b/web/app/components/datasets/create-from-pipeline/list/built-in-pipeline-list.tsx
@@ -1,7 +1,8 @@
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useMemo } from 'react'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useLocale } from '@/context/i18n'
import { LanguagesSupported } from '@/i18n-config/language'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { usePipelineTemplateList } from '@/service/use-pipeline'
import CreateCard from './create-card'
import TemplateCard from './template-card'
@@ -13,7 +14,10 @@ const BuiltInPipelineList = () => {
return locale
return LanguagesSupported[0]
}, [locale])
- const enableMarketplace = useGlobalPublicStore(s => s.systemFeatures.enable_marketplace)
+ const { data: enableMarketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const { data: pipelineList, isLoading } = usePipelineTemplateList({ type: 'built-in', language }, enableMarketplace)
const list = pipelineList?.pipeline_templates || []
diff --git a/web/app/components/datasets/list/__tests__/index.spec.tsx b/web/app/components/datasets/list/__tests__/index.spec.tsx
index 37a787ff510..beee35b06de 100644
--- a/web/app/components/datasets/list/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/list/__tests__/index.spec.tsx
@@ -1,7 +1,14 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import List from '../index'
+let mockBrandingEnabled = false
+const render = (ui: ReactElement) => renderWithSystemFeatures(ui, {
+ systemFeatures: { branding: { enabled: mockBrandingEnabled } },
+})
+
const mockPush = vi.fn()
const mockReplace = vi.fn()
vi.mock('@/next/navigation', () => ({
@@ -20,15 +27,6 @@ vi.mock('@/context/app-context', () => ({
useSelector: () => true,
}))
-// Mock global public context
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: () => ({
- systemFeatures: {
- branding: { enabled: false },
- },
- }),
-}))
-
// Mock external api panel context
const mockSetShowExternalApiPanel = vi.fn()
vi.mock('@/context/external-api-panel-context', () => ({
@@ -133,6 +131,7 @@ vi.mock('@/app/components/datasets/create/website/base/checkbox-with-label', ()
describe('List', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockBrandingEnabled = false
})
describe('Rendering', () => {
@@ -319,18 +318,9 @@ describe('List', () => {
})
it('should not show DatasetFooter when branding is enabled', async () => {
- vi.doMock('@/context/global-public-context', () => ({
- useGlobalPublicStore: () => ({
- systemFeatures: {
- branding: { enabled: true },
- },
- }),
- }))
-
- vi.resetModules()
- const { default: ListComponent } = await import('../index')
+ mockBrandingEnabled = true
- render(<ListComponent />)
+ render(<List />)
expect(screen.queryByTestId('dataset-footer')).not.toBeInTheDocument()
})
diff --git a/web/app/components/datasets/list/index.tsx b/web/app/components/datasets/list/index.tsx
index 34be78ab3ff..1f7eba63c6a 100644
--- a/web/app/components/datasets/list/index.tsx
+++ b/web/app/components/datasets/list/index.tsx
@@ -1,10 +1,11 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useBoolean, useDebounceFn } from 'ahooks'
+
// Libraries
import { useState } from 'react'
-
import { useTranslation } from 'react-i18next'
import Input from '@/app/components/base/input'
import TagManagementModal from '@/app/components/base/tag-management'
@@ -14,9 +15,9 @@ import { useStore as useTagStore } from '@/app/components/base/tag-management/st
import CheckboxWithLabel from '@/app/components/datasets/create/website/base/checkbox-with-label'
import { useAppContext, useSelector as useAppContextSelector } from '@/context/app-context'
import { useExternalApiPanel } from '@/context/external-api-panel-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import useDocumentTitle from '@/hooks/use-document-title'
import { useDatasetApiBaseUrl } from '@/service/knowledge/use-dataset'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
// Components
import ExternalAPIPanel from '../external-api/external-api-panel'
import ServiceApi from '../extra-info/service-api'
@@ -25,7 +26,7 @@ import Datasets from './datasets'
const List = () => {
const { t } = useTranslation()
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { isCurrentWorkspaceOwner } = useAppContext()
const showTagManagementModal = useTagStore(s => s.showTagManagementModal)
const { showExternalApiPanel, setShowExternalApiPanel } = useExternalApiPanel()
diff --git a/web/app/components/devtools/react-scan/loader.tsx b/web/app/components/devtools/react-scan/loader.tsx
index bd310f292fe..8e933c2b24d 100644
--- a/web/app/components/devtools/react-scan/loader.tsx
+++ b/web/app/components/devtools/react-scan/loader.tsx
@@ -9,7 +9,7 @@ export function ReactScanLoader() {
<Script
src="//unpkg.com/react-scan/dist/auto.global.js"
crossOrigin="anonymous"
- strategy="afterInteractive"
+ strategy="beforeInteractive"
/>
)
}
diff --git a/web/app/components/explore/app-card/__tests__/index.spec.tsx b/web/app/components/explore/app-card/__tests__/index.spec.tsx
index c42f6f1d322..43b8e4fde2f 100644
--- a/web/app/components/explore/app-card/__tests__/index.spec.tsx
+++ b/web/app/components/explore/app-card/__tests__/index.spec.tsx
@@ -1,7 +1,8 @@
import type { AppCardProps } from '../index'
import type { App } from '@/models/explore'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { fireEvent, screen } from '@testing-library/react'
import * as React from 'react'
+import { renderWithSystemFeatures as render } from '@/__tests__/utils/mock-system-features'
import { trackEvent } from '@/app/components/base/amplitude'
import { AppModeEnum } from '@/types/app'
import AppCard from '../index'
diff --git a/web/app/components/explore/app-card/index.tsx b/web/app/components/explore/app-card/index.tsx
index 869e2a6a181..afa46f6ed40 100644
--- a/web/app/components/explore/app-card/index.tsx
+++ b/web/app/components/explore/app-card/index.tsx
@@ -5,10 +5,11 @@ import { PlusIcon } from '@heroicons/react/20/solid'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { RiInformation2Line } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { trackEvent } from '@/app/components/base/amplitude'
import AppIcon from '@/app/components/base/app-icon'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { AppModeEnum } from '@/types/app'
import { AppTypeIcon } from '../../app/type-selector'
@@ -29,7 +30,7 @@ const AppCard = ({
}: AppCardProps) => {
const { t } = useTranslation()
const { app: appBasicInfo } = app
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const isTrialApp = app.can_trial && systemFeatures.enable_trial_app
const handleTryApp = () => {
trackEvent('preview_template', {
diff --git a/web/app/components/explore/app-list/__tests__/index.spec.tsx b/web/app/components/explore/app-list/__tests__/index.spec.tsx
index 67312f5ec3b..4da92dd5681 100644
--- a/web/app/components/explore/app-list/__tests__/index.spec.tsx
+++ b/web/app/components/explore/app-list/__tests__/index.spec.tsx
@@ -1,9 +1,10 @@
+import type { ReactNode } from 'react'
import type { Mock } from 'vitest'
import type { CreateAppModalProps } from '@/app/components/explore/create-app-modal'
import type { App } from '@/models/explore'
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
+import { createSystemFeaturesWrapper } from '@/__tests__/utils/mock-system-features'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { fetchAppDetail } from '@/service/explore'
import { useMembers } from '@/service/use-common'
import { renderWithNuqs } from '@/test/nuqs-testing'
@@ -134,12 +135,28 @@ const mockMemberRole = (hasEditPermission: boolean) => {
})
}
-const renderAppList = (hasEditPermission = false, onSuccess?: () => void, searchParams?: Record<string, string>) => {
+type RenderOptions = {
+ enableExploreBanner?: boolean
+}
+
+const renderAppList = (
+ hasEditPermission = false,
+ onSuccess?: () => void,
+ searchParams?: Record<string, string>,
+ options: RenderOptions = {},
+) => {
mockMemberRole(hasEditPermission)
- return renderWithNuqs(
- <AppList onSuccess={onSuccess} />,
+ const { wrapper: SystemFeaturesWrapper, queryClient } = createSystemFeaturesWrapper({
+ systemFeatures: { enable_explore_banner: options.enableExploreBanner ?? false },
+ })
+ const Wrapped = ({ children }: { children: ReactNode }) => (
+ <SystemFeaturesWrapper>{children}</SystemFeaturesWrapper>
+ )
+ const rendered = renderWithNuqs(
+ <Wrapped><AppList onSuccess={onSuccess} /></Wrapped>,
{ searchParams },
)
+ return { ...rendered, queryClient }
}
describe('AppList', () => {
@@ -435,18 +452,12 @@ describe('AppList', () => {
describe('Banner', () => {
it('should render banner when enable_explore_banner is true', () => {
- useGlobalPublicStore.setState({
- systemFeatures: {
- ...useGlobalPublicStore.getState().systemFeatures,
- enable_explore_banner: true,
- },
- })
mockExploreData = {
categories: ['Writing'],
allList: [createApp()],
}
- renderAppList()
+ renderAppList(false, undefined, undefined, { enableExploreBanner: true })
expect(screen.getByTestId('explore-banner')).toBeInTheDocument()
})
diff --git a/web/app/components/explore/app-list/index.tsx b/web/app/components/explore/app-list/index.tsx
index d57283b9997..0cb0e30d2ed 100644
--- a/web/app/components/explore/app-list/index.tsx
+++ b/web/app/components/explore/app-list/index.tsx
@@ -5,6 +5,7 @@ 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 { useSuspenseQuery } from '@tanstack/react-query'
import { useDebounceFn } from 'ahooks'
import { useQueryState } from 'nuqs'
import * as React from 'react'
@@ -18,12 +19,12 @@ import Banner from '@/app/components/explore/banner/banner'
import Category from '@/app/components/explore/category'
import CreateAppModal from '@/app/components/explore/create-app-modal'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useImportDSL } from '@/hooks/use-import-dsl'
import {
DSLImportMode,
} from '@/models/app'
import { fetchAppDetail } from '@/service/explore'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useMembers } from '@/service/use-common'
import { useExploreAppList } from '@/service/use-explore'
import { trackCreateApp } from '@/utils/create-app-tracking'
@@ -39,7 +40,7 @@ const Apps = ({
}: AppsProps) => {
const { t } = useTranslation()
const { userProfile } = useAppContext()
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { data: membersData } = useMembers()
const allCategoriesEn = t('apps.allCategories', { ns: 'explore', lng: 'en' })
const userAccount = membersData?.accounts?.find(account => account.id === userProfile.id)
diff --git a/web/app/components/explore/try-app/__tests__/index.spec.tsx b/web/app/components/explore/try-app/__tests__/index.spec.tsx
index be6c6ea8e2a..a84989dea93 100644
--- a/web/app/components/explore/try-app/__tests__/index.spec.tsx
+++ b/web/app/components/explore/try-app/__tests__/index.spec.tsx
@@ -1,6 +1,7 @@
import type { TryAppInfo } from '@/service/try-app'
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures as render } from '@/__tests__/utils/mock-system-features'
import TryApp from '../index'
import { TypeEnum } from '../tab'
diff --git a/web/app/components/explore/try-app/index.tsx b/web/app/components/explore/try-app/index.tsx
index 209bde9cb6f..8bb27d90867 100644
--- a/web/app/components/explore/try-app/index.tsx
+++ b/web/app/components/explore/try-app/index.tsx
@@ -3,13 +3,14 @@
import type { FC } from 'react'
import type { App as AppType } from '@/models/explore'
import { Button } from '@langgenius/dify-ui/button'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useState } from 'react'
import AppUnavailable from '@/app/components/base/app-unavailable'
import Loading from '@/app/components/base/loading'
import Modal from '@/app/components/base/modal/index'
import { IS_CLOUD_EDITION } from '@/config'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useGetTryAppInfo } from '@/service/use-try-app'
import App from './app'
import AppInfo from './app-info'
@@ -31,7 +32,7 @@ const TryApp: FC<Props> = ({
onClose,
onCreate,
}) => {
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const isTrialApp = !!(app && app.can_trial && systemFeatures.enable_trial_app)
const canUseTryTab = IS_CLOUD_EDITION && (app ? isTrialApp : true)
const [type, setType] = useState<TypeEnum>(() => (canUseTryTab ? TypeEnum.TRY : TypeEnum.DETAIL))
diff --git a/web/app/components/header/__tests__/index.spec.tsx b/web/app/components/header/__tests__/index.spec.tsx
index 16e0854339b..ba284829f39 100644
--- a/web/app/components/header/__tests__/index.spec.tsx
+++ b/web/app/components/header/__tests__/index.spec.tsx
@@ -1,5 +1,7 @@
-import { fireEvent, render, screen } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { fireEvent, screen } from '@testing-library/react'
import { vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import Header from '../index'
function createMockComponent(testId: string) {
@@ -93,21 +95,16 @@ vi.mock('@/context/modal-context', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => {
- type SystemFeatures = { branding: { enabled: boolean, application_title: string | null, workspace_logo: string | null } }
- return {
- useGlobalPublicStore: (selector: (s: { systemFeatures: SystemFeatures }) => SystemFeatures) =>
- selector({
- systemFeatures: {
- branding: {
- enabled: mockBrandingEnabled,
- application_title: mockBrandingTitle,
- workspace_logo: mockBrandingLogo,
- },
- },
- }),
- }
-})
+const renderHeader = (ui: ReactElement = <Header />) =>
+ renderWithSystemFeatures(ui, {
+ systemFeatures: {
+ branding: {
+ enabled: mockBrandingEnabled,
+ application_title: mockBrandingTitle ?? '',
+ workspace_logo: mockBrandingLogo ?? '',
+ },
+ },
+ })
describe('Header', () => {
beforeEach(() => {
@@ -123,7 +120,7 @@ describe('Header', () => {
})
it('should render header with main nav components', () => {
- render(<Header />)
+ renderHeader()
expect(screen.getByRole('img', { name: /dify logo/i })).toBeInTheDocument()
expect(screen.getByTestId('workplace-selector')).toBeInTheDocument()
@@ -133,7 +130,7 @@ describe('Header', () => {
it('should show license nav when billing disabled, plan badge when enabled', () => {
mockEnableBilling = false
- const { rerender } = render(<Header />)
+ const { rerender } = renderHeader()
expect(screen.getByTestId('license-nav')).toBeInTheDocument()
expect(screen.queryByTestId('plan-badge')).not.toBeInTheDocument()
@@ -145,7 +142,7 @@ describe('Header', () => {
it('should hide explore nav when user is dataset operator', () => {
mockIsDatasetOperator = true
- render(<Header />)
+ renderHeader()
expect(screen.queryByTestId('explore-nav')).not.toBeInTheDocument()
expect(screen.getByTestId('dataset-nav')).toBeInTheDocument()
@@ -154,7 +151,7 @@ describe('Header', () => {
it('should call pricing modal for free plan, settings modal for paid plan', () => {
mockEnableBilling = true
mockPlanType = 'sandbox'
- const { rerender } = render(<Header />)
+ const { rerender } = renderHeader()
fireEvent.click(screen.getByTestId('plan-badge'))
expect(mockSetShowPricingModal).toHaveBeenCalledTimes(1)
@@ -167,7 +164,7 @@ describe('Header', () => {
it('should render mobile layout without env nav', () => {
mockMedia = 'mobile'
- render(<Header />)
+ renderHeader()
expect(screen.getByRole('img', { name: /dify logo/i })).toBeInTheDocument()
expect(screen.queryByTestId('env-nav')).not.toBeInTheDocument()
@@ -178,7 +175,7 @@ describe('Header', () => {
mockBrandingTitle = 'Acme Workspace'
mockBrandingLogo = '/logo.png'
- render(<Header />)
+ renderHeader()
expect(screen.getByText('Acme Workspace')).toBeInTheDocument()
expect(screen.getByRole('img', { name: /logo/i })).toBeInTheDocument()
@@ -190,7 +187,7 @@ describe('Header', () => {
mockBrandingTitle = 'Custom Title'
mockBrandingLogo = null
- render(<Header />)
+ renderHeader()
expect(screen.getByText('Custom Title')).toBeInTheDocument()
expect(screen.getByRole('img', { name: /dify logo/i })).toBeInTheDocument()
@@ -201,7 +198,7 @@ describe('Header', () => {
mockBrandingTitle = null
mockBrandingLogo = null
- render(<Header />)
+ renderHeader()
expect(screen.getByText('Dify')).toBeInTheDocument()
})
@@ -210,7 +207,7 @@ describe('Header', () => {
mockIsWorkspaceEditor = true
mockIsDatasetOperator = false
- render(<Header />)
+ renderHeader()
expect(screen.getByTestId('dataset-nav')).toBeInTheDocument()
expect(screen.getByTestId('explore-nav')).toBeInTheDocument()
@@ -221,7 +218,7 @@ describe('Header', () => {
mockIsWorkspaceEditor = false
mockIsDatasetOperator = false
- render(<Header />)
+ renderHeader()
expect(screen.queryByTestId('dataset-nav')).not.toBeInTheDocument()
})
@@ -230,7 +227,7 @@ describe('Header', () => {
mockMedia = 'mobile'
mockIsDatasetOperator = true
- render(<Header />)
+ renderHeader()
expect(screen.queryByTestId('explore-nav')).not.toBeInTheDocument()
expect(screen.queryByTestId('app-nav')).not.toBeInTheDocument()
@@ -243,7 +240,7 @@ describe('Header', () => {
mockEnableBilling = true
mockPlanType = 'sandbox'
- render(<Header />)
+ renderHeader()
expect(screen.getByTestId('plan-badge')).toBeInTheDocument()
expect(screen.queryByTestId('license-nav')).not.toBeInTheDocument()
diff --git a/web/app/components/header/account-about/__tests__/index.spec.tsx b/web/app/components/header/account-about/__tests__/index.spec.tsx
index f4be46389ed..694a6320399 100644
--- a/web/app/components/header/account-about/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-about/__tests__/index.spec.tsx
@@ -1,22 +1,16 @@
import type { LangGeniusVersionResponse } from '@/models/common'
-import type { SystemFeatures } from '@/types/feature'
-import { fireEvent, render, screen } from '@testing-library/react'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { fireEvent, screen } from '@testing-library/react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import AccountAbout from '../index'
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
let mockIsCEEdition = false
-vi.mock('@/config', () => ({
- get IS_CE_EDITION() { return mockIsCEEdition },
-}))
-
-type GlobalPublicStore = {
- systemFeatures: SystemFeatures
- setSystemFeatures: (systemFeatures: SystemFeatures) => void
-}
+vi.mock('@/config', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/config')>()
+ return {
+ ...actual,
+ get IS_CE_EDITION() { return mockIsCEEdition },
+ }
+})
describe('AccountAbout', () => {
const mockVersionInfo: LangGeniusVersionResponse = {
@@ -34,31 +28,23 @@ describe('AccountAbout', () => {
beforeEach(() => {
vi.clearAllMocks()
mockIsCEEdition = false
- vi.mocked(useGlobalPublicStore).mockImplementation(selector => selector({
- systemFeatures: { branding: { enabled: false } },
- } as unknown as GlobalPublicStore))
})
describe('Rendering', () => {
it('should render correctly with version information', () => {
- // Act
- render(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />)
+ renderWithSystemFeatures(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />, {
+ systemFeatures: { branding: { enabled: false } },
+ })
- // Assert
expect(screen.getByText(/^Version/)).toBeInTheDocument()
expect(screen.getAllByText(/0.6.0/).length).toBeGreaterThan(0)
})
it('should render branding logo if enabled', () => {
- // Arrange
- vi.mocked(useGlobalPublicStore).mockImplementation(selector => selector({
+ renderWithSystemFeatures(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />, {
systemFeatures: { branding: { enabled: true, workspace_logo: 'custom-logo.png' } },
- } as unknown as GlobalPublicStore))
-
- // Act
- render(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />)
+ })
- // Assert
const img = screen.getByAltText('logo')
expect(img).toBeInTheDocument()
expect(img).toHaveAttribute('src', 'custom-logo.png')
@@ -67,21 +53,16 @@ describe('AccountAbout', () => {
describe('Version Logic', () => {
it('should show "Latest Available" when current version equals latest', () => {
- // Act
- render(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />)
+ renderWithSystemFeatures(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />)
- // Assert
expect(screen.getByText(/about.latestAvailable/)).toBeInTheDocument()
})
it('should show "Now Available" when current version is behind', () => {
- // Arrange
const behindVersionInfo = { ...mockVersionInfo, latest_version: '0.7.0' }
- // Act
- render(<AccountAbout langGeniusVersionInfo={behindVersionInfo} onCancel={mockOnCancel} />)
+ renderWithSystemFeatures(<AccountAbout langGeniusVersionInfo={behindVersionInfo} onCancel={mockOnCancel} />)
- // Assert
expect(screen.getByText(/about.nowAvailable/)).toBeInTheDocument()
expect(screen.getByText(/about.updateNow/)).toBeInTheDocument()
})
@@ -89,33 +70,26 @@ describe('AccountAbout', () => {
describe('Community Edition', () => {
it('should render correctly in Community Edition', () => {
- // Arrange
mockIsCEEdition = true
- // Act
- render(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />)
+ renderWithSystemFeatures(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />)
- // Assert
expect(screen.getByText(/Open Source License/)).toBeInTheDocument()
})
it('should hide update button in Community Edition when behind version', () => {
- // Arrange
mockIsCEEdition = true
const behindVersionInfo = { ...mockVersionInfo, latest_version: '0.7.0' }
- // Act
- render(<AccountAbout langGeniusVersionInfo={behindVersionInfo} onCancel={mockOnCancel} />)
+ renderWithSystemFeatures(<AccountAbout langGeniusVersionInfo={behindVersionInfo} onCancel={mockOnCancel} />)
- // Assert
expect(screen.queryByText(/about.updateNow/)).not.toBeInTheDocument()
})
})
describe('User Interactions', () => {
it('should call onCancel when close button is clicked', () => {
- // Act
- render(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />)
+ renderWithSystemFeatures(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />)
// Modal uses Headless UI Dialog which renders into a portal, so we need to use document
const closeButton = document.querySelector('div.absolute.cursor-pointer')
diff --git a/web/app/components/header/account-about/index.tsx b/web/app/components/header/account-about/index.tsx
index 93754975667..e2535144f93 100644
--- a/web/app/components/header/account-about/index.tsx
+++ b/web/app/components/header/account-about/index.tsx
@@ -2,15 +2,16 @@
import type { LangGeniusVersionResponse } from '@/models/common'
import { Button } from '@langgenius/dify-ui/button'
import { RiCloseLine } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import dayjs from 'dayjs'
import { useTranslation } from 'react-i18next'
import DifyLogo from '@/app/components/base/logo/dify-logo'
import Modal from '@/app/components/base/modal'
import { IS_CE_EDITION } from '@/config'
-import { useGlobalPublicStore } from '@/context/global-public-context'
-
import Link from '@/next/link'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
+
type IAccountSettingProps = {
langGeniusVersionInfo: LangGeniusVersionResponse
onCancel: () => void
@@ -22,7 +23,7 @@ export default function AccountAbout({
}: IAccountSettingProps) {
const { t } = useTranslation()
const isLatest = langGeniusVersionInfo.current_version === langGeniusVersionInfo.latest_version
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
return (
<Modal
diff --git a/web/app/components/header/account-dropdown/__tests__/index.spec.tsx b/web/app/components/header/account-dropdown/__tests__/index.spec.tsx
index 9d4226c33a4..f23cb2efd4e 100644
--- a/web/app/components/header/account-dropdown/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-dropdown/__tests__/index.spec.tsx
@@ -1,17 +1,23 @@
import type { AppContextValue } from '@/context/app-context'
import type { ModalContextState } from '@/context/modal-context'
import type { ProviderContextState } from '@/context/provider-context'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import type { SystemFeatures } from '@/types/feature'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { Plan } from '@/app/components/billing/type'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useModalContext } from '@/context/modal-context'
import { useProviderContext } from '@/context/provider-context'
import { useRouter } from '@/next/navigation'
import { useLogout } from '@/service/use-common'
import AppSelector from '../index'
+type DeepPartial<T> = T extends Array<infer U>
+ ? Array<U>
+ : T extends object
+ ? { [K in keyof T]?: DeepPartial<T[K]> }
+ : T
+
vi.mock('../../account-setting', () => ({
default: () => <div data-testid="account-setting">AccountSetting</div>,
}))
@@ -37,10 +43,6 @@ vi.mock('@/context/app-context', () => ({
useAppContext: vi.fn(),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
vi.mock('@/context/provider-context', () => ({
useProviderContext: vi.fn(),
}))
@@ -79,15 +81,19 @@ const { mockConfig, mockEnv } = vi.hoisted(() => ({
},
},
}))
-vi.mock('@/config', () => ({
- get IS_CLOUD_EDITION() { return mockConfig.IS_CLOUD_EDITION },
- get AMPLITUDE_API_KEY() { return mockConfig.AMPLITUDE_API_KEY },
- get isAmplitudeEnabled() { return mockConfig.IS_CLOUD_EDITION && !!mockConfig.AMPLITUDE_API_KEY },
- get ZENDESK_WIDGET_KEY() { return mockConfig.ZENDESK_WIDGET_KEY },
- get SUPPORT_EMAIL_ADDRESS() { return mockConfig.SUPPORT_EMAIL_ADDRESS },
- IS_DEV: false,
- IS_CE_EDITION: false,
-}))
+vi.mock('@/config', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/config')>()
+ return {
+ ...actual,
+ get IS_CLOUD_EDITION() { return mockConfig.IS_CLOUD_EDITION },
+ get AMPLITUDE_API_KEY() { return mockConfig.AMPLITUDE_API_KEY },
+ get isAmplitudeEnabled() { return mockConfig.IS_CLOUD_EDITION && !!mockConfig.AMPLITUDE_API_KEY },
+ get ZENDESK_WIDGET_KEY() { return mockConfig.ZENDESK_WIDGET_KEY },
+ get SUPPORT_EMAIL_ADDRESS() { return mockConfig.SUPPORT_EMAIL_ADDRESS },
+ IS_DEV: false,
+ IS_CE_EDITION: false,
+ }
+})
vi.mock('@/env', () => mockEnv)
const baseAppContextValue: AppContextValue = {
@@ -136,20 +142,13 @@ describe('AccountDropdown', () => {
const mockLogout = vi.fn()
const mockSetShowAccountSettingModal = vi.fn()
- const renderWithRouter = (ui: React.ReactElement) => {
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
+ const renderWithRouter = (
+ ui: React.ReactElement,
+ options: { systemFeatures?: DeepPartial<SystemFeatures> } = {},
+ ) => {
+ return renderWithSystemFeatures(ui, {
+ systemFeatures: options.systemFeatures ?? { branding: { enabled: false } },
})
-
- return render(
- <QueryClientProvider client={queryClient}>
- {ui}
- </QueryClientProvider>,
- )
}
beforeEach(() => {
@@ -159,10 +158,6 @@ describe('AccountDropdown', () => {
mockEnv.env.NEXT_PUBLIC_SITE_ABOUT = 'show'
vi.mocked(useAppContext).mockReturnValue(baseAppContextValue)
- vi.mocked(useGlobalPublicStore).mockImplementation((selector?: unknown) => {
- const fullState = { systemFeatures: { branding: { enabled: false } }, setSystemFeatures: vi.fn() }
- return typeof selector === 'function' ? (selector as (state: typeof fullState) => unknown)(fullState) : fullState
- })
vi.mocked(useProviderContext).mockReturnValue({
isEducationAccount: false,
plan: { type: Plan.sandbox },
@@ -316,14 +311,10 @@ describe('AccountDropdown', () => {
describe('Branding and Environment', () => {
it('should hide sections when branding is enabled', () => {
- // Arrange
- vi.mocked(useGlobalPublicStore).mockImplementation((selector?: unknown) => {
- const fullState = { systemFeatures: { branding: { enabled: true } }, setSystemFeatures: vi.fn() }
- return typeof selector === 'function' ? (selector as (state: typeof fullState) => unknown)(fullState) : fullState
- })
-
// Act
- renderWithRouter(<AppSelector />)
+ renderWithRouter(<AppSelector />, {
+ systemFeatures: { branding: { enabled: true } },
+ })
fireEvent.click(screen.getByRole('button'))
// Assert
diff --git a/web/app/components/header/account-dropdown/index.tsx b/web/app/components/header/account-dropdown/index.tsx
index 27a601a4ab2..b62eb424829 100644
--- a/web/app/components/header/account-dropdown/index.tsx
+++ b/web/app/components/header/account-dropdown/index.tsx
@@ -4,6 +4,7 @@ import type { MouseEventHandler, ReactNode } from 'react'
import { Avatar } from '@langgenius/dify-ui/avatar'
import { cn } from '@langgenius/dify-ui/cn'
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLinkItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@langgenius/dify-ui/dropdown-menu'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { resetUser } from '@/app/components/base/amplitude/utils'
@@ -12,13 +13,13 @@ import ThemeSwitcher from '@/app/components/base/theme-switcher'
import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'
import { IS_CLOUD_EDITION } from '@/config'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useDocLink } from '@/context/i18n'
import { useModalContext } from '@/context/modal-context'
import { useProviderContext } from '@/context/provider-context'
import { env } from '@/env'
import Link from '@/next/link'
import { useRouter } from '@/next/navigation'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useLogout } from '@/service/use-common'
import AccountAbout from '../account-about'
import GithubStar from '../github-star'
@@ -110,7 +111,7 @@ export default function AppSelector() {
const router = useRouter()
const [aboutVisible, setAboutVisible] = useState(false)
const [isAccountMenuOpen, setIsAccountMenuOpen] = useState(false)
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { t } = useTranslation()
const docLink = useDocLink()
diff --git a/web/app/components/header/account-setting/__tests__/index.spec.tsx b/web/app/components/header/account-setting/__tests__/index.spec.tsx
index d37b0bbcf25..4bf9d1c5153 100644
--- a/web/app/components/header/account-setting/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/__tests__/index.spec.tsx
@@ -1,8 +1,8 @@
import type { AccountSettingTab } from '../constants'
import type { AppContextValue } from '@/context/app-context'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { fireEvent, screen } from '@testing-library/react'
import { useState } from 'react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useAppContext } from '@/context/app-context'
import { baseProviderContextValue, useProviderContext } from '@/context/provider-context'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
@@ -47,36 +47,6 @@ vi.mock('@/hooks/use-breakpoints', () => ({
default: vi.fn(),
}))
-vi.mock('@/context/global-public-context', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@/context/global-public-context')>()
- const systemFeatures = {
- ...actual.useGlobalPublicStore.getState().systemFeatures,
- webapp_auth: {
- ...actual.useGlobalPublicStore.getState().systemFeatures.webapp_auth,
- enabled: true,
- },
- branding: {
- ...actual.useGlobalPublicStore.getState().systemFeatures.branding,
- enabled: false,
- },
- enable_marketplace: true,
- enable_collaboration_mode: false,
- }
-
- return {
- ...actual,
- useGlobalPublicStore: (selector: (state: Record<string, unknown>) => unknown) => selector({
- systemFeatures,
- }),
- useSystemFeaturesQuery: () => ({
- data: systemFeatures,
- isPending: false,
- isLoading: false,
- isFetching: false,
- }),
- }
-})
-
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
useDefaultModel: vi.fn(() => ({ data: null, isLoading: false })),
useUpdateDefaultModel: vi.fn(() => ({ trigger: vi.fn() })),
@@ -176,11 +146,14 @@ describe('AccountSetting', () => {
)
}
- return render(
- <QueryClientProvider client={new QueryClient()}>
- <StatefulAccountSetting />
- </QueryClientProvider>,
- )
+ return renderWithSystemFeatures(<StatefulAccountSetting />, {
+ systemFeatures: {
+ webapp_auth: { enabled: true },
+ branding: { enabled: false },
+ enable_marketplace: true,
+ enable_collaboration_mode: false,
+ },
+ })
}
beforeEach(() => {
diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx
index 9baea5c722b..b88c2343948 100644
--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx
@@ -1,12 +1,11 @@
import type { UseQueryResult } from '@tanstack/react-query'
import type { DataSourceAuth } from '../types'
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import { useTheme } from 'next-themes'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { usePluginAuthAction } from '@/app/components/plugins/plugin-auth'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import { useGetDataSourceListAuth, useGetDataSourceOAuthUrl } from '@/service/use-datasource'
-import { defaultSystemFeatures } from '@/types/feature'
import { useDataSourceAuthUpdate, useMarketplaceAllPlugins } from '../hooks'
import DataSourcePage from '../index'
@@ -24,10 +23,6 @@ vi.mock('@/hooks/use-i18n', () => ({
useRenderI18nObject: vi.fn(),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
vi.mock('@/service/use-datasource', () => ({
useGetDataSourceListAuth: vi.fn(),
useGetDataSourceOAuthUrl: vi.fn(),
@@ -96,18 +91,14 @@ describe('DataSourcePage Component', () => {
describe('Initial View Rendering', () => {
it('should render an empty view when no data is available and marketplace is disabled', () => {
// Arrange
- /* eslint-disable-next-line ts/no-explicit-any */
- vi.mocked(useGlobalPublicStore).mockImplementation((selector: any) =>
- selector({
- systemFeatures: { ...defaultSystemFeatures, enable_marketplace: false },
- }),
- )
vi.mocked(useGetDataSourceListAuth).mockReturnValue({
data: undefined,
} as unknown as UseQueryResult<{ result: DataSourceAuth[] }, Error>)
// Act
- render(<DataSourcePage />)
+ renderWithSystemFeatures(<DataSourcePage />, {
+ systemFeatures: { enable_marketplace: false },
+ })
// Assert
expect(screen.queryByText('Dify Source')).not.toBeInTheDocument()
@@ -118,18 +109,14 @@ describe('DataSourcePage Component', () => {
describe('Data Source List Rendering', () => {
it('should render Card components for each data source returned from the API', () => {
// Arrange
- /* eslint-disable-next-line ts/no-explicit-any */
- vi.mocked(useGlobalPublicStore).mockImplementation((selector: any) =>
- selector({
- systemFeatures: { ...defaultSystemFeatures, enable_marketplace: false },
- }),
- )
vi.mocked(useGetDataSourceListAuth).mockReturnValue({
data: { result: mockProviders },
} as unknown as UseQueryResult<{ result: DataSourceAuth[] }, Error>)
// Act
- render(<DataSourcePage />)
+ renderWithSystemFeatures(<DataSourcePage />, {
+ systemFeatures: { enable_marketplace: false },
+ })
// Assert
expect(screen.getByText('Dify Source')).toBeInTheDocument()
@@ -140,18 +127,14 @@ describe('DataSourcePage Component', () => {
describe('Marketplace Integration', () => {
it('should render the InstallFromMarketplace component when enable_marketplace feature is enabled', () => {
// Arrange
- /* eslint-disable-next-line ts/no-explicit-any */
- vi.mocked(useGlobalPublicStore).mockImplementation((selector: any) =>
- selector({
- systemFeatures: { ...defaultSystemFeatures, enable_marketplace: true },
- }),
- )
vi.mocked(useGetDataSourceListAuth).mockReturnValue({
data: { result: mockProviders },
} as unknown as UseQueryResult<{ result: DataSourceAuth[] }, Error>)
// Act
- render(<DataSourcePage />)
+ renderWithSystemFeatures(<DataSourcePage />, {
+ systemFeatures: { enable_marketplace: true },
+ })
// Assert
expect(screen.getByText('common.modelProvider.installDataSourceProvider')).toBeInTheDocument()
@@ -160,18 +143,14 @@ describe('DataSourcePage Component', () => {
it('should pass an empty array to InstallFromMarketplace if data result is missing but marketplace is enabled', () => {
// Arrange
- /* eslint-disable-next-line ts/no-explicit-any */
- vi.mocked(useGlobalPublicStore).mockImplementation((selector: any) =>
- selector({
- systemFeatures: { ...defaultSystemFeatures, enable_marketplace: true },
- }),
- )
vi.mocked(useGetDataSourceListAuth).mockReturnValue({
data: undefined,
} as unknown as UseQueryResult<{ result: DataSourceAuth[] }, Error>)
// Act
- render(<DataSourcePage />)
+ renderWithSystemFeatures(<DataSourcePage />, {
+ systemFeatures: { enable_marketplace: true },
+ })
// Assert
expect(screen.getByText('common.modelProvider.installDataSourceProvider')).toBeInTheDocument()
@@ -179,38 +158,30 @@ describe('DataSourcePage Component', () => {
it('should handle the case where data exists but result is an empty array', () => {
// Arrange
- /* eslint-disable-next-line ts/no-explicit-any */
- vi.mocked(useGlobalPublicStore).mockImplementation((selector: any) =>
- selector({
- systemFeatures: { ...defaultSystemFeatures, enable_marketplace: true },
- }),
- )
vi.mocked(useGetDataSourceListAuth).mockReturnValue({
data: { result: [] },
} as unknown as UseQueryResult<{ result: DataSourceAuth[] }, Error>)
// Act
- render(<DataSourcePage />)
+ renderWithSystemFeatures(<DataSourcePage />, {
+ systemFeatures: { enable_marketplace: true },
+ })
// Assert
expect(screen.queryByText('Dify Source')).not.toBeInTheDocument()
expect(screen.getByText('common.modelProvider.installDataSourceProvider')).toBeInTheDocument()
})
- it('should handle the case where systemFeatures is missing (edge case for coverage)', () => {
+ it('should handle the case where enable_marketplace is false (edge case for coverage)', () => {
// Arrange
- /* eslint-disable-next-line ts/no-explicit-any */
- vi.mocked(useGlobalPublicStore).mockImplementation((selector: any) =>
- selector({
- systemFeatures: {},
- }),
- )
vi.mocked(useGetDataSourceListAuth).mockReturnValue({
data: { result: [] },
} as unknown as UseQueryResult<{ result: DataSourceAuth[] }, Error>)
// Act
- render(<DataSourcePage />)
+ renderWithSystemFeatures(<DataSourcePage />, {
+ systemFeatures: { enable_marketplace: false },
+ })
// Assert
expect(screen.queryByText('common.modelProvider.installDataSourceProvider')).not.toBeInTheDocument()
diff --git a/web/app/components/header/account-setting/data-source-page-new/index.tsx b/web/app/components/header/account-setting/data-source-page-new/index.tsx
index e7884cc2dbb..a12adfacbdd 100644
--- a/web/app/components/header/account-setting/data-source-page-new/index.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/index.tsx
@@ -1,11 +1,15 @@
+import { useSuspenseQuery } from '@tanstack/react-query'
import { memo } from 'react'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useGetDataSourceListAuth } from '@/service/use-datasource'
import Card from './card'
import InstallFromMarketplace from './install-from-marketplace'
const DataSourcePage = () => {
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const { data } = useGetDataSourceListAuth()
return (
diff --git a/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx
index b50073b1f26..c09f32ea83a 100644
--- a/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/__tests__/index.spec.tsx
@@ -1,23 +1,26 @@
import type { AppContextValue } from '@/context/app-context'
import type { ICurrentWorkspace, Member } from '@/models/common'
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { vi } from 'vitest'
import { createMockProviderContextValue } from '@/__mocks__/provider-context'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { Plan } from '@/app/components/billing/type'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useProviderContext } from '@/context/provider-context'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import { useMembers } from '@/service/use-common'
import MembersPage from '../index'
vi.mock('@/context/app-context')
-vi.mock('@/context/global-public-context')
vi.mock('@/context/provider-context')
vi.mock('@/hooks/use-format-time-from-now')
vi.mock('@/service/use-common')
+const renderMembersPage = () => renderWithSystemFeatures(<MembersPage />, {
+ systemFeatures: { is_email_setup: true },
+})
+
vi.mock('../edit-workspace-modal', () => ({
default: ({ onCancel }: { onCancel: () => void }) => (
<div>
@@ -112,10 +115,6 @@ describe('MembersPage', () => {
refetch: mockRefetch,
} as unknown as ReturnType<typeof useMembers>)
- vi.mocked(useGlobalPublicStore).mockImplementation(selector => selector({
- systemFeatures: { is_email_setup: true },
- } as unknown as Parameters<typeof selector>[0]))
-
vi.mocked(useProviderContext).mockReturnValue(createMockProviderContextValue({
enableBilling: false,
isAllowTransferWorkspace: true,
@@ -127,7 +126,7 @@ describe('MembersPage', () => {
})
it('should render workspace and member information', () => {
- render(<MembersPage />)
+ renderMembersPage()
expect(screen.getByText('Test Workspace'))!.toBeInTheDocument()
expect(screen.getByText('Owner User'))!.toBeInTheDocument()
@@ -137,7 +136,7 @@ describe('MembersPage', () => {
it('should open and close invite modal', async () => {
const user = userEvent.setup()
- render(<MembersPage />)
+ renderMembersPage()
await user.click(screen.getByRole('button', { name: /invite/i }))
expect(screen.getByText('Invite Modal'))!.toBeInTheDocument()
@@ -149,7 +148,7 @@ describe('MembersPage', () => {
it('should open invited modal after invite results are sent', async () => {
const user = userEvent.setup()
- render(<MembersPage />)
+ renderMembersPage()
await user.click(screen.getByRole('button', { name: /invite/i }))
await user.click(screen.getByRole('button', { name: 'Send Invite Results' }))
@@ -164,7 +163,7 @@ describe('MembersPage', () => {
it('should open transfer ownership modal when transfer action is used', async () => {
const user = userEvent.setup()
- render(<MembersPage />)
+ renderMembersPage()
await user.click(screen.getByRole('button', { name: /transfer ownership/i }))
expect(screen.getByText('Transfer Ownership Modal'))!.toBeInTheDocument()
@@ -176,7 +175,7 @@ describe('MembersPage', () => {
isAllowTransferWorkspace: false,
}))
- render(<MembersPage />)
+ renderMembersPage()
expect(screen.getByText('common.members.owner'))!.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /transfer ownership/i })).not.toBeInTheDocument()
@@ -190,7 +189,7 @@ describe('MembersPage', () => {
isCurrentWorkspaceManager: false,
} as unknown as AppContextValue)
- render(<MembersPage />)
+ renderMembersPage()
expect(screen.queryByRole('button', { name: /invite/i })).not.toBeInTheDocument()
expect(screen.queryByText('Transfer ownership')).not.toBeInTheDocument()
@@ -199,7 +198,7 @@ describe('MembersPage', () => {
it('should open and close edit workspace modal', async () => {
const user = userEvent.setup()
- render(<MembersPage />)
+ renderMembersPage()
await user.click(screen.getByTestId('edit-workspace-pencil'))
expect(screen.getByText('Edit Workspace Modal'))!.toBeInTheDocument()
@@ -211,7 +210,7 @@ describe('MembersPage', () => {
it('should close transfer ownership modal when close is clicked', async () => {
const user = userEvent.setup()
- render(<MembersPage />)
+ renderMembersPage()
await user.click(screen.getByRole('button', { name: /transfer ownership/i }))
expect(screen.getByText('Transfer Ownership Modal'))!.toBeInTheDocument()
@@ -230,7 +229,7 @@ describe('MembersPage', () => {
refetch: mockRefetch,
} as unknown as ReturnType<typeof useMembers>)
- render(<MembersPage />)
+ renderMembersPage()
expect(screen.getByText(/members\.pending/i))!.toBeInTheDocument()
expect(screen.getByText(/members\.you/i))!.toBeInTheDocument() // Current user is [email protected]
@@ -245,7 +244,7 @@ describe('MembersPage', () => {
} as unknown as ReturnType<typeof useProviderContext>['plan'],
}))
- render(<MembersPage />)
+ renderMembersPage()
expect(screen.getByText(/plansCommon\.member/i))!.toBeInTheDocument()
expect(screen.getByText('2'))!.toBeInTheDocument() // accounts.length
@@ -262,7 +261,7 @@ describe('MembersPage', () => {
} as unknown as ReturnType<typeof useProviderContext>['plan'],
}))
- render(<MembersPage />)
+ renderMembersPage()
expect(screen.getByText(/plansCommon\.unlimited/i))!.toBeInTheDocument()
})
@@ -276,7 +275,7 @@ describe('MembersPage', () => {
} as unknown as ReturnType<typeof useProviderContext>['plan'],
}))
- render(<MembersPage />)
+ renderMembersPage()
// Plan.team is an unlimited member plan → isNotUnlimitedMemberPlan=false → non-billing layout
// Plan.team is an unlimited member plan → isNotUnlimitedMemberPlan=false → non-billing layout
@@ -291,7 +290,7 @@ describe('MembersPage', () => {
isCurrentWorkspaceManager: true,
} as unknown as AppContextValue)
- render(<MembersPage />)
+ renderMembersPage()
expect(screen.getByRole('button', { name: /invite/i }))!.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /transfer ownership/i })).not.toBeInTheDocument()
@@ -308,7 +307,7 @@ describe('MembersPage', () => {
refetch: mockRefetch,
} as unknown as ReturnType<typeof useMembers>)
- render(<MembersPage />)
+ renderMembersPage()
expect(mockFormatTimeFromNow).toHaveBeenCalledWith(1700000000000)
})
@@ -326,7 +325,7 @@ describe('MembersPage', () => {
} as unknown as ReturnType<typeof useProviderContext>['plan'],
}))
- render(<MembersPage />)
+ renderMembersPage()
expect(screen.getByText(/plansCommon\.member/i))!.toBeInTheDocument()
expect(screen.getByText('1'))!.toBeInTheDocument()
@@ -338,7 +337,7 @@ describe('MembersPage', () => {
refetch: mockRefetch,
} as unknown as ReturnType<typeof useMembers>)
- render(<MembersPage />)
+ renderMembersPage()
expect(screen.getByText(/plansCommon\.memberAfter/i))!.toBeInTheDocument()
expect(screen.getByText('1'))!.toBeInTheDocument()
@@ -356,7 +355,7 @@ describe('MembersPage', () => {
refetch: mockRefetch,
} as unknown as ReturnType<typeof useMembers>)
- render(<MembersPage />)
+ renderMembersPage()
expect(screen.getByText('common.members.normal'))!.toBeInTheDocument()
})
@@ -370,7 +369,7 @@ describe('MembersPage', () => {
} as unknown as ReturnType<typeof useProviderContext>['plan'],
}))
- render(<MembersPage />)
+ renderMembersPage()
expect(screen.getByText('Upgrade Button'))!.toBeInTheDocument()
})
diff --git a/web/app/components/header/account-setting/members-page/__tests__/invite-button.spec.tsx b/web/app/components/header/account-setting/members-page/__tests__/invite-button.spec.tsx
index c64e4652796..43fcce16f74 100644
--- a/web/app/components/header/account-setting/members-page/__tests__/invite-button.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/__tests__/invite-button.spec.tsx
@@ -1,35 +1,34 @@
import type { AppContextValue } from '@/context/app-context'
import type { ICurrentWorkspace } from '@/models/common'
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import { vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useWorkspacePermissions } from '@/service/use-workspace'
import InviteButton from '../invite-button'
vi.mock('@/context/app-context')
-vi.mock('@/context/global-public-context')
vi.mock('@/service/use-workspace')
describe('InviteButton', () => {
- const setupMocks = ({
- brandingEnabled,
+ const setupPermissions = ({
isFetching,
allowInvite,
}: {
- brandingEnabled: boolean
isFetching: boolean
allowInvite?: boolean
}) => {
- vi.mocked(useGlobalPublicStore).mockImplementation(selector => selector({
- systemFeatures: { branding: { enabled: brandingEnabled } },
- } as unknown as Parameters<typeof selector>[0]))
vi.mocked(useWorkspacePermissions).mockReturnValue({
data: allowInvite === undefined ? null : { allow_member_invite: allowInvite },
isFetching,
} as unknown as ReturnType<typeof useWorkspacePermissions>)
}
+ const renderInviteButton = (brandingEnabled: boolean) =>
+ renderWithSystemFeatures(<InviteButton />, {
+ systemFeatures: { branding: { enabled: brandingEnabled } },
+ })
+
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(useAppContext).mockReturnValue({
@@ -38,33 +37,33 @@ describe('InviteButton', () => {
})
it('should show invite button when branding is disabled', () => {
- setupMocks({ brandingEnabled: false, isFetching: false })
+ setupPermissions({ isFetching: false })
- render(<InviteButton />)
+ renderInviteButton(false)
expect(screen.getByRole('button', { name: /members\.invite/i })).toBeInTheDocument()
})
it('should show loading status while permissions are loading', () => {
- setupMocks({ brandingEnabled: true, isFetching: true })
+ setupPermissions({ isFetching: true })
- render(<InviteButton />)
+ renderInviteButton(true)
expect(screen.getByRole('status')).toBeInTheDocument()
})
it('should hide invite button when permission is denied', () => {
- setupMocks({ brandingEnabled: true, isFetching: false, allowInvite: false })
+ setupPermissions({ isFetching: false, allowInvite: false })
- render(<InviteButton />)
+ renderInviteButton(true)
expect(screen.queryByRole('button', { name: /members\.invite/i })).not.toBeInTheDocument()
})
it('should show invite button when permission is granted', () => {
- setupMocks({ brandingEnabled: true, isFetching: false, allowInvite: true })
+ setupPermissions({ isFetching: false, allowInvite: true })
- render(<InviteButton />)
+ renderInviteButton(true)
expect(screen.getByRole('button', { name: /members\.invite/i })).toBeInTheDocument()
})
diff --git a/web/app/components/header/account-setting/members-page/index.tsx b/web/app/components/header/account-setting/members-page/index.tsx
index f671eed94a7..cf25a2446a0 100644
--- a/web/app/components/header/account-setting/members-page/index.tsx
+++ b/web/app/components/header/account-setting/members-page/index.tsx
@@ -2,17 +2,18 @@
import type { InvitationResult } from '@/models/common'
import { Avatar } from '@langgenius/dify-ui/avatar'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { NUM_INFINITE } from '@/app/components/billing/config'
import { Plan } from '@/app/components/billing/type'
import UpgradeBtn from '@/app/components/billing/upgrade-btn'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useLocale } from '@/context/i18n'
import { useProviderContext } from '@/context/provider-context'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import { LanguagesSupported } from '@/i18n-config/language'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useMembers } from '@/service/use-common'
import EditWorkspaceModal from './edit-workspace-modal'
import InviteButton from './invite-button'
@@ -35,7 +36,7 @@ const MembersPage = () => {
const { userProfile, currentWorkspace, isCurrentWorkspaceOwner, isCurrentWorkspaceManager } = useAppContext()
const { data, refetch } = useMembers()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { formatTimeFromNow } = useFormatTimeFromNow()
const [inviteModalVisible, setInviteModalVisible] = useState(false)
const [invitationResults, setInvitationResults] = useState<InvitationResult[]>([])
diff --git a/web/app/components/header/account-setting/members-page/invite-button.tsx b/web/app/components/header/account-setting/members-page/invite-button.tsx
index c703924112f..a9a8b88dcf4 100644
--- a/web/app/components/header/account-setting/members-page/invite-button.tsx
+++ b/web/app/components/header/account-setting/members-page/invite-button.tsx
@@ -1,9 +1,10 @@
import { Button } from '@langgenius/dify-ui/button'
import { RiUserAddLine } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useWorkspacePermissions } from '@/service/use-workspace'
type InviteButtonProps = {
@@ -14,7 +15,7 @@ type InviteButtonProps = {
const InviteButton = (props: InviteButtonProps) => {
const { t } = useTranslation()
const { currentWorkspace } = useAppContext()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { data: workspacePermissions, isFetching: isFetchingWorkspacePermissions } = useWorkspacePermissions(currentWorkspace!.id, systemFeatures.branding.enabled)
if (systemFeatures.branding.enabled) {
if (isFetchingWorkspacePermissions) {
diff --git a/web/app/components/header/account-setting/members-page/operation/__tests__/transfer-ownership.spec.tsx b/web/app/components/header/account-setting/members-page/operation/__tests__/transfer-ownership.spec.tsx
index a38e66a2f8a..f7b8f1dd5a2 100644
--- a/web/app/components/header/account-setting/members-page/operation/__tests__/transfer-ownership.spec.tsx
+++ b/web/app/components/header/account-setting/members-page/operation/__tests__/transfer-ownership.spec.tsx
@@ -1,36 +1,38 @@
import type { AppContextValue } from '@/context/app-context'
import type { ICurrentWorkspace } from '@/models/common'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useWorkspacePermissions } from '@/service/use-workspace'
import TransferOwnership from '../transfer-ownership'
vi.mock('@/context/app-context')
-vi.mock('@/context/global-public-context')
vi.mock('@/service/use-workspace')
describe('TransferOwnership', () => {
- const setupMocks = ({
- brandingEnabled,
+ const setupPermissions = ({
isFetching,
allowOwnerTransfer,
}: {
- brandingEnabled: boolean
isFetching: boolean
allowOwnerTransfer?: boolean
}) => {
- vi.mocked(useGlobalPublicStore).mockImplementation(selector => selector({
- systemFeatures: { branding: { enabled: brandingEnabled } },
- } as unknown as Parameters<typeof selector>[0]))
vi.mocked(useWorkspacePermissions).mockReturnValue({
data: allowOwnerTransfer === undefined ? null : { allow_owner_transfer: allowOwnerTransfer },
isFetching,
} as unknown as ReturnType<typeof useWorkspacePermissions>)
}
+ const renderTransferOwnership = (
+ brandingEnabled: boolean,
+ onOperate: () => void = vi.fn(),
+ ) =>
+ renderWithSystemFeatures(<TransferOwnership onOperate={onOperate} />, {
+ systemFeatures: { branding: { enabled: brandingEnabled } },
+ })
+
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(useAppContext).mockReturnValue({
@@ -39,17 +41,17 @@ describe('TransferOwnership', () => {
})
it('should show loading status while permissions are loading', () => {
- setupMocks({ brandingEnabled: true, isFetching: true })
+ setupPermissions({ isFetching: true })
- render(<TransferOwnership onOperate={vi.fn()} />)
+ renderTransferOwnership(true)
expect(screen.getByRole('status')).toBeInTheDocument()
})
it('should show owner text without transfer menu when transfer is forbidden', () => {
- setupMocks({ brandingEnabled: true, isFetching: false, allowOwnerTransfer: false })
+ setupPermissions({ isFetching: false, allowOwnerTransfer: false })
- render(<TransferOwnership onOperate={vi.fn()} />)
+ renderTransferOwnership(true)
expect(screen.getByText(/members\.owner/i)).toBeInTheDocument()
expect(screen.queryByText(/members\.transferOwnership/i)).toBeNull()
@@ -59,9 +61,9 @@ describe('TransferOwnership', () => {
const user = userEvent.setup()
const onOperate = vi.fn()
- setupMocks({ brandingEnabled: true, isFetching: false, allowOwnerTransfer: true })
+ setupPermissions({ isFetching: false, allowOwnerTransfer: true })
- render(<TransferOwnership onOperate={onOperate} />)
+ renderTransferOwnership(true, onOperate)
await user.click(screen.getByRole('button', { name: /members\.owner/i }))
const transferOptionText = await screen.findByText(/members\.transferOwnership/i)
@@ -78,9 +80,9 @@ describe('TransferOwnership', () => {
it('should allow transfer menu when branding is disabled', async () => {
const user = userEvent.setup()
- setupMocks({ brandingEnabled: false, isFetching: false })
+ setupPermissions({ isFetching: false })
- render(<TransferOwnership onOperate={vi.fn()} />)
+ renderTransferOwnership(false)
await user.click(screen.getByRole('button', { name: /members\.owner/i }))
diff --git a/web/app/components/header/account-setting/members-page/operation/transfer-ownership.tsx b/web/app/components/header/account-setting/members-page/operation/transfer-ownership.tsx
index b485aed7048..97a4a5b2f28 100644
--- a/web/app/components/header/account-setting/members-page/operation/transfer-ownership.tsx
+++ b/web/app/components/header/account-setting/members-page/operation/transfer-ownership.tsx
@@ -4,11 +4,12 @@ import { cn } from '@langgenius/dify-ui/cn'
import {
RiArrowDownSLine,
} from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { Fragment } from 'react'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useWorkspacePermissions } from '@/service/use-workspace'
type Props = {
@@ -18,7 +19,7 @@ type Props = {
const TransferOwnership = ({ onOperate }: Props) => {
const { t } = useTranslation()
const { currentWorkspace } = useAppContext()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { data: workspacePermissions, isFetching: isFetchingWorkspacePermissions } = useWorkspacePermissions(currentWorkspace!.id, systemFeatures.branding.enabled)
if (systemFeatures.branding.enabled) {
if (isFetchingWorkspacePermissions) {
diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsx
index 0fbed45fa65..8f9366635d5 100644
--- a/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/index.non-cloud.spec.tsx
@@ -1,4 +1,5 @@
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import {
CurrentSystemQuotaTypeEnum,
CustomConfigurationStatusEnum,
@@ -15,17 +16,13 @@ const mockQuotaConfig = {
is_valid: true,
}
-vi.mock('@/config', () => ({
- IS_CLOUD_EDITION: false,
-}))
-
-vi.mock('@/context/global-public-context', () => ({
- useSystemFeaturesQuery: () => ({
- data: {
- enable_marketplace: false,
- },
- }),
-}))
+vi.mock('@/config', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/config')>()
+ return {
+ ...actual,
+ IS_CLOUD_EDITION: false,
+ }
+})
vi.mock('@/context/provider-context', () => ({
useProviderContext: () => ({
@@ -62,26 +59,41 @@ vi.mock('../install-from-marketplace', () => ({
default: () => <div data-testid="install-from-marketplace" />,
}))
-vi.mock('@tanstack/react-query', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-query')>()
+vi.mock('@/service/client', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/client')>()
+ const originalPlugins = actual.consoleQuery.plugins as unknown as Record<string, unknown>
return {
...actual,
- useQuery: () => ({ data: undefined }),
+ consoleQuery: new Proxy(actual.consoleQuery, {
+ get(target, prop) {
+ if (prop === 'plugins') {
+ return {
+ ...originalPlugins,
+ checkInstalled: {
+ queryOptions: () => ({
+ queryKey: ['plugins', 'checkInstalled'],
+ queryFn: () => new Promise(() => {}),
+ }),
+ },
+ latestVersions: {
+ queryOptions: () => ({
+ queryKey: ['plugins', 'latestVersions'],
+ queryFn: () => new Promise(() => {}),
+ }),
+ },
+ }
+ }
+ return Reflect.get(target, prop)
+ },
+ }),
}
})
-vi.mock('@/service/client', () => ({
- consoleQuery: {
- plugins: {
- checkInstalled: { queryOptions: () => ({}) },
- latestVersions: { queryOptions: () => ({}) },
- },
- },
-}))
-
describe('ModelProviderPage non-cloud branch', () => {
it('should skip the quota panel when cloud edition is disabled', () => {
- render(<ModelProviderPage searchText="" />)
+ renderWithSystemFeatures(<ModelProviderPage searchText="" />, {
+ systemFeatures: { enable_marketplace: false },
+ })
expect(screen.getByTestId('system-model-selector')).toBeInTheDocument()
expect(screen.queryByTestId('quota-panel')).not.toBeInTheDocument()
diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx
index 8d6c59bbf29..6bf818a544c 100644
--- a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx
@@ -1,5 +1,6 @@
-import { act, render, screen } from '@testing-library/react'
+import { act, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import {
CurrentSystemQuotaTypeEnum,
CustomConfigurationStatusEnum,
@@ -7,8 +8,6 @@ import {
} from '../declarations'
import ModelProviderPage from '../index'
-let mockEnableMarketplace = true
-
const mockQuotaConfig = {
quota_type: CurrentSystemQuotaTypeEnum.free,
quota_unit: QuotaUnitEnum.times,
@@ -18,13 +17,14 @@ const mockQuotaConfig = {
is_valid: true,
}
-vi.mock('@/context/global-public-context', () => ({
- useSystemFeaturesQuery: () => ({
- data: {
- enable_marketplace: mockEnableMarketplace,
- },
- }),
-}))
+const renderModelProviderPage = (
+ props: { searchText?: string, enableMarketplace?: boolean } = {},
+) => {
+ const { searchText = '', enableMarketplace = true } = props
+ return renderWithSystemFeatures(<ModelProviderPage searchText={searchText} />, {
+ systemFeatures: { enable_marketplace: enableMarketplace },
+ })
+}
const mockProviders = [
{
@@ -83,28 +83,40 @@ vi.mock('../system-model-selector', () => ({
default: () => <div data-testid="system-model-selector" />,
}))
-vi.mock('@tanstack/react-query', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-query')>()
+vi.mock('@/service/client', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/client')>()
+ const originalPlugins = actual.consoleQuery.plugins as unknown as Record<string, unknown>
return {
...actual,
- useQuery: () => ({ data: undefined }),
+ consoleQuery: new Proxy(actual.consoleQuery, {
+ get(target, prop) {
+ if (prop === 'plugins') {
+ return {
+ ...originalPlugins,
+ checkInstalled: {
+ queryOptions: () => ({
+ queryKey: ['plugins', 'checkInstalled'],
+ queryFn: () => new Promise(() => {}),
+ }),
+ },
+ latestVersions: {
+ queryOptions: () => ({
+ queryKey: ['plugins', 'latestVersions'],
+ queryFn: () => new Promise(() => {}),
+ }),
+ },
+ }
+ }
+ return Reflect.get(target, prop)
+ },
+ }),
}
})
-vi.mock('@/service/client', () => ({
- consoleQuery: {
- plugins: {
- checkInstalled: { queryOptions: () => ({}) },
- latestVersions: { queryOptions: () => ({}) },
- },
- },
-}))
-
describe('ModelProviderPage', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.clearAllMocks()
- mockEnableMarketplace = true
Object.keys(mockDefaultModels).forEach((key) => {
mockDefaultModels[key] = { data: null, isLoading: false }
})
@@ -134,21 +146,21 @@ describe('ModelProviderPage', () => {
})
it('should render main elements', () => {
- render(<ModelProviderPage searchText="" />)
+ renderModelProviderPage()
expect(screen.getByText('common.modelProvider.models')).toBeInTheDocument()
expect(screen.getByTestId('system-model-selector')).toBeInTheDocument()
expect(screen.getByTestId('install-from-marketplace')).toBeInTheDocument()
})
it('should render configured and not configured providers sections', () => {
- render(<ModelProviderPage searchText="" />)
+ renderModelProviderPage()
expect(screen.getByText('openai')).toBeInTheDocument()
expect(screen.getByText('common.modelProvider.toBeConfigured')).toBeInTheDocument()
expect(screen.getByText('anthropic')).toBeInTheDocument()
})
it('should filter providers based on search text', () => {
- render(<ModelProviderPage searchText="open" />)
+ renderModelProviderPage({ searchText: 'open' })
act(() => {
vi.advanceTimersByTime(600)
})
@@ -157,7 +169,7 @@ describe('ModelProviderPage', () => {
})
it('should show empty state if no configured providers match', () => {
- render(<ModelProviderPage searchText="non-existent" />)
+ renderModelProviderPage({ searchText: 'non-existent' })
act(() => {
vi.advanceTimersByTime(600)
})
@@ -165,9 +177,7 @@ describe('ModelProviderPage', () => {
})
it('should hide marketplace section when marketplace feature is disabled', () => {
- mockEnableMarketplace = false
-
- render(<ModelProviderPage searchText="" />)
+ renderModelProviderPage({ enableMarketplace: false })
expect(screen.queryByTestId('install-from-marketplace')).not.toBeInTheDocument()
})
@@ -185,14 +195,14 @@ describe('ModelProviderPage', () => {
},
})
- render(<ModelProviderPage searchText="" />)
+ renderModelProviderPage()
expect(screen.queryByText('common.modelProvider.noneConfigured')).not.toBeInTheDocument()
expect(screen.queryByText('common.modelProvider.notConfigured')).not.toBeInTheDocument()
expect(screen.getByText('common.modelProvider.emptyProviderTitle')).toBeInTheDocument()
})
it('should show none-configured warning when providers exist but no default models set', () => {
- render(<ModelProviderPage searchText="" />)
+ renderModelProviderPage()
expect(screen.getByText('common.modelProvider.noneConfigured')).toBeInTheDocument()
})
@@ -202,7 +212,7 @@ describe('ModelProviderPage', () => {
isLoading: false,
}
- render(<ModelProviderPage searchText="" />)
+ renderModelProviderPage()
expect(screen.getByText('common.modelProvider.notConfigured')).toBeInTheDocument()
})
@@ -217,7 +227,7 @@ describe('ModelProviderPage', () => {
mockDefaultModels.speech2text = makeModel('whisper-1', 'speech2text')
mockDefaultModels.tts = makeModel('tts-1', 'tts')
- render(<ModelProviderPage searchText="" />)
+ renderModelProviderPage()
expect(screen.queryByText('common.modelProvider.noProviderInstalled')).not.toBeInTheDocument()
expect(screen.queryByText('common.modelProvider.noneConfigured')).not.toBeInTheDocument()
expect(screen.queryByText('common.modelProvider.notConfigured')).not.toBeInTheDocument()
@@ -228,7 +238,7 @@ describe('ModelProviderPage', () => {
mockDefaultModels[key] = { data: null, isLoading: true }
})
- render(<ModelProviderPage searchText="" />)
+ renderModelProviderPage()
expect(screen.queryByText('common.modelProvider.noProviderInstalled')).not.toBeInTheDocument()
expect(screen.queryByText('common.modelProvider.noneConfigured')).not.toBeInTheDocument()
expect(screen.queryByText('common.modelProvider.notConfigured')).not.toBeInTheDocument()
@@ -265,7 +275,7 @@ describe('ModelProviderPage', () => {
},
})
- render(<ModelProviderPage searchText="" />)
+ renderModelProviderPage()
const renderedProviders = screen.getAllByTestId('provider-card').map(item => item.textContent)
expect(renderedProviders).toEqual([
diff --git a/web/app/components/header/account-setting/model-provider-page/index.tsx b/web/app/components/header/account-setting/model-provider-page/index.tsx
index 06ab1776cb4..6522ea2db4c 100644
--- a/web/app/components/header/account-setting/model-provider-page/index.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/index.tsx
@@ -3,15 +3,15 @@ import type {
} from './declarations'
import type { PluginDetail } from '@/app/components/plugins/types'
import { cn } from '@langgenius/dify-ui/cn'
-import { useQuery } from '@tanstack/react-query'
+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useDebounce } from 'ahooks'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { usePluginsWithLatestVersion } from '@/app/components/plugins/hooks'
import { IS_CLOUD_EDITION } from '@/config'
-import { useSystemFeaturesQuery } from '@/context/global-public-context'
import { useProviderContext } from '@/context/provider-context'
import { consoleQuery } from '@/service/client'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import {
CustomConfigurationStatusEnum,
ModelTypeEnum,
@@ -42,7 +42,7 @@ const ModelProviderPage = ({ searchText }: Props) => {
const { data: speech2textDefaultModel, isLoading: isSpeech2textDefaultModelLoading } = useDefaultModel(ModelTypeEnum.speech2text)
const { data: ttsDefaultModel, isLoading: isTTSDefaultModelLoading } = useDefaultModel(ModelTypeEnum.tts)
const { modelProviders: providers } = useProviderContext()
- const { data: systemFeatures } = useSystemFeaturesQuery()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const allPluginIds = useMemo(() => {
return [...new Set(providers.map(p => providerToPluginId(p.provider)).filter(Boolean))]
@@ -59,7 +59,7 @@ const ModelProviderPage = ({ searchText }: Props) => {
map.set(plugin.plugin_id, plugin)
return map
}, [enrichedPlugins])
- const enableMarketplace = systemFeatures?.enable_marketplace ?? false
+ const enableMarketplace = systemFeatures.enable_marketplace
const isDefaultModelLoading = isTextGenerationDefaultModelLoading
|| isEmbeddingsDefaultModelLoading
|| isRerankDefaultModelLoading
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx
index 61d6bb4466a..318b5bcd73c 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx
@@ -1,5 +1,8 @@
+import type { ReactElement } from 'react'
import type { Model, ModelItem, ModelProvider } from '../../declarations'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import type { SystemFeatures } from '@/types/feature'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import {
ConfigurationMethodEnum,
ModelFeatureEnum,
@@ -59,11 +62,12 @@ vi.mock('@/context/provider-context', () => ({
useProviderContext: () => ({ modelProviders: mockContextModelProviders.current }),
}))
-vi.mock('@/context/global-public-context', () => ({
- useSystemFeaturesQuery: () => ({
- data: { trial_models: mockTrialModels.current },
- }),
-}))
+const renderPopup = (ui: ReactElement) => renderWithSystemFeatures(ui, {
+ // The Popup component never inspects trial_models beyond passing them
+ // through, so an opaque string[] is enough; cast to satisfy the
+ // ModelProviderQuotaGetPaid[] declared on SystemFeatures.
+ systemFeatures: { trial_models: mockTrialModels.current as unknown as SystemFeatures['trial_models'] },
+})
const mockTrialCredits = vi.hoisted(() => ({
credits: 200,
@@ -183,7 +187,7 @@ describe('Popup', () => {
})
it('should filter models by search and allow clearing search', () => {
- const { container } = render(
+ const { container } = renderPopup(
<Popup
modelList={[makeModel()]}
onSelect={vi.fn()}
@@ -204,7 +208,7 @@ describe('Popup', () => {
})
it('should not show compatible-only helper text when no scope features are applied', () => {
- render(
+ renderPopup(
<Popup
modelList={[makeModel()]}
onSelect={vi.fn()}
@@ -216,7 +220,7 @@ describe('Popup', () => {
})
it('should show compatible-only helper banner when scope features are applied', () => {
- const { container } = render(
+ const { container } = renderPopup(
<Popup
modelList={[makeModel()]}
onSelect={vi.fn()}
@@ -236,7 +240,7 @@ describe('Popup', () => {
]
mockSupportFunctionCall.mockReturnValue(false)
- const { unmount } = render(
+ const { unmount } = renderPopup(
<Popup
modelList={modelList}
onSelect={vi.fn()}
@@ -248,7 +252,7 @@ describe('Popup', () => {
unmount()
mockSupportFunctionCall.mockReturnValue(true)
- const { unmount: unmount2 } = render(
+ const { unmount: unmount2 } = renderPopup(
<Popup
modelList={modelList}
onSelect={vi.fn()}
@@ -259,7 +263,7 @@ describe('Popup', () => {
expect(screen.getByText('openai'))!.toBeInTheDocument()
unmount2()
- const { unmount: unmount3 } = render(
+ const { unmount: unmount3 } = renderPopup(
<Popup
modelList={modelList}
onSelect={vi.fn()}
@@ -270,7 +274,7 @@ describe('Popup', () => {
expect(screen.getByText('openai'))!.toBeInTheDocument()
unmount3()
- render(
+ renderPopup(
<Popup
modelList={[makeModel({ models: [makeModelItem({ features: undefined })] })]}
onSelect={vi.fn()}
@@ -284,7 +288,7 @@ describe('Popup', () => {
it('should match model labels from fallback languages when current language key is missing', () => {
mockLanguage = 'fr_FR'
- render(
+ renderPopup(
<Popup
modelList={[
makeModel({
@@ -323,7 +327,7 @@ describe('Popup', () => {
}),
]
- render(
+ renderPopup(
<Popup
modelList={[makeModel()]}
onSelect={vi.fn()}
@@ -350,7 +354,7 @@ describe('Popup', () => {
}),
]
- render(
+ renderPopup(
<Popup
modelList={[makeModel()]}
onSelect={vi.fn()}
@@ -380,7 +384,7 @@ describe('Popup', () => {
}),
]
- render(
+ renderPopup(
<Popup
modelList={[makeModel()]}
onSelect={vi.fn()}
@@ -393,7 +397,7 @@ describe('Popup', () => {
it('should open provider settings when clicking footer link', () => {
const onHide = vi.fn()
- render(
+ renderPopup(
<Popup
modelList={[makeModel()]}
onSelect={vi.fn()}
@@ -411,7 +415,7 @@ describe('Popup', () => {
it('should show empty state when no providers are configured', () => {
const onHide = vi.fn()
- render(
+ renderPopup(
<Popup
modelList={[]}
onSelect={vi.fn()}
@@ -432,7 +436,7 @@ describe('Popup', () => {
it('should render marketplace providers that are not installed', () => {
mockContextModelProviders.current = [makeContextProvider({ provider: 'test-openai' })]
- render(
+ renderPopup(
<Popup
modelList={[]}
onSelect={vi.fn()}
@@ -454,7 +458,7 @@ describe('Popup', () => {
} as MockContextProvider['system_configuration'],
})]
- render(
+ renderPopup(
<Popup
modelList={[]}
onSelect={vi.fn()}
@@ -479,7 +483,7 @@ describe('Popup', () => {
} as MockContextProvider['system_configuration'],
})]
- render(
+ renderPopup(
<Popup
modelList={[]}
onSelect={vi.fn()}
@@ -493,7 +497,7 @@ describe('Popup', () => {
})
it('should toggle marketplace section collapse', () => {
- render(
+ renderPopup(
<Popup
modelList={[]}
onSelect={vi.fn()}
@@ -518,7 +522,7 @@ describe('Popup', () => {
]
mockInstallMutateAsync.mockResolvedValue({ all_installed: true, task_id: 'task-1' })
- render(
+ renderPopup(
<Popup
modelList={[]}
onSelect={vi.fn()}
@@ -541,7 +545,7 @@ describe('Popup', () => {
]
mockInstallMutateAsync.mockRejectedValue(new Error('Install failed'))
- render(
+ renderPopup(
<Popup
modelList={[]}
onSelect={vi.fn()}
@@ -567,7 +571,7 @@ describe('Popup', () => {
mockInstallMutateAsync.mockResolvedValue({ all_installed: false, task_id: 'task-1' })
mockCheck.mockResolvedValue(undefined)
- render(
+ renderPopup(
<Popup
modelList={[]}
onSelect={vi.fn()}
@@ -593,7 +597,7 @@ describe('Popup', () => {
]
mockMarketplacePlugins.isLoading = true
- render(
+ renderPopup(
<Popup
modelList={[]}
onSelect={vi.fn()}
@@ -611,7 +615,7 @@ describe('Popup', () => {
it('should skip install requests when the marketplace plugin cannot be found', async () => {
mockMarketplacePlugins.current = []
- render(
+ renderPopup(
<Popup
modelList={[]}
onSelect={vi.fn()}
@@ -627,7 +631,7 @@ describe('Popup', () => {
})
it('should sort the selected provider to the top when a default model is provided', () => {
- render(
+ renderPopup(
<Popup
defaultModel={{ provider: 'anthropic', model: 'claude-3' }}
modelList={[
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx
index 017194aaf5e..ec07b6c1140 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx
@@ -7,15 +7,16 @@ import type {
import type { ModelProviderQuotaGetPaid } from '@/types/model-provider'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useTheme } from 'next-themes'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'
import checkTaskStatus from '@/app/components/plugins/install-plugin/base/check-task-status'
import useRefreshPluginList from '@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list'
-import { useSystemFeaturesQuery } from '@/context/global-public-context'
import { useModalContext } from '@/context/modal-context'
import { useProviderContext } from '@/context/provider-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useInstallPackageFromMarketPlace } from '@/service/use-plugins'
import { supportFunctionCall } from '@/utils/tool-call'
import { getMarketplaceUrl } from '@/utils/var'
@@ -60,8 +61,8 @@ const Popup: FC<PopupProps> = ({
const { refreshPluginList } = useRefreshPluginList()
const [installingProvider, setInstallingProvider] = useState<ModelProviderQuotaGetPaid | null>(null)
const { isExhausted: isCreditsExhausted } = useTrialCredits()
- const { data: systemFeatures } = useSystemFeaturesQuery()
- const trialModels = systemFeatures?.trial_models
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
+ const trialModels = systemFeatures.trial_models
const installedProviderMap = useMemo(() => new Map(
modelProviders.map(provider => [provider.provider, provider]),
), [modelProviders])
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx
index f07f9652f88..9d158a019e9 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx
@@ -1,6 +1,6 @@
import type { ModelProvider } from '../../declarations'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, screen, waitFor } from '@testing-library/react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import {
ConfigurationMethodEnum,
CurrentSystemQuotaTypeEnum,
@@ -28,10 +28,6 @@ vi.mock('@/config', async (importOriginal) => {
return { ...actual, IS_CLOUD_EDITION: true }
})
-vi.mock('@/context/global-public-context', () => ({
- useSystemFeaturesQuery: () => ({ data: { trial_models: ['langgenius/openai/openai'] } }),
-}))
-
vi.mock('@langgenius/dify-ui/toast', () => ({
default: { notify: mockToastNotify },
toast: {
@@ -42,24 +38,33 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
},
}))
-vi.mock('@/service/client', () => ({
- consoleQuery: {
- modelProviders: {
- models: {
- queryKey: ({ input }: { input: { params: { provider: string } } }) => ['console', 'modelProviders', 'models', input.params.provider],
- },
- changePreferredProviderType: {
- mutationOptions: (opts: Record<string, unknown>) => ({
- mutationFn: (...args: unknown[]) => {
- mockChangePriorityFn(...args)
- return Promise.resolve({ result: 'success' })
- },
- ...opts,
- }),
- },
+vi.mock('@/service/client', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/client')>()
+ const mockedModelProviders = {
+ models: {
+ queryKey: ({ input }: { input: { params: { provider: string } } }) => ['console', 'modelProviders', 'models', input.params.provider],
},
- },
-}))
+ changePreferredProviderType: {
+ mutationOptions: (opts: Record<string, unknown>) => ({
+ mutationFn: (...args: unknown[]) => {
+ mockChangePriorityFn(...args)
+ return Promise.resolve({ result: 'success' })
+ },
+ ...opts,
+ }),
+ },
+ }
+ return {
+ ...actual,
+ consoleQuery: new Proxy(actual.consoleQuery, {
+ get(target, prop) {
+ if (prop === 'modelProviders')
+ return mockedModelProviders
+ return Reflect.get(target, prop)
+ },
+ }),
+ }
+})
vi.mock('../../hooks', () => ({
useUpdateModelList: () => mockUpdateModelList,
@@ -88,13 +93,6 @@ vi.mock('@/app/components/base/icons/src/vender/line/alertsAndFeedback/Warning',
default: (props: Record<string, unknown>) => <div data-testid="warning-icon" className={props.className as string} />,
}))
-const createTestQueryClient = () => new QueryClient({
- defaultOptions: {
- queries: { retry: false, gcTime: 0 },
- mutations: { retry: false },
- },
-})
-
const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({
provider: 'langgenius/openai/openai',
provider_credential_schema: { credential_form_schemas: [] },
@@ -112,12 +110,9 @@ const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider =
} as unknown as ModelProvider)
const renderWithQueryClient = (provider: ModelProvider) => {
- const queryClient = createTestQueryClient()
- return render(
- <QueryClientProvider client={queryClient}>
- <CredentialPanel provider={provider} />
- </QueryClientProvider>,
- )
+ return renderWithSystemFeatures(<CredentialPanel provider={provider} />, {
+ systemFeatures: { trial_models: ['langgenius/openai/openai'] as never },
+ })
}
describe('CredentialPanel', () => {
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsx
index a3e527680f2..db17ab7fc51 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsx
@@ -1,5 +1,7 @@
+import type { ReactElement } from 'react'
import type { ModelProvider } from '../../declarations'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import QuotaPanel from '../quota-panel'
let mockWorkspaceData: {
@@ -37,11 +39,9 @@ vi.mock('@/service/use-common', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useSystemFeaturesQuery: () => ({
- data: mockTrialModels ? { trial_models: mockTrialModels } : undefined,
- }),
-}))
+const renderQuotaPanel = (ui: ReactElement) => renderWithSystemFeatures(ui, {
+ systemFeatures: mockTrialModels === undefined ? null : { trial_models: mockTrialModels as never },
+})
vi.mock('../../hooks', () => ({
useMarketplaceAllPlugins: () => ({
@@ -89,12 +89,12 @@ describe('QuotaPanel', () => {
mockWorkspaceData = undefined
mockWorkspaceIsPending = true
- render(<QuotaPanel providers={mockProviders} />)
+ renderQuotaPanel(<QuotaPanel providers={mockProviders} />)
expect(screen.getByRole('status')).toBeInTheDocument()
})
it('should show remaining credits and reset date', () => {
- render(
+ renderQuotaPanel(
<QuotaPanel
providers={mockProviders}
/>,
@@ -108,7 +108,7 @@ describe('QuotaPanel', () => {
it('should keep quota content during background refetch when cached workspace exists', () => {
mockWorkspaceIsPending = true
- render(<QuotaPanel providers={mockProviders} />)
+ renderQuotaPanel(<QuotaPanel providers={mockProviders} />)
expect(screen.queryByRole('status')).not.toBeInTheDocument()
expect(screen.getByText('70')).toBeInTheDocument()
@@ -121,14 +121,14 @@ describe('QuotaPanel', () => {
next_credit_reset_date: '',
}
- render(<QuotaPanel providers={mockProviders} />)
+ renderQuotaPanel(<QuotaPanel providers={mockProviders} />)
expect(screen.getByText(/modelProvider\.card\.quotaExhausted/)).toBeInTheDocument()
expect(screen.queryByText(/modelProvider\.resetDate/)).not.toBeInTheDocument()
})
it('should open install modal when clicking an unsupported trial provider', () => {
- render(<QuotaPanel providers={[]} />)
+ renderQuotaPanel(<QuotaPanel providers={[]} />)
fireEvent.click(screen.getByText('openai'))
@@ -136,7 +136,7 @@ describe('QuotaPanel', () => {
})
it('should close install modal when provider becomes installed', async () => {
- const { rerender } = render(<QuotaPanel providers={[]} />)
+ const { rerender } = renderQuotaPanel(<QuotaPanel providers={[]} />)
fireEvent.click(screen.getByText('openai'))
expect(screen.getByText('install modal')).toBeInTheDocument()
@@ -151,13 +151,13 @@ describe('QuotaPanel', () => {
it('should tolerate missing trial model configuration', () => {
mockTrialModels = undefined
- render(<QuotaPanel providers={mockProviders} />)
+ renderQuotaPanel(<QuotaPanel providers={mockProviders} />)
expect(screen.queryByText('openai')).not.toBeInTheDocument()
})
it('should render installed custom providers without opening the install modal', () => {
- render(<QuotaPanel providers={mockProviders} />)
+ renderQuotaPanel(<QuotaPanel providers={mockProviders} />)
expect(screen.getByLabelText(/modelAPI/)).toBeInTheDocument()
@@ -167,7 +167,7 @@ describe('QuotaPanel', () => {
})
it('should show the supported-model tooltip for installed non-custom providers', () => {
- render(
+ renderQuotaPanel(
<QuotaPanel providers={[
{
provider: 'langgenius/openai/openai',
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-credential-panel-state.spec.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-credential-panel-state.spec.ts
index c58abfb44d5..2052c1eb8dc 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-credential-panel-state.spec.ts
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/use-credential-panel-state.spec.ts
@@ -1,5 +1,5 @@
import type { ModelProvider } from '../../declarations'
-import { renderHook } from '@testing-library/react'
+import { renderHookWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import {
ConfigurationMethodEnum,
CurrentSystemQuotaTypeEnum,
@@ -15,15 +15,16 @@ vi.mock('../use-trial-credits', () => ({
useTrialCredits: () => mockTrialCredits,
}))
-vi.mock('@/context/global-public-context', () => ({
- useSystemFeaturesQuery: () => ({ data: { trial_models: mockTrialModels } }),
-}))
-
vi.mock('@/config', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/config')>()
return { ...actual, IS_CLOUD_EDITION: true }
})
+const renderPanelHook = (provider: ModelProvider | undefined) =>
+ renderHookWithSystemFeatures(() => useCredentialPanelState(provider), {
+ systemFeatures: { trial_models: mockTrialModels as never },
+ })
+
const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({
provider: 'langgenius/openai/openai',
provider_credential_schema: { credential_form_schemas: [] },
@@ -49,7 +50,7 @@ describe('useCredentialPanelState', () => {
// Credits priority variants
describe('Credits priority variants', () => {
it('should return credits-active when credits available', () => {
- const { result } = renderHook(() => useCredentialPanelState(createProvider()))
+ const { result } = renderPanelHook(createProvider())
expect(result.current.variant).toBe('credits-active')
expect(result.current.priority).toBe('credits')
@@ -60,7 +61,7 @@ describe('useCredentialPanelState', () => {
mockTrialCredits.isExhausted = true
mockTrialCredits.credits = 0
- const { result } = renderHook(() => useCredentialPanelState(createProvider()))
+ const { result } = renderPanelHook(createProvider())
expect(result.current.variant).toBe('api-fallback')
})
@@ -76,7 +77,7 @@ describe('useCredentialPanelState', () => {
},
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.variant).toBe('no-usage')
})
@@ -90,7 +91,7 @@ describe('useCredentialPanelState', () => {
},
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.variant).toBe('credits-exhausted')
})
@@ -103,7 +104,7 @@ describe('useCredentialPanelState', () => {
preferred_provider_type: PreferredProviderTypeEnum.custom,
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.variant).toBe('api-active')
expect(result.current.priority).toBe('apiKey')
@@ -120,7 +121,7 @@ describe('useCredentialPanelState', () => {
},
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.variant).toBe('credits-fallback')
})
@@ -134,7 +135,7 @@ describe('useCredentialPanelState', () => {
},
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.variant).toBe('credits-fallback')
})
@@ -150,7 +151,7 @@ describe('useCredentialPanelState', () => {
},
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.variant).toBe('no-usage')
})
@@ -168,7 +169,7 @@ describe('useCredentialPanelState', () => {
},
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.variant).toBe('api-unavailable')
})
@@ -186,7 +187,7 @@ describe('useCredentialPanelState', () => {
},
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.variant).toBe('api-required-configure')
})
@@ -199,7 +200,7 @@ describe('useCredentialPanelState', () => {
system_configuration: { enabled: false, current_quota_type: CurrentSystemQuotaTypeEnum.trial, quota_configurations: [] },
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.priority).toBe('apiKeyOnly')
expect(result.current.supportsCredits).toBe(false)
@@ -212,7 +213,7 @@ describe('useCredentialPanelState', () => {
preferred_provider_type: PreferredProviderTypeEnum.system,
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.priority).toBe('apiKeyOnly')
expect(result.current.supportsCredits).toBe(false)
@@ -223,7 +224,7 @@ describe('useCredentialPanelState', () => {
// Undefined provider
describe('Undefined provider', () => {
it('should return safe defaults when provider is undefined', () => {
- const { result } = renderHook(() => useCredentialPanelState(undefined))
+ const { result } = renderPanelHook(undefined)
expect(result.current.priority).toBe('apiKeyOnly')
expect(result.current.supportsCredits).toBe(false)
@@ -237,7 +238,7 @@ describe('useCredentialPanelState', () => {
it('should show priority switcher when credits supported and custom config active', () => {
const provider = createProvider()
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.showPrioritySwitcher).toBe(true)
})
@@ -247,7 +248,7 @@ describe('useCredentialPanelState', () => {
system_configuration: { enabled: false, current_quota_type: CurrentSystemQuotaTypeEnum.trial, quota_configurations: [] },
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.showPrioritySwitcher).toBe(false)
})
@@ -258,13 +259,13 @@ describe('useCredentialPanelState', () => {
system_configuration: { enabled: true, current_quota_type: CurrentSystemQuotaTypeEnum.trial, quota_configurations: [] },
})
- const { result } = renderHook(() => useCredentialPanelState(provider))
+ const { result } = renderPanelHook(provider)
expect(result.current.showPrioritySwitcher).toBe(false)
})
it('should expose credential name from provider', () => {
- const { result } = renderHook(() => useCredentialPanelState(createProvider()))
+ const { result } = renderPanelHook(createProvider())
expect(result.current.credentialName).toBe('My Key')
})
@@ -272,7 +273,7 @@ describe('useCredentialPanelState', () => {
it('should expose credits amount', () => {
mockTrialCredits.credits = 500
- const { result } = renderHook(() => useCredentialPanelState(createProvider()))
+ const { result } = renderPanelHook(createProvider())
expect(result.current.credits).toBe(500)
})
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx
index 7828dc4635f..bbc2cfaa988 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx
@@ -4,14 +4,15 @@ import type { Plugin } from '@/app/components/plugins/types'
import type { ModelProviderQuotaGetPaid } from '@/types/model-provider'
import { cn } from '@langgenius/dify-ui/cn'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useBoolean } from 'ahooks'
import * as React from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'
-import { useSystemFeaturesQuery } from '@/context/global-public-context'
import useTimestamp from '@/hooks/use-timestamp'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { formatNumber } from '@/utils/format'
import { PreferredProviderTypeEnum } from '../declarations'
import { useMarketplaceAllPlugins } from '../hooks'
@@ -32,8 +33,8 @@ const QuotaPanel: FC<QuotaPanelProps> = ({
}) => {
const { t } = useTranslation()
const { credits, isExhausted, isLoading, nextCreditResetDate } = useTrialCredits()
- const { data: systemFeatures } = useSystemFeaturesQuery()
- const trialModels = systemFeatures?.trial_models ?? []
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
+ const trialModels = systemFeatures.trial_models
const providerMap = useMemo(() => new Map(
providers.map(p => [p.provider, p.preferred_provider_type]),
), [providers])
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.ts
index c9ca9d105fa..e8a5f0f8a58 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.ts
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.ts
@@ -1,6 +1,7 @@
import type { ModelProvider } from '../declarations'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCredentialStatus } from '@/app/components/header/account-setting/model-provider-page/model-auth/hooks'
-import { useSystemFeaturesQuery } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import {
PreferredProviderTypeEnum,
} from '../declarations'
@@ -79,8 +80,8 @@ export function useCredentialPanelState(provider: ModelProvider | undefined): Cr
current_credential_name,
} = useCredentialStatus(provider)
- const { data: systemFeatures } = useSystemFeaturesQuery()
- const trialModels = systemFeatures?.trial_models
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
+ const trialModels = systemFeatures.trial_models
const preferredType = provider?.preferred_provider_type
diff --git a/web/app/components/header/index.tsx b/web/app/components/header/index.tsx
index d92fd032fd7..c7c12f1e350 100644
--- a/web/app/components/header/index.tsx
+++ b/web/app/components/header/index.tsx
@@ -1,15 +1,16 @@
'use client'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback } from 'react'
import DifyLogo from '@/app/components/base/logo/dify-logo'
import WorkplaceSelector from '@/app/components/header/account-dropdown/workplace-selector'
import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useModalContext } from '@/context/modal-context'
import { useProviderContext } from '@/context/provider-context'
import { WorkspaceProvider } from '@/context/workspace-context-provider'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import Link from '@/next/link'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { Plan } from '../billing/type'
import AccountDropdown from './account-dropdown'
import AppNav from './app-nav'
@@ -33,7 +34,7 @@ const Header = () => {
const isMobile = media === MediaType.mobile
const { enableBilling, plan } = useProviderContext()
const { setShowPricingModal, setShowAccountSettingModal } = useModalContext()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const isFreePlan = plan.type === Plan.sandbox
const isBrandingEnabled = systemFeatures.branding.enabled
const handlePlanClick = useCallback(() => {
diff --git a/web/app/components/header/license-env/__tests__/index.spec.tsx b/web/app/components/header/license-env/__tests__/index.spec.tsx
index cec4af60d9c..ec8959da789 100644
--- a/web/app/components/header/license-env/__tests__/index.spec.tsx
+++ b/web/app/components/header/license-env/__tests__/index.spec.tsx
@@ -1,7 +1,7 @@
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import dayjs from 'dayjs'
-import { useGlobalPublicStore } from '@/context/global-public-context'
-import { defaultSystemFeatures, LicenseStatus } from '@/types/feature'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
+import { LicenseStatus } from '@/types/feature'
import LicenseNav from '../index'
describe('LicenseNav', () => {
@@ -10,9 +10,6 @@ describe('LicenseNav', () => {
vi.useFakeTimers()
const now = new Date('2024-01-01T12:00:00Z')
vi.setSystemTime(now)
- useGlobalPublicStore.setState({
- systemFeatures: defaultSystemFeatures,
- })
})
afterEach(() => {
@@ -20,72 +17,60 @@ describe('LicenseNav', () => {
})
it('should render null when license status is NONE', () => {
- const { container } = render(<LicenseNav />)
+ const { container } = renderWithSystemFeatures(<LicenseNav />)
expect(container).toBeEmptyDOMElement()
})
it('should render Enterprise badge when license status is ACTIVE', () => {
- useGlobalPublicStore.setState({
+ renderWithSystemFeatures(<LicenseNav />, {
systemFeatures: {
- ...defaultSystemFeatures,
license: {
status: LicenseStatus.ACTIVE,
expired_at: null,
},
},
})
-
- render(<LicenseNav />)
expect(screen.getByText('Enterprise')).toBeInTheDocument()
})
it('should render singular expiring message when license expires in 0 days', () => {
const expiredAt = dayjs().add(2, 'hours').toISOString()
- useGlobalPublicStore.setState({
+ renderWithSystemFeatures(<LicenseNav />, {
systemFeatures: {
- ...defaultSystemFeatures,
license: {
status: LicenseStatus.EXPIRING,
expired_at: expiredAt,
},
},
})
-
- render(<LicenseNav />)
expect(screen.getByText(/license\.expiring/)).toBeInTheDocument()
expect(screen.getByText(/count":0/)).toBeInTheDocument()
})
it('should render singular expiring message when license expires in 1 day', () => {
const tomorrow = dayjs().add(1, 'day').add(1, 'hour').toISOString()
- useGlobalPublicStore.setState({
+ renderWithSystemFeatures(<LicenseNav />, {
systemFeatures: {
- ...defaultSystemFeatures,
license: {
status: LicenseStatus.EXPIRING,
expired_at: tomorrow,
},
},
})
-
- render(<LicenseNav />)
expect(screen.getByText(/license\.expiring/)).toBeInTheDocument()
expect(screen.getByText(/count":1/)).toBeInTheDocument()
})
it('should render plural expiring message when license expires in 5 days', () => {
const fiveDaysLater = dayjs().add(5, 'day').add(1, 'hour').toISOString()
- useGlobalPublicStore.setState({
+ renderWithSystemFeatures(<LicenseNav />, {
systemFeatures: {
- ...defaultSystemFeatures,
license: {
status: LicenseStatus.EXPIRING,
expired_at: fiveDaysLater,
},
},
})
-
- render(<LicenseNav />)
expect(screen.getByText(/license\.expiring_plural/)).toBeInTheDocument()
expect(screen.getByText(/count":5/)).toBeInTheDocument()
})
diff --git a/web/app/components/header/license-env/index.tsx b/web/app/components/header/license-env/index.tsx
index 2e505ddd415..fd360796b1a 100644
--- a/web/app/components/header/license-env/index.tsx
+++ b/web/app/components/header/license-env/index.tsx
@@ -1,15 +1,16 @@
'use client'
import { RiHourglass2Fill } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import dayjs from 'dayjs'
import { useTranslation } from 'react-i18next'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { LicenseStatus } from '@/types/feature'
import PremiumBadge from '../../base/premium-badge'
const LicenseNav = () => {
const { t } = useTranslation()
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
if (systemFeatures.license?.status === LicenseStatus.EXPIRING) {
const expiredAt = systemFeatures.license?.expired_at
diff --git a/web/app/components/plugins/install-plugin/hooks/__tests__/use-install-plugin-limit.spec.ts b/web/app/components/plugins/install-plugin/hooks/__tests__/use-install-plugin-limit.spec.ts
index fa01b63b5a2..c6881e5c88e 100644
--- a/web/app/components/plugins/install-plugin/hooks/__tests__/use-install-plugin-limit.spec.ts
+++ b/web/app/components/plugins/install-plugin/hooks/__tests__/use-install-plugin-limit.spec.ts
@@ -1,20 +1,8 @@
-import { renderHook } from '@testing-library/react'
-import { describe, expect, it, vi } from 'vitest'
+import { describe, expect, it } from 'vitest'
+import { renderHookWithSystemFeatures as renderHook } from '@/__tests__/utils/mock-system-features'
import { InstallationScope } from '@/types/feature'
import { pluginInstallLimit } from '../use-install-plugin-limit'
-const mockSystemFeatures = {
- plugin_installation_permission: {
- restrict_to_marketplace_only: false,
- plugin_installation_scope: InstallationScope.ALL,
- },
-}
-
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: typeof mockSystemFeatures }) => unknown) =>
- selector({ systemFeatures: mockSystemFeatures }),
-}))
-
const basePlugin = {
from: 'marketplace' as const,
verification: { authorized_category: 'langgenius' },
diff --git a/web/app/components/plugins/install-plugin/hooks/use-install-plugin-limit.tsx b/web/app/components/plugins/install-plugin/hooks/use-install-plugin-limit.tsx
index 227c572a778..ccc28c74c10 100644
--- a/web/app/components/plugins/install-plugin/hooks/use-install-plugin-limit.tsx
+++ b/web/app/components/plugins/install-plugin/hooks/use-install-plugin-limit.tsx
@@ -1,6 +1,7 @@
import type { Plugin, PluginManifestInMarket } from '../../types'
import type { SystemFeatures } from '@/types/feature'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { useSuspenseQuery } from '@tanstack/react-query'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { InstallationScope } from '@/types/feature'
type PluginProps = (Plugin | PluginManifestInMarket) & { from: 'github' | 'marketplace' | 'package' }
@@ -41,6 +42,6 @@ export function pluginInstallLimit(plugin: PluginProps, systemFeatures: SystemFe
}
export default function usePluginInstallLimit(plugin: PluginProps) {
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
return pluginInstallLimit(plugin, systemFeatures)
}
diff --git a/web/app/components/plugins/install-plugin/install-bundle/__tests__/index.spec.tsx b/web/app/components/plugins/install-plugin/install-bundle/__tests__/index.spec.tsx
index fee88913b79..dd3d63aa326 100644
--- a/web/app/components/plugins/install-plugin/install-bundle/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/install-plugin/install-bundle/__tests__/index.spec.tsx
@@ -1,6 +1,7 @@
import type { Dependency, GitHubItemAndMarketPlaceDependency, InstallStatus, PackageDependency, Plugin, PluginDeclaration, VersionProps } from '../../../types'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures as render } from '@/__tests__/utils/mock-system-features'
import { InstallStep, PluginCategoryEnum } from '../../../types'
import InstallBundle, { InstallType } from '../index'
import GithubItem from '../item/github-item'
@@ -183,11 +184,6 @@ vi.mock('@/context/mitt-context', () => ({
useMittContextSelector: () => vi.fn(),
}))
-// Mock global public context
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: () => ({}),
-}))
-
// Mock useCanInstallPluginFromMarketplace
vi.mock('@/app/components/plugins/plugin-page/use-reference-setting', () => ({
useCanInstallPluginFromMarketplace: () => ({ canInstallPluginFromMarketplace: true }),
diff --git a/web/app/components/plugins/install-plugin/install-bundle/steps/__tests__/install-multi.spec.tsx b/web/app/components/plugins/install-plugin/install-bundle/steps/__tests__/install-multi.spec.tsx
index d45b05bfd16..5a2bbf7ea93 100644
--- a/web/app/components/plugins/install-plugin/install-bundle/steps/__tests__/install-multi.spec.tsx
+++ b/web/app/components/plugins/install-plugin/install-bundle/steps/__tests__/install-multi.spec.tsx
@@ -1,7 +1,8 @@
import type { Dependency, GitHubItemAndMarketPlaceDependency, PackageDependency, Plugin, VersionInfo } from '../../../../types'
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures as render } from '@/__tests__/utils/mock-system-features'
import { PluginCategoryEnum } from '../../../../types'
import InstallMulti from '../install-multi'
@@ -56,11 +57,6 @@ vi.mock('@/app/components/plugins/install-plugin/hooks/use-check-installed', ()
}),
}))
-// Mock useGlobalPublicStore
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: () => ({}),
-}))
-
// Mock pluginInstallLimit (imported by the useInstallMultiState hook via @/ path)
vi.mock('@/app/components/plugins/install-plugin/hooks/use-install-plugin-limit', () => ({
pluginInstallLimit: () => ({ canInstall: true }),
diff --git a/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/__tests__/use-install-multi-state.spec.ts b/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/__tests__/use-install-multi-state.spec.ts
index 47f85d35cf0..9506ca1b0b7 100644
--- a/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/__tests__/use-install-multi-state.spec.ts
+++ b/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/__tests__/use-install-multi-state.spec.ts
@@ -1,6 +1,7 @@
import type { Dependency, GitHubItemAndMarketPlaceDependency, PackageDependency, Plugin, VersionInfo } from '@/app/components/plugins/types'
-import { act, renderHook, waitFor } from '@testing-library/react'
+import { act, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderHookWithSystemFeatures as renderHook } from '@/__tests__/utils/mock-system-features'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { getPluginKey, useInstallMultiState } from '../use-install-multi-state'
@@ -23,10 +24,6 @@ vi.mock('@/app/components/plugins/install-plugin/hooks/use-check-installed', ()
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: () => ({}),
-}))
-
vi.mock('@/app/components/plugins/install-plugin/hooks/use-install-plugin-limit', () => ({
pluginInstallLimit: () => ({ canInstall: mockCanInstall }),
}))
diff --git a/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/use-install-multi-state.ts b/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/use-install-multi-state.ts
index ca06f33c160..196f4533253 100644
--- a/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/use-install-multi-state.ts
+++ b/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/use-install-multi-state.ts
@@ -1,10 +1,11 @@
'use client'
import type { Dependency, GitHubItemAndMarketPlaceDependency, PackageDependency, Plugin, VersionInfo } from '@/app/components/plugins/types'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback, useEffect, useMemo, useState } from 'react'
import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use-check-installed'
import { pluginInstallLimit } from '@/app/components/plugins/install-plugin/hooks/use-install-plugin-limit'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useFetchPluginsInMarketPlaceByInfo } from '@/service/use-plugins'
type UseInstallMultiStateParams = {
@@ -86,7 +87,7 @@ export function useInstallMultiState({
onSelect,
onLoadedAllPlugin,
}: UseInstallMultiStateParams) {
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
// Marketplace plugins filtering and index mapping
const marketplacePlugins = useMemo(
diff --git a/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsx b/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsx
index 63cf25d0398..875b526cfd5 100644
--- a/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsx
@@ -1,10 +1,19 @@
+import type { ReactElement } from 'react'
import type { PluginDetail } from '../../types'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import * as amplitude from '@/app/components/base/amplitude'
import { PluginSource } from '../../types'
import DetailHeader from '../detail-header'
+let mockEnableMarketplace = true
+
+const render = (ui: ReactElement) =>
+ renderWithSystemFeatures(ui, {
+ systemFeatures: { enable_marketplace: mockEnableMarketplace },
+ })
+
const { mockToast } = vi.hoisted(() => ({
mockToast: Object.assign(vi.fn(), {
success: vi.fn(),
@@ -70,13 +79,7 @@ vi.mock('@/context/i18n', () => ({
useLocale: () => 'en-US',
}))
-// Global mock state for enable_marketplace
-let mockEnableMarketplace = true
-
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { enable_marketplace: boolean } }) => unknown) =>
- selector({ systemFeatures: { enable_marketplace: mockEnableMarketplace } }),
-}))
+// Global mock state for enable_marketplace seeded into the QueryClient via the local render helper.
vi.mock('@/context/modal-context', () => ({
useModalContext: () => ({
diff --git a/web/app/components/plugins/plugin-detail-panel/__tests__/operation-dropdown.spec.tsx b/web/app/components/plugins/plugin-detail-panel/__tests__/operation-dropdown.spec.tsx
index db6ff579570..5a870c6c826 100644
--- a/web/app/components/plugins/plugin-detail-panel/__tests__/operation-dropdown.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/__tests__/operation-dropdown.spec.tsx
@@ -1,14 +1,13 @@
import type { ReactElement, ReactNode } from 'react'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { fireEvent, screen } from '@testing-library/react'
import { cloneElement } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { PluginSource } from '../../types'
import OperationDropdown from '../operation-dropdown'
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: <T,>(selector: (state: { systemFeatures: { enable_marketplace: boolean } }) => T): T =>
- selector({ systemFeatures: { enable_marketplace: true } }),
-}))
+const render = (ui: ReactElement) =>
+ renderWithSystemFeatures(ui, { systemFeatures: { enable_marketplace: true } })
vi.mock('@langgenius/dify-ui/cn', () => ({
cn: (...args: (string | undefined | false | null)[]) => args.filter(Boolean).join(' '),
diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-detail-header-state.spec.ts b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-detail-header-state.spec.ts
index 044d03ca61e..04eb78ad983 100644
--- a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-detail-header-state.spec.ts
+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-detail-header-state.spec.ts
@@ -1,14 +1,16 @@
import type { PluginDetail } from '../../../../types'
-import { act, renderHook } from '@testing-library/react'
+import { act } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderHookWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { PluginSource } from '../../../../types'
import { useDetailHeaderState } from '../use-detail-header-state'
let mockEnableMarketplace = true
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { enable_marketplace: boolean } }) => unknown) =>
- selector({ systemFeatures: { enable_marketplace: mockEnableMarketplace } }),
-}))
+
+const renderHook = <Result>(callback: () => Result) =>
+ renderHookWithSystemFeatures(callback, {
+ systemFeatures: { enable_marketplace: mockEnableMarketplace },
+ })
let mockAutoUpgradeInfo: {
strategy_setting: string
diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.ts b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.ts
index 3af7fc41730..8ebcbe0dc1b 100644
--- a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.ts
+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.ts
@@ -1,9 +1,10 @@
'use client'
import type { PluginDetail } from '../../../types'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useBoolean } from 'ahooks'
import { useCallback, useMemo, useState } from 'react'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import useReferenceSetting from '../../../plugin-page/use-reference-setting'
import { AUTO_UPDATE_MODE } from '../../../reference-setting-modal/auto-update-setting/types'
import { PluginSource } from '../../../types'
@@ -48,7 +49,10 @@ type UseDetailHeaderStateReturn = {
}
export const useDetailHeaderState = (detail: PluginDetail): UseDetailHeaderStateReturn => {
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const { referenceSetting } = useReferenceSetting()
const {
diff --git a/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsx b/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsx
index c7a1529a3e4..76ed8799d2e 100644
--- a/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsx
@@ -9,9 +9,10 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { PluginSource } from '../types'
type Props = {
@@ -39,7 +40,10 @@ const OperationDropdown: FC<Props> = ({
}) => {
const { t } = useTranslation()
const [open, setOpen] = React.useState(false)
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
diff --git a/web/app/components/plugins/plugin-item/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-item/__tests__/index.spec.tsx
index 39f3915f99c..9d713042ccb 100644
--- a/web/app/components/plugins/plugin-item/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-item/__tests__/index.spec.tsx
@@ -1,9 +1,18 @@
+import type { ReactElement } from 'react'
import type { PluginDeclaration, PluginDetail } from '../../types'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { fireEvent, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { PluginCategoryEnum, PluginSource } from '../../types'
import PluginItem from '../index'
+const mockEnableMarketplace = vi.fn(() => true)
+
+const render = (ui: ReactElement) =>
+ renderWithSystemFeatures(ui, {
+ systemFeatures: { enable_marketplace: mockEnableMarketplace() },
+ })
+
const mockTheme = vi.fn(() => 'light')
vi.mock('@/hooks/use-theme', () => ({
default: () => ({ theme: mockTheme() }),
@@ -54,12 +63,6 @@ vi.mock('@/context/app-context', () => ({
}),
}))
-const mockEnableMarketplace = vi.fn(() => true)
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (s: Record<string, unknown>) => unknown) =>
- selector({ systemFeatures: { enable_marketplace: mockEnableMarketplace() } }),
-}))
-
vi.mock('../action', () => ({
default: ({ onDelete, pluginName }: { onDelete: () => void, pluginName: string }) => (
<div data-testid="plugin-action" data-plugin-name={pluginName}>
diff --git a/web/app/components/plugins/plugin-item/index.tsx b/web/app/components/plugins/plugin-item/index.tsx
index 0f19db81e60..5843dffbe98 100644
--- a/web/app/components/plugins/plugin-item/index.tsx
+++ b/web/app/components/plugins/plugin-item/index.tsx
@@ -9,6 +9,7 @@ import {
RiHardDrive3Line,
RiLoginCircleLine,
} from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
@@ -16,9 +17,9 @@ import Tooltip from '@/app/components/base/tooltip'
import useRefreshPluginList from '@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list'
import { API_PREFIX } from '@/config'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import useTheme from '@/hooks/use-theme'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { isEqualOrLaterThanVersion } from '@/utils/semver'
import { getMarketplaceUrl } from '@/utils/var'
import Badge from '../../base/badge'
@@ -85,7 +86,10 @@ const PluginItem: FC<Props> = ({
const getValueFromI18nObject = useRenderI18nObject()
const title = getValueFromI18nObject(label)
const descriptionText = getValueFromI18nObject(description)
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const iconFileName = theme === 'dark' && icon_dark ? icon_dark : icon
const iconSrc = iconFileName
? (iconFileName.startsWith('http') ? iconFileName : `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${tenant_id}&filename=${iconFileName}`)
diff --git a/web/app/components/plugins/plugin-page/__tests__/context-provider.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/context-provider.spec.tsx
index 476ab8e1455..ea56d75fc94 100644
--- a/web/app/components/plugins/plugin-page/__tests__/context-provider.spec.tsx
+++ b/web/app/components/plugins/plugin-page/__tests__/context-provider.spec.tsx
@@ -1,14 +1,11 @@
-import { fireEvent, screen } from '@testing-library/react'
+import type { ReactElement, ReactNode } from 'react'
+import { fireEvent, render, screen } from '@testing-library/react'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { useGlobalPublicStore } from '@/context/global-public-context'
-import { renderWithNuqs } from '@/test/nuqs-testing'
+import { createSystemFeaturesWrapper } from '@/__tests__/utils/mock-system-features'
import { usePluginPageContext } from '../context'
import { PluginPageContextProvider } from '../context-provider'
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
vi.mock('../../hooks', () => ({
PLUGIN_PAGE_TABS_MAP: {
plugins: 'plugins',
@@ -20,11 +17,21 @@ vi.mock('../../hooks', () => ({
],
}))
-const mockGlobalPublicStore = (enableMarketplace: boolean) => {
- vi.mocked(useGlobalPublicStore).mockImplementation((selector) => {
- const state = { systemFeatures: { enable_marketplace: enableMarketplace } }
- return selector(state as Parameters<typeof selector>[0])
+const renderWithProviders = (
+ ui: ReactElement,
+ options: { enableMarketplace: boolean, searchParams?: string } = { enableMarketplace: true },
+) => {
+ const { wrapper: SystemFeaturesWrapper } = createSystemFeaturesWrapper({
+ systemFeatures: { enable_marketplace: options.enableMarketplace },
})
+ const Wrapper = ({ children }: { children: ReactNode }) => (
+ <SystemFeaturesWrapper>
+ <NuqsTestingAdapter searchParams={options.searchParams ?? ''}>
+ {children}
+ </NuqsTestingAdapter>
+ </SystemFeaturesWrapper>
+ )
+ return render(ui, { wrapper: Wrapper })
}
const Consumer = () => {
@@ -47,25 +54,22 @@ describe('PluginPageContextProvider', () => {
})
it('filters out the marketplace tab when the feature is disabled', () => {
- mockGlobalPublicStore(false)
-
- renderWithNuqs(
+ renderWithProviders(
<PluginPageContextProvider>
<Consumer />
</PluginPageContextProvider>,
+ { enableMarketplace: false },
)
expect(screen.getByTestId('options-count')).toHaveTextContent('1')
})
it('keeps the query-state tab and updates the current plugin id', () => {
- mockGlobalPublicStore(true)
-
- renderWithNuqs(
+ renderWithProviders(
<PluginPageContextProvider>
<Consumer />
</PluginPageContextProvider>,
- { searchParams: '?tab=discover' },
+ { enableMarketplace: true, searchParams: '?tab=discover' },
)
fireEvent.click(screen.getByText('select plugin'))
diff --git a/web/app/components/plugins/plugin-page/__tests__/context.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/context.spec.tsx
index 389c161e8af..e534776a852 100644
--- a/web/app/components/plugins/plugin-page/__tests__/context.spec.tsx
+++ b/web/app/components/plugins/plugin-page/__tests__/context.spec.tsx
@@ -1,7 +1,7 @@
-import { render, screen } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-// Import mocks
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { PluginPageContext, usePluginPageContext } from '../context'
import { PluginPageContextProvider } from '../context-provider'
@@ -14,10 +14,6 @@ vi.mock('nuqs', () => ({
useQueryState: vi.fn(() => ['plugins', vi.fn()]),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
vi.mock('../../hooks', () => ({
PLUGIN_PAGE_TABS_MAP: {
plugins: 'plugins',
@@ -29,13 +25,10 @@ vi.mock('../../hooks', () => ({
],
}))
-// Helper function to mock useGlobalPublicStore with marketplace setting
-const mockGlobalPublicStore = (enableMarketplace: boolean) => {
- vi.mocked(useGlobalPublicStore).mockImplementation((selector) => {
- const state = { systemFeatures: { enable_marketplace: enableMarketplace } }
- return selector(state as Parameters<typeof selector>[0])
+const renderWithMarketplace = (ui: ReactElement, enableMarketplace: boolean) =>
+ renderWithSystemFeatures(ui, {
+ systemFeatures: { enable_marketplace: enableMarketplace },
})
-}
// Test component that uses the context
const TestConsumer = () => {
@@ -62,12 +55,11 @@ describe('PluginPageContext', () => {
describe('PluginPageContextProvider', () => {
it('should provide context values to children', () => {
- mockGlobalPublicStore(true)
-
- render(
+ renderWithMarketplace(
<PluginPageContextProvider>
<TestConsumer />
</PluginPageContextProvider>,
+ true,
)
expect(screen.getByTestId('has-container-ref')).toHaveTextContent('true')
@@ -75,12 +67,11 @@ describe('PluginPageContext', () => {
})
it('should include marketplace tab when enable_marketplace is true', () => {
- mockGlobalPublicStore(true)
-
- render(
+ renderWithMarketplace(
<PluginPageContextProvider>
<TestConsumer />
</PluginPageContextProvider>,
+ true,
)
expect(screen.getByTestId('option-plugins')).toBeInTheDocument()
@@ -88,12 +79,11 @@ describe('PluginPageContext', () => {
})
it('should filter out marketplace tab when enable_marketplace is false', () => {
- mockGlobalPublicStore(false)
-
- render(
+ renderWithMarketplace(
<PluginPageContextProvider>
<TestConsumer />
</PluginPageContextProvider>,
+ false,
)
expect(screen.getByTestId('option-plugins')).toBeInTheDocument()
@@ -104,12 +94,11 @@ describe('PluginPageContext', () => {
describe('usePluginPageContext', () => {
it('should select specific context values', () => {
- mockGlobalPublicStore(true)
-
- render(
+ renderWithMarketplace(
<PluginPageContextProvider>
<TestConsumer />
</PluginPageContextProvider>,
+ true,
)
// activeTab should be 'plugins' from the mock
diff --git a/web/app/components/plugins/plugin-page/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/index.spec.tsx
index e02a2bcb57b..067cea0a427 100644
--- a/web/app/components/plugins/plugin-page/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-page/__tests__/index.spec.tsx
@@ -1,8 +1,10 @@
+import type { ReactElement } from 'react'
import type { PluginPageProps } from '../index'
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import { useQueryState } from 'nuqs'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { usePluginInstallation } from '@/hooks/use-query-params'
// Import mocked modules for assertions
import { fetchBundleInfoFromMarketPlace, fetchManifestFromMarketPlace } from '@/service/plugins'
@@ -10,6 +12,12 @@ import PluginPageWithContext from '../index'
let mockEnableMarketplace = true
+const render = (ui: ReactElement, options: Parameters<typeof renderWithSystemFeatures>[1] = {}) =>
+ renderWithSystemFeatures(ui, {
+ systemFeatures: { enable_marketplace: mockEnableMarketplace },
+ ...options,
+ })
+
// Mock external dependencies
vi.mock('@/service/plugins', () => ({
fetchManifestFromMarketPlace: vi.fn(),
@@ -29,17 +37,6 @@ vi.mock('@/context/i18n', () => ({
useDocLink: () => (path: string) => `https://docs.example.com${path}`,
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn((selector) => {
- const state = {
- systemFeatures: {
- enable_marketplace: mockEnableMarketplace,
- },
- }
- return selector(state)
- }),
-}))
-
vi.mock('@/context/app-context', () => ({
useAppContext: () => ({
isCurrentWorkspaceManager: true,
diff --git a/web/app/components/plugins/plugin-page/__tests__/install-plugin-dropdown.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/install-plugin-dropdown.spec.tsx
index 2dd884e18b5..6d6784dea81 100644
--- a/web/app/components/plugins/plugin-page/__tests__/install-plugin-dropdown.spec.tsx
+++ b/web/app/components/plugins/plugin-page/__tests__/install-plugin-dropdown.spec.tsx
@@ -1,5 +1,7 @@
-import { fireEvent, render, screen } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { fireEvent, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import InstallPluginDropdown from '../install-plugin-dropdown'
let portalOpen = false
@@ -14,14 +16,16 @@ const {
},
}))
-vi.mock('@/config', () => ({
- SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS: '.difypkg,.zip',
-}))
+vi.mock('@/config', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/config')>()
+ return {
+ ...actual,
+ SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS: '.difypkg,.zip',
+ }
+})
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: typeof mockSystemFeatures }) => unknown) =>
- selector({ systemFeatures: mockSystemFeatures }),
-}))
+const render = (ui: ReactElement) =>
+ renderWithSystemFeatures(ui, { systemFeatures: mockSystemFeatures })
vi.mock('@/app/components/base/icons/src/vender/solid/files', () => ({
FileZip: () => <span data-testid="file-zip-icon">file</span>,
diff --git a/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.ts b/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.ts
index efb31b5afb1..f195be3e78e 100644
--- a/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.ts
+++ b/web/app/components/plugins/plugin-page/__tests__/use-reference-setting.spec.ts
@@ -1,9 +1,9 @@
// Import mocks for assertions
import { toast } from '@langgenius/dify-ui/toast'
-import { renderHook, waitFor } from '@testing-library/react'
+import { waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderHookWithSystemFeatures as renderHook } from '@/__tests__/utils/mock-system-features'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useInvalidateReferenceSettings, useMutationReferenceSettings, useReferenceSettings } from '@/service/use-plugins'
import { PermissionType } from '../../types'
@@ -13,10 +13,6 @@ vi.mock('@/context/app-context', () => ({
useAppContext: vi.fn(),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
vi.mock('@/service/use-plugins', () => ({
useReferenceSettings: vi.fn(),
useMutationReferenceSettings: vi.fn(),
@@ -296,45 +292,22 @@ describe('useCanInstallPluginFromMarketplace Hook', () => {
})
it('should return true when marketplace is enabled and canManagement is true', () => {
- vi.mocked(useGlobalPublicStore).mockImplementation((selector) => {
- const state = {
- systemFeatures: {
- enable_marketplace: true,
- },
- }
- return selector(state as Parameters<typeof selector>[0])
+ const { result } = renderHook(() => useCanInstallPluginFromMarketplace(), {
+ systemFeatures: { enable_marketplace: true },
})
- const { result } = renderHook(() => useCanInstallPluginFromMarketplace())
-
expect(result.current.canInstallPluginFromMarketplace).toBe(true)
})
it('should return false when marketplace is disabled', () => {
- vi.mocked(useGlobalPublicStore).mockImplementation((selector) => {
- const state = {
- systemFeatures: {
- enable_marketplace: false,
- },
- }
- return selector(state as Parameters<typeof selector>[0])
+ const { result } = renderHook(() => useCanInstallPluginFromMarketplace(), {
+ systemFeatures: { enable_marketplace: false },
})
- const { result } = renderHook(() => useCanInstallPluginFromMarketplace())
-
expect(result.current.canInstallPluginFromMarketplace).toBe(false)
})
it('should return false when canManagement is false', () => {
- vi.mocked(useGlobalPublicStore).mockImplementation((selector) => {
- const state = {
- systemFeatures: {
- enable_marketplace: true,
- },
- }
- return selector(state as Parameters<typeof selector>[0])
- })
-
vi.mocked(useReferenceSettings).mockReturnValue({
data: {
permission: {
@@ -344,21 +317,14 @@ describe('useCanInstallPluginFromMarketplace Hook', () => {
},
} as ReturnType<typeof useReferenceSettings>)
- const { result } = renderHook(() => useCanInstallPluginFromMarketplace())
+ const { result } = renderHook(() => useCanInstallPluginFromMarketplace(), {
+ systemFeatures: { enable_marketplace: true },
+ })
expect(result.current.canInstallPluginFromMarketplace).toBe(false)
})
it('should return false when both marketplace is disabled and canManagement is false', () => {
- vi.mocked(useGlobalPublicStore).mockImplementation((selector) => {
- const state = {
- systemFeatures: {
- enable_marketplace: false,
- },
- }
- return selector(state as Parameters<typeof selector>[0])
- })
-
vi.mocked(useReferenceSettings).mockReturnValue({
data: {
permission: {
@@ -368,7 +334,9 @@ describe('useCanInstallPluginFromMarketplace Hook', () => {
},
} as ReturnType<typeof useReferenceSettings>)
- const { result } = renderHook(() => useCanInstallPluginFromMarketplace())
+ const { result } = renderHook(() => useCanInstallPluginFromMarketplace(), {
+ systemFeatures: { enable_marketplace: false },
+ })
expect(result.current.canInstallPluginFromMarketplace).toBe(false)
})
diff --git a/web/app/components/plugins/plugin-page/context-provider.tsx b/web/app/components/plugins/plugin-page/context-provider.tsx
index 83776b48f90..6347fde86f2 100644
--- a/web/app/components/plugins/plugin-page/context-provider.tsx
+++ b/web/app/components/plugins/plugin-page/context-provider.tsx
@@ -3,13 +3,14 @@
import type { ReactNode } from 'react'
import type { PluginPageTab } from './context'
import type { FilterState } from './filter-management'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { parseAsStringEnum, useQueryState } from 'nuqs'
import {
useMemo,
useRef,
useState,
} from 'react'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { PLUGIN_PAGE_TABS_MAP, usePluginPageTabs } from '../hooks'
import { PLUGIN_TYPE_SEARCH_MAP } from '../marketplace/constants'
import {
@@ -40,7 +41,10 @@ export const PluginPageContextProvider = ({
})
const [currentPluginID, setCurrentPluginID] = useState<string | undefined>()
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const tabs = usePluginPageTabs()
const options = useMemo(() => {
return enable_marketplace ? tabs : tabs.filter(tab => tab.value !== PLUGIN_PAGE_TABS_MAP.marketplace)
diff --git a/web/app/components/plugins/plugin-page/empty/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-page/empty/__tests__/index.spec.tsx
index 933814eca52..73a5dd379d9 100644
--- a/web/app/components/plugins/plugin-page/empty/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-page/empty/__tests__/index.spec.tsx
@@ -1,8 +1,10 @@
+import type { ReactElement } from 'react'
import type { FilterState } from '../../filter-management'
import type { SystemFeatures } from '@/types/feature'
-import { act, fireEvent, render, screen } from '@testing-library/react'
+import { act, fireEvent, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { defaultSystemFeatures, InstallationScope } from '@/types/feature'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
+import { InstallationScope } from '@/types/feature'
// ==================== Imports (after mocks) ====================
@@ -10,7 +12,9 @@ import Empty from '../index'
// ==================== Mock Setup ====================
-// Use vi.hoisted to define ALL mock state and functions
+// Use vi.hoisted to define ALL mock state and functions so the local render
+// helper below (and downstream `vi.mock` factories) can read from the same
+// shared object regardless of declaration order.
const {
mockSetActiveTab,
mockUseInstalledPluginList,
@@ -38,6 +42,9 @@ const {
}
})
+const render = (ui: ReactElement) =>
+ renderWithSystemFeatures(ui, { systemFeatures: mockState.systemFeatures })
+
// Mock plugin page context
vi.mock('../../context', () => ({
usePluginPageContext: (selector: (value: Record<string, unknown>) => unknown) => {
@@ -49,18 +56,6 @@ vi.mock('../../context', () => ({
},
}))
-// Mock global public store (Zustand store)
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: Record<string, unknown>) => unknown) => {
- return selector({
- systemFeatures: {
- ...defaultSystemFeatures,
- ...mockState.systemFeatures,
- },
- })
- },
-}))
-
// Mock useInstalledPluginList hook
vi.mock('@/service/use-plugins', () => ({
useInstalledPluginList: () => mockUseInstalledPluginList(),
diff --git a/web/app/components/plugins/plugin-page/empty/index.tsx b/web/app/components/plugins/plugin-page/empty/index.tsx
index e90918b4abd..7b9fab6f3e8 100644
--- a/web/app/components/plugins/plugin-page/empty/index.tsx
+++ b/web/app/components/plugins/plugin-page/empty/index.tsx
@@ -1,5 +1,6 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { noop } from 'es-toolkit/function'
import * as React from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
@@ -11,7 +12,7 @@ import { MagicBox } from '@/app/components/base/icons/src/vender/solid/mediaAndD
import InstallFromGitHub from '@/app/components/plugins/install-plugin/install-from-github'
import InstallFromLocalPackage from '@/app/components/plugins/install-plugin/install-from-local-package'
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useInstalledPluginList } from '@/service/use-plugins'
import Line from '../../marketplace/empty/line'
import { usePluginPageContext } from '../context'
@@ -27,7 +28,14 @@ const Empty = () => {
const fileInputRef = useRef<HTMLInputElement>(null)
const [selectedAction, setSelectedAction] = useState<string | null>(null)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
- const { enable_marketplace, plugin_installation_permission } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
+ const { data: plugin_installation_permission } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.plugin_installation_permission,
+ })
const setActiveTab = usePluginPageContext(v => v.setActiveTab)
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
diff --git a/web/app/components/plugins/plugin-page/index.tsx b/web/app/components/plugins/plugin-page/index.tsx
index f80d37189a9..61d5bfb387b 100644
--- a/web/app/components/plugins/plugin-page/index.tsx
+++ b/web/app/components/plugins/plugin-page/index.tsx
@@ -9,6 +9,7 @@ import {
RiDragDropLine,
RiEqualizer2Line,
} from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useBoolean } from 'ahooks'
import { noop } from 'es-toolkit/function'
import { useEffect, useMemo, useState } from 'react'
@@ -17,12 +18,12 @@ import TabSlider from '@/app/components/base/tab-slider'
import Tooltip from '@/app/components/base/tooltip'
import ReferenceSettingModal from '@/app/components/plugins/reference-setting-modal'
import { MARKETPLACE_API_PREFIX, SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useDocLink } from '@/context/i18n'
import useDocumentTitle from '@/hooks/use-document-title'
import { usePluginInstallation } from '@/hooks/use-query-params'
import Link from '@/next/link'
import { fetchBundleInfoFromMarketPlace, fetchManifestFromMarketPlace } from '@/service/plugins'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { sleep } from '@/utils'
import { PLUGIN_PAGE_TABS_MAP } from '../hooks'
import InstallFromLocalPackage from '../install-plugin/install-from-local-package'
@@ -121,7 +122,10 @@ const PluginPage = ({
const options = usePluginPageContext(v => v.options)
const activeTab = usePluginPageContext(v => v.activeTab)
const setActiveTab = usePluginPageContext(v => v.setActiveTab)
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const isPluginsTab = useMemo(() => activeTab === PLUGIN_PAGE_TABS_MAP.plugins, [activeTab])
const isExploringMarketplace = useMemo(() => {
diff --git a/web/app/components/plugins/plugin-page/install-plugin-dropdown.tsx b/web/app/components/plugins/plugin-page/install-plugin-dropdown.tsx
index dee3dc17bb6..f74de31159b 100644
--- a/web/app/components/plugins/plugin-page/install-plugin-dropdown.tsx
+++ b/web/app/components/plugins/plugin-page/install-plugin-dropdown.tsx
@@ -9,6 +9,7 @@ import {
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
import { RiAddLine, RiArrowDownSLine } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { noop } from 'es-toolkit/function'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -18,7 +19,7 @@ import { MagicBox } from '@/app/components/base/icons/src/vender/solid/mediaAndD
import InstallFromGitHub from '@/app/components/plugins/install-plugin/install-from-github'
import InstallFromLocalPackage from '@/app/components/plugins/install-plugin/install-from-local-package'
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
type Props = {
onSwitchToMarketplaceTab: () => void
@@ -38,7 +39,14 @@ const InstallPluginDropdown = ({
const [isMenuOpen, setIsMenuOpen] = useState(false)
const [selectedAction, setSelectedAction] = useState<string | null>(null)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
- const { enable_marketplace, plugin_installation_permission } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
+ const { data: plugin_installation_permission } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.plugin_installation_permission,
+ })
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
diff --git a/web/app/components/plugins/plugin-page/use-reference-setting.ts b/web/app/components/plugins/plugin-page/use-reference-setting.ts
index b688bdc11e6..7c62c1879af 100644
--- a/web/app/components/plugins/plugin-page/use-reference-setting.ts
+++ b/web/app/components/plugins/plugin-page/use-reference-setting.ts
@@ -1,8 +1,9 @@
import { toast } from '@langgenius/dify-ui/toast'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useInvalidateReferenceSettings, useMutationReferenceSettings, useReferenceSettings } from '@/service/use-plugins'
import { PermissionType } from '../types'
@@ -45,7 +46,10 @@ const useReferenceSetting = () => {
}
export const useCanInstallPluginFromMarketplace = () => {
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const { canManagement } = useReferenceSetting()
const canInstallPluginFromMarketplace = useMemo(() => {
diff --git a/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx b/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx
index f71780e2df0..95a9910038b 100644
--- a/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx
@@ -1,19 +1,18 @@
+import type { ReactElement } from 'react'
import type { AutoUpdateConfig } from '../auto-update-setting/types'
import type { Permissions, ReferenceSetting } from '@/app/components/plugins/types'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { PermissionType } from '@/app/components/plugins/types'
import { AUTO_UPDATE_MODE, AUTO_UPDATE_STRATEGY } from '../auto-update-setting/types'
import ReferenceSettingModal from '../index'
-// Mock global public store
const mockSystemFeatures = { enable_marketplace: true }
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (s: { systemFeatures: typeof mockSystemFeatures }) => typeof mockSystemFeatures) => {
- return selector({ systemFeatures: mockSystemFeatures })
- },
-}))
+
+const render = (ui: ReactElement) =>
+ renderWithSystemFeatures(ui, { systemFeatures: mockSystemFeatures })
// Mock Modal component
vi.mock('@/app/components/base/modal', () => ({
diff --git a/web/app/components/plugins/reference-setting-modal/index.tsx b/web/app/components/plugins/reference-setting-modal/index.tsx
index 061777e38b8..b93713bdd8e 100644
--- a/web/app/components/plugins/reference-setting-modal/index.tsx
+++ b/web/app/components/plugins/reference-setting-modal/index.tsx
@@ -3,13 +3,14 @@ import type { FC } from 'react'
import type { AutoUpdateConfig } from './auto-update-setting/types'
import type { Permissions, ReferenceSetting } from '@/app/components/plugins/types'
import { Button } from '@langgenius/dify-ui/button'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Modal from '@/app/components/base/modal'
import { PermissionType } from '@/app/components/plugins/types'
import OptionCard from '@/app/components/workflow/nodes/_base/components/option-card'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import AutoUpdateSetting from './auto-update-setting'
import { defaultValue as autoUpdateDefaultValue } from './auto-update-setting/config'
import Label from './label'
@@ -30,7 +31,10 @@ const PluginSettingModal: FC<Props> = ({
const { auto_upgrade: autoUpdateConfig, permission: privilege } = payload || {}
const [tempPrivilege, setTempPrivilege] = useState<Permissions>(privilege)
const [tempAutoUpdateConfig, setTempAutoUpdateConfig] = useState<AutoUpdateConfig>(autoUpdateConfig || autoUpdateDefaultValue)
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const handlePrivilegeChange = useCallback((key: string) => {
return (value: PermissionType) => {
setTempPrivilege({
diff --git a/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-app-state.spec.ts b/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-app-state.spec.ts
index 34636472a7b..df8dcf3f986 100644
--- a/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-app-state.spec.ts
+++ b/web/app/components/share/text-generation/hooks/__tests__/use-text-generation-app-state.spec.ts
@@ -1,7 +1,13 @@
-import { act, renderHook, waitFor } from '@testing-library/react'
+import { act, waitFor } from '@testing-library/react'
+import { renderHookWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { AppSourceType } from '@/service/share'
import { useTextGenerationAppState } from '../use-text-generation-app-state'
+const renderHook = <Result, Props = void>(callback: (props: Props) => Result) =>
+ renderHookWithSystemFeatures(callback, {
+ systemFeatures: { branding: { enabled: false, workspace_logo: '' } },
+ })
+
const {
changeLanguageMock,
fetchSavedMessageMock,
@@ -54,13 +60,6 @@ vi.mock('@/service/share', async () => {
}
})
-const mockSystemFeatures = {
- branding: {
- enabled: false,
- workspace_logo: null,
- },
-}
-
const defaultAppInfo = {
app_id: 'app-123',
site: {
@@ -163,11 +162,6 @@ const resetMockWebAppState = () => {
mockWebAppState.webAppAccessMode = 'public'
}
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: typeof mockSystemFeatures }) => unknown) =>
- selector({ systemFeatures: mockSystemFeatures }),
-}))
-
vi.mock('@/context/web-app-context', () => ({
useWebAppStore: (selector: (state: typeof mockWebAppState) => unknown) => selector(mockWebAppState),
}))
diff --git a/web/app/components/share/text-generation/hooks/use-text-generation-app-state.ts b/web/app/components/share/text-generation/hooks/use-text-generation-app-state.ts
index 8cca8d1d782..f56efc39029 100644
--- a/web/app/components/share/text-generation/hooks/use-text-generation-app-state.ts
+++ b/web/app/components/share/text-generation/hooks/use-text-generation-app-state.ts
@@ -3,14 +3,15 @@ import type { MoreLikeThisConfig, PromptConfig, SavedMessage, TextToSpeechConfig
import type { SiteInfo } from '@/models/share'
import type { VisionSettings } from '@/types/app'
import { toast } from '@langgenius/dify-ui/toast'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useWebAppStore } from '@/context/web-app-context'
import { useAppFavicon } from '@/hooks/use-app-favicon'
import useDocumentTitle from '@/hooks/use-document-title'
import { changeLanguage } from '@/i18n-config/client'
import { AppSourceType, fetchSavedMessage as doFetchSavedMessage, removeMessage, saveMessage } from '@/service/share'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { Resolution, TransferMethod } from '@/types/app'
import { userInputsFormToPromptVariables } from '@/utils/model-config'
@@ -33,7 +34,7 @@ type ShareAppParams = {
export const useTextGenerationAppState = ({ isInstalledApp, isWorkflow }: UseTextGenerationAppStateOptions) => {
const { t } = useTranslation()
const appSourceType = isInstalledApp ? AppSourceType.installedApp : AppSourceType.webApp
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const appData = useWebAppStore(s => s.appInfo)
const appParams = useWebAppStore(s => s.appParams)
const accessMode = useWebAppStore(s => s.webAppAccessMode)
diff --git a/web/app/components/splash.tsx b/web/app/components/splash.tsx
deleted file mode 100644
index 2e46b95f764..00000000000
--- a/web/app/components/splash.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-'use client'
-import type { FC, PropsWithChildren } from 'react'
-import * as React from 'react'
-import { useUserProfile } from '@/service/use-common'
-import Loading from './base/loading'
-
-const Splash: FC<PropsWithChildren> = () => {
- const { isPending } = useUserProfile()
-
- if (isPending) {
- return (
- <div className="fixed inset-0 z-9999999 flex h-full items-center justify-center bg-background-body">
- <Loading />
- </div>
- )
- }
-
- return null
-}
-export default React.memo(Splash)
diff --git a/web/app/components/tools/__tests__/provider-list.spec.tsx b/web/app/components/tools/__tests__/provider-list.spec.tsx
index a5cb4821bbe..6661c260835 100644
--- a/web/app/components/tools/__tests__/provider-list.spec.tsx
+++ b/web/app/components/tools/__tests__/provider-list.spec.tsx
@@ -1,5 +1,7 @@
+import type { ReactNode } from 'react'
import { cleanup, fireEvent, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createSystemFeaturesWrapper } from '@/__tests__/utils/mock-system-features'
import { renderWithNuqs } from '@/test/nuqs-testing'
import { ToolTypeEnum } from '../../workflow/block-selector/types'
import ProviderList from '../provider-list'
@@ -14,10 +16,6 @@ vi.mock('@/app/components/plugins/hooks', () => ({
}))
let mockEnableMarketplace = false
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (s: Record<string, unknown>) => unknown) =>
- selector({ systemFeatures: { enable_marketplace: mockEnableMarketplace } }),
-}))
const createDefaultCollections = () => [
{
@@ -206,8 +204,14 @@ describe('getToolType', () => {
})
const renderProviderList = (searchParams?: Record<string, string>) => {
+ const { wrapper: SystemFeaturesWrapper } = createSystemFeaturesWrapper({
+ systemFeatures: { enable_marketplace: mockEnableMarketplace },
+ })
+ const Wrapped = ({ children }: { children: ReactNode }) => (
+ <SystemFeaturesWrapper>{children}</SystemFeaturesWrapper>
+ )
return renderWithNuqs(
- <ProviderList />,
+ <Wrapped><ProviderList /></Wrapped>,
{ searchParams },
)
}
diff --git a/web/app/components/tools/provider-list.tsx b/web/app/components/tools/provider-list.tsx
index 7d400b7cf70..74fc47a8331 100644
--- a/web/app/components/tools/provider-list.tsx
+++ b/web/app/components/tools/provider-list.tsx
@@ -1,6 +1,7 @@
'use client'
import type { Collection } from './types'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { parseAsStringLiteral, useQueryState } from 'nuqs'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -15,7 +16,7 @@ import LabelFilter from '@/app/components/tools/labels/filter'
import CustomCreateCard from '@/app/components/tools/provider/custom-create-card'
import ProviderDetail from '@/app/components/tools/provider/detail'
import WorkflowToolEmpty from '@/app/components/tools/provider/empty'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useCheckInstalled, useInvalidateInstalledPluginList } from '@/service/use-plugins'
import { useAllToolProviders } from '@/service/use-tools'
import Marketplace from './marketplace'
@@ -39,7 +40,10 @@ const ProviderList = () => {
// searchParams.get('category') === 'workflow'
const { t } = useTranslation()
const { getTagLabel } = useTags()
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const containerRef = useRef<HTMLDivElement>(null)
const [activeTab, setActiveTab] = useQueryState('category', parseAsToolProviderCategory)
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
index 1a8a7d3a595..d9e9cbdb8db 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
+++ b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
@@ -1,6 +1,7 @@
-import { act, renderHook } from '@testing-library/react'
+import { act } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { renderHookWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useNodesSyncDraft } from '../use-nodes-sync-draft'
const mockGetNodes = vi.fn()
@@ -69,15 +70,6 @@ vi.mock('@/app/components/workflow/collaboration/core/collaboration-manager', ()
},
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { enable_collaboration_mode: boolean } }) => unknown) =>
- selector({
- systemFeatures: {
- enable_collaboration_mode: isCollaborationEnabled,
- },
- }),
-}))
-
vi.mock('@/app/components/workflow/hooks/use-serial-async-callback', () => ({
useSerialAsyncCallback: (fn: (...args: unknown[]) => Promise<void>, checkFn: () => boolean) =>
(...args: unknown[]) => {
@@ -91,14 +83,28 @@ vi.mock('@/service/workflow', () => ({
syncWorkflowDraft: (p: unknown) => mockSyncWorkflowDraft(p),
}))
-vi.mock('@/service/fetch', () => ({ postWithKeepalive: (...args: unknown[]) => mockPostWithKeepalive(...args) }))
-vi.mock('@/config', () => ({ API_PREFIX: '/api' }))
+vi.mock('@/service/fetch', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/fetch')>()
+ return {
+ ...actual,
+ postWithKeepalive: (...args: unknown[]) => mockPostWithKeepalive(...args),
+ }
+})
+vi.mock('@/config', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/config')>()
+ return { ...actual, API_PREFIX: '/api' }
+})
const mockHandleRefreshWorkflowDraft = vi.fn()
vi.mock('@/app/components/workflow-app/hooks', () => ({
useWorkflowRefreshDraft: () => ({ handleRefreshWorkflowDraft: mockHandleRefreshWorkflowDraft }),
}))
+const renderUseNodesSyncDraft = () =>
+ renderHookWithSystemFeatures(() => useNodesSyncDraft(), {
+ systemFeatures: { enable_collaboration_mode: isCollaborationEnabled },
+ })
+
describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -139,7 +145,7 @@ describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () =>
const error = { json: vi.fn().mockResolvedValue({ code: 'draft_workflow_not_sync' }), bodyUsed: false }
mockSyncWorkflowDraft.mockRejectedValue(error)
- const { result } = renderHook(() => useNodesSyncDraft())
+ const { result } = renderUseNodesSyncDraft()
await act(async () => {
await result.current.doSyncWorkflowDraft(false)
})
@@ -152,7 +158,7 @@ describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () =>
const error = { json: vi.fn().mockResolvedValue({ code: 'draft_workflow_not_sync' }), bodyUsed: false }
mockSyncWorkflowDraft.mockRejectedValue(error)
- const { result } = renderHook(() => useNodesSyncDraft())
+ const { result } = renderUseNodesSyncDraft()
await act(async () => {
await result.current.doSyncWorkflowDraft(true)
})
@@ -165,7 +171,7 @@ describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () =>
const error = { json: vi.fn().mockResolvedValue({ code: 'other_error' }), bodyUsed: false }
mockSyncWorkflowDraft.mockRejectedValue(error)
- const { result } = renderHook(() => useNodesSyncDraft())
+ const { result } = renderUseNodesSyncDraft()
await act(async () => {
await result.current.doSyncWorkflowDraft(false)
})
@@ -175,7 +181,7 @@ describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () =>
})
it('should not include source_workflow_id in draft sync payloads', async () => {
- const { result } = renderHook(() => useNodesSyncDraft())
+ const { result } = renderUseNodesSyncDraft()
await act(async () => {
await result.current.doSyncWorkflowDraft(false)
@@ -225,7 +231,7 @@ describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () =>
onSettled: vi.fn(),
}
- const { result } = renderHook(() => useNodesSyncDraft())
+ const { result } = renderUseNodesSyncDraft()
await act(async () => {
await result.current.doSyncWorkflowDraft(false, callbacks)
@@ -272,7 +278,7 @@ describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () =>
conversationVariables: [{ id: 'conversation-1' }],
}
- const { result } = renderHook(() => useNodesSyncDraft())
+ const { result } = renderUseNodesSyncDraft()
act(() => {
result.current.syncWorkflowDraftWhenPageClose()
@@ -296,7 +302,7 @@ describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () =>
onSettled: vi.fn(),
}
- const { result } = renderHook(() => useNodesSyncDraft())
+ const { result } = renderUseNodesSyncDraft()
await act(async () => {
await result.current.doSyncWorkflowDraft(false, callbacks)
@@ -314,7 +320,7 @@ describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () =>
mockCollaborationIsConnected.mockReturnValue(true)
mockCollaborationGetIsLeader.mockReturnValue(false)
- const { result } = renderHook(() => useNodesSyncDraft())
+ const { result } = renderUseNodesSyncDraft()
act(() => {
result.current.syncWorkflowDraftWhenPageClose()
diff --git a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
index 42946e14a84..0ac528c303f 100644
--- a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
+++ b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
@@ -1,5 +1,6 @@
import type { SyncDraftCallback } from '@/app/components/workflow/hooks-store'
import type { WorkflowDraftFeaturesPayload } from '@/service/workflow'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { produce } from 'immer'
import { useCallback } from 'react'
import { useStoreApi } from 'reactflow'
@@ -9,8 +10,8 @@ import { useSerialAsyncCallback } from '@/app/components/workflow/hooks/use-seri
import { useNodesReadOnly } from '@/app/components/workflow/hooks/use-workflow'
import { useWorkflowStore } from '@/app/components/workflow/store'
import { API_PREFIX } from '@/config'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { postWithKeepalive } from '@/service/fetch'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { syncWorkflowDraft } from '@/service/workflow'
import { useWorkflowRefreshDraft } from '.'
@@ -20,7 +21,10 @@ export const useNodesSyncDraft = () => {
const featuresStore = useFeaturesStore()
const { getNodesReadOnly } = useNodesReadOnly()
const { handleRefreshWorkflowDraft } = useWorkflowRefreshDraft()
- const isCollaborationEnabled = useGlobalPublicStore(s => s.systemFeatures.enable_collaboration_mode)
+ const { data: isCollaborationEnabled } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_collaboration_mode,
+ })
const getPostParams = useCallback(() => {
const {
diff --git a/web/app/components/workflow/__tests__/workflow-test-env.tsx b/web/app/components/workflow/__tests__/workflow-test-env.tsx
index bbc5fe98dda..549a055c1e6 100644
--- a/web/app/components/workflow/__tests__/workflow-test-env.tsx
+++ b/web/app/components/workflow/__tests__/workflow-test-env.tsx
@@ -72,6 +72,7 @@ import * as React from 'react'
import ReactFlow, { ReactFlowProvider } from 'reactflow'
import { temporal } from 'zundo'
import { create } from 'zustand'
+import { seedSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { WorkflowContext } from '../context'
import { HooksStoreContext } from '../hooks-store/provider'
import { createHooksStore } from '../hooks-store/store'
@@ -134,6 +135,7 @@ type WorkflowProviderOptions = {
initialStoreState?: Partial<Shape>
hooksStoreProps?: Partial<HooksStoreShape>
historyStore?: HistoryStoreConfig
+ queryClient?: QueryClient
}
type StoreInstances = {
@@ -152,17 +154,20 @@ function createStoresFromOptions(options: WorkflowProviderOptions): StoreInstanc
function createWorkflowWrapper(
stores: StoreInstances,
historyConfig?: HistoryStoreConfig,
+ externalQueryClient?: QueryClient,
) {
const historyCtxValue = historyConfig
? createTestHistoryStoreContext(historyConfig)
: undefined
- const queryClient = new QueryClient({
+ const queryClient = externalQueryClient ?? new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
})
+ if (!externalQueryClient)
+ seedSystemFeatures(queryClient)
return ({ children }: { children: React.ReactNode }) => {
let inner: React.ReactNode = children
@@ -215,10 +220,10 @@ export function renderWorkflowHook<R, P = undefined>(
hook: (props: P) => R,
options?: WorkflowHookTestOptions<P>,
): WorkflowHookTestResult<R, P> {
- const { initialStoreState, hooksStoreProps, historyStore: historyConfig, ...rest } = options ?? {}
+ const { initialStoreState, hooksStoreProps, historyStore: historyConfig, queryClient, ...rest } = options ?? {}
const stores = createStoresFromOptions({ initialStoreState, hooksStoreProps })
- const wrapper = createWorkflowWrapper(stores, historyConfig)
+ const wrapper = createWorkflowWrapper(stores, historyConfig, queryClient)
const renderResult = renderHook(hook, { wrapper, ...rest })
return { ...renderResult, ...stores }
@@ -244,10 +249,10 @@ export function renderWorkflowComponent(
ui: React.ReactElement,
options?: WorkflowComponentTestOptions,
): WorkflowComponentTestResult {
- const { initialStoreState, hooksStoreProps, historyStore: historyConfig, ...renderOptions } = options ?? {}
+ const { initialStoreState, hooksStoreProps, historyStore: historyConfig, queryClient, ...renderOptions } = options ?? {}
const stores = createStoresFromOptions({ initialStoreState, hooksStoreProps })
- const wrapper = createWorkflowWrapper(stores, historyConfig)
+ const wrapper = createWorkflowWrapper(stores, historyConfig, queryClient)
const renderResult = render(ui, { wrapper, ...renderOptions })
return { ...renderResult, ...stores }
diff --git a/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsx b/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsx
index 2b28662b45f..802516d729f 100644
--- a/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsx
@@ -1,24 +1,20 @@
+import type { ReactElement } from 'react'
import type { TriggerWithProvider } from '../types'
-import { render, screen, waitFor } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/hooks'
import { CollectionType } from '@/app/components/tools/types'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useGetLanguage, useLocale } from '@/context/i18n'
import useTheme from '@/hooks/use-theme'
import { useFeaturedTriggersRecommendations } from '@/service/use-plugins'
import { useAllTriggerPlugins, useInvalidateAllTriggerPlugins } from '@/service/use-triggers'
import { Theme } from '@/types/app'
-import { defaultSystemFeatures } from '@/types/feature'
import { useAvailableNodesMetaData } from '../../../workflow-app/hooks'
import useNodes from '../../store/workflow/use-nodes'
import { BlockEnum } from '../../types'
import AllStartBlocks from '../all-start-blocks'
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
vi.mock('@/context/i18n', () => ({
useGetLanguage: vi.fn(),
useLocale: vi.fn(),
@@ -57,7 +53,6 @@ vi.mock('@/utils/var', async (importOriginal) => {
}
})
-const mockUseGlobalPublicStore = vi.mocked(useGlobalPublicStore)
const mockUseGetLanguage = vi.mocked(useGetLanguage)
const mockUseLocale = vi.mocked(useLocale)
const mockUseTheme = vi.mocked(useTheme)
@@ -106,15 +101,9 @@ const createTriggerProvider = (overrides: Partial<TriggerWithProvider> = {}): Tr
...overrides,
})
-const createSystemFeatures = (enableMarketplace: boolean) => ({
- ...defaultSystemFeatures,
- enable_marketplace: enableMarketplace,
-})
-
-const createGlobalPublicStoreState = (enableMarketplace: boolean) => ({
- systemFeatures: createSystemFeatures(enableMarketplace),
- setSystemFeatures: vi.fn(),
-})
+let enableMarketplaceForRender = false
+const render = (ui: ReactElement) =>
+ renderWithSystemFeatures(ui, { systemFeatures: { enable_marketplace: enableMarketplaceForRender } })
const createMarketplacePluginsMock = (
overrides: Partial<UseMarketplacePluginsReturn> = {},
@@ -179,7 +168,7 @@ const createAvailableNodesMetaData = (): ReturnType<typeof useAvailableNodesMeta
describe('AllStartBlocks', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockUseGlobalPublicStore.mockImplementation(selector => selector(createGlobalPublicStoreState(false)))
+ enableMarketplaceForRender = false
mockUseGetLanguage.mockReturnValue('en_US')
mockUseLocale.mockReturnValue('en_US')
mockUseTheme.mockReturnValue({ theme: Theme.light } as ReturnType<typeof useTheme>)
@@ -226,7 +215,7 @@ describe('AllStartBlocks', () => {
})
it('should show marketplace footer when marketplace is enabled without filters', async () => {
- mockUseGlobalPublicStore.mockImplementation(selector => selector(createGlobalPublicStoreState(true)))
+ enableMarketplaceForRender = true
render(
<AllStartBlocks
@@ -244,7 +233,7 @@ describe('AllStartBlocks', () => {
describe('Filtered Empty State', () => {
it('should query marketplace and show the no-results state when filters have no matches', async () => {
const queryPluginsWithDebounced = vi.fn()
- mockUseGlobalPublicStore.mockImplementation(selector => selector(createGlobalPublicStoreState(true)))
+ enableMarketplaceForRender = true
mockUseMarketplacePlugins.mockReturnValue(createMarketplacePluginsMock({
queryPluginsWithDebounced,
}))
diff --git a/web/app/components/workflow/block-selector/__tests__/all-tools.spec.tsx b/web/app/components/workflow/block-selector/__tests__/all-tools.spec.tsx
index 64f012fae33..9c7caeaa068 100644
--- a/web/app/components/workflow/block-selector/__tests__/all-tools.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/all-tools.spec.tsx
@@ -1,16 +1,13 @@
-import { render, screen, waitFor } from '@testing-library/react'
+import type { ReactElement } from 'react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/hooks'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useGetLanguage } from '@/context/i18n'
import useTheme from '@/hooks/use-theme'
import { Theme } from '@/types/app'
import AllTools from '../all-tools'
-import { createGlobalPublicStoreState, createToolProvider } from './factories'
-
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
+import { createToolProvider } from './factories'
vi.mock('@/context/i18n', () => ({
useGetLanguage: vi.fn(),
@@ -36,10 +33,12 @@ vi.mock('@/utils/var', async importOriginal => ({
}))
const mockUseMarketplacePlugins = vi.mocked(useMarketplacePlugins)
-const mockUseGlobalPublicStore = vi.mocked(useGlobalPublicStore)
const mockUseGetLanguage = vi.mocked(useGetLanguage)
const mockUseTheme = vi.mocked(useTheme)
+const render = (ui: ReactElement, enableMarketplace = false) =>
+ renderWithSystemFeatures(ui, { systemFeatures: { enable_marketplace: enableMarketplace } })
+
const createMarketplacePluginsMock = () => ({
plugins: [],
total: 0,
@@ -57,7 +56,6 @@ const createMarketplacePluginsMock = () => ({
describe('AllTools', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockUseGlobalPublicStore.mockImplementation(selector => selector(createGlobalPublicStoreState(false)))
mockUseGetLanguage.mockReturnValue('en_US')
mockUseTheme.mockReturnValue({ theme: Theme.light } as ReturnType<typeof useTheme>)
mockUseMarketplacePlugins.mockReturnValue(createMarketplacePluginsMock())
diff --git a/web/app/components/workflow/block-selector/__tests__/data-sources.spec.tsx b/web/app/components/workflow/block-selector/__tests__/data-sources.spec.tsx
index 64bcd514c6c..0d242dbf78f 100644
--- a/web/app/components/workflow/block-selector/__tests__/data-sources.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/data-sources.spec.tsx
@@ -1,21 +1,17 @@
+import type { ReactElement } from 'react'
import type { ToolWithProvider } from '../../types'
-import { render, screen, waitFor } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/hooks'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { CollectionType } from '@/app/components/tools/types'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useGetLanguage } from '@/context/i18n'
import useTheme from '@/hooks/use-theme'
import { Theme } from '@/types/app'
-import { defaultSystemFeatures } from '@/types/feature'
import { BlockEnum } from '../../types'
import DataSources from '../data-sources'
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
vi.mock('@/context/i18n', () => ({
useGetLanguage: vi.fn(),
}))
@@ -28,11 +24,14 @@ vi.mock('@/app/components/plugins/marketplace/hooks', () => ({
useMarketplacePlugins: vi.fn(),
}))
-const mockUseGlobalPublicStore = vi.mocked(useGlobalPublicStore)
const mockUseGetLanguage = vi.mocked(useGetLanguage)
const mockUseTheme = vi.mocked(useTheme)
const mockUseMarketplacePlugins = vi.mocked(useMarketplacePlugins)
+let enableMarketplaceForRender = false
+const render = (ui: ReactElement) =>
+ renderWithSystemFeatures(ui, { systemFeatures: { enable_marketplace: enableMarketplaceForRender } })
+
type UseMarketplacePluginsReturn = ReturnType<typeof useMarketplacePlugins>
const createToolProvider = (overrides: Partial<ToolWithProvider> = {}): ToolWithProvider => ({
@@ -63,16 +62,6 @@ const createToolProvider = (overrides: Partial<ToolWithProvider> = {}): ToolWith
...overrides,
})
-const createSystemFeatures = (enableMarketplace: boolean) => ({
- ...defaultSystemFeatures,
- enable_marketplace: enableMarketplace,
-})
-
-const createGlobalPublicStoreState = (enableMarketplace: boolean) => ({
- systemFeatures: createSystemFeatures(enableMarketplace),
- setSystemFeatures: vi.fn(),
-})
-
const createMarketplacePluginsMock = (
overrides: Partial<UseMarketplacePluginsReturn> = {},
): UseMarketplacePluginsReturn => ({
@@ -93,7 +82,7 @@ const createMarketplacePluginsMock = (
describe('DataSources', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockUseGlobalPublicStore.mockImplementation(selector => selector(createGlobalPublicStoreState(false)))
+ enableMarketplaceForRender = false
mockUseGetLanguage.mockReturnValue('en_US')
mockUseTheme.mockReturnValue({ theme: Theme.light } as ReturnType<typeof useTheme>)
mockUseMarketplacePlugins.mockReturnValue(createMarketplacePluginsMock())
@@ -162,7 +151,7 @@ describe('DataSources', () => {
describe('Marketplace Search', () => {
it('should query marketplace plugins for datasource search results', async () => {
const queryPluginsWithDebounced = vi.fn()
- mockUseGlobalPublicStore.mockImplementation(selector => selector(createGlobalPublicStoreState(true)))
+ enableMarketplaceForRender = true
mockUseMarketplacePlugins.mockReturnValue(createMarketplacePluginsMock({
queryPluginsWithDebounced,
}))
diff --git a/web/app/components/workflow/block-selector/__tests__/factories.ts b/web/app/components/workflow/block-selector/__tests__/factories.ts
index b7d82f7cb3b..dfb7c36aea5 100644
--- a/web/app/components/workflow/block-selector/__tests__/factories.ts
+++ b/web/app/components/workflow/block-selector/__tests__/factories.ts
@@ -3,7 +3,6 @@ import type { Plugin } from '@/app/components/plugins/types'
import type { Tool } from '@/app/components/tools/types'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { CollectionType } from '@/app/components/tools/types'
-import { defaultSystemFeatures } from '@/types/feature'
export const createTool = (
name: string,
@@ -91,11 +90,3 @@ export const createPlugin = (overrides: Partial<Plugin> = {}): Plugin => ({
from: 'github',
...overrides,
})
-
-export const createGlobalPublicStoreState = (enableMarketplace: boolean) => ({
- systemFeatures: {
- ...defaultSystemFeatures,
- enable_marketplace: enableMarketplace,
- },
- setSystemFeatures: vi.fn(),
-})
diff --git a/web/app/components/workflow/block-selector/__tests__/index.spec.tsx b/web/app/components/workflow/block-selector/__tests__/index.spec.tsx
index 735a831c106..d426b43cfdc 100644
--- a/web/app/components/workflow/block-selector/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/index.spec.tsx
@@ -23,12 +23,6 @@ vi.mock('@/service/use-tools', () => ({
useInvalidateAllBuiltInTools: () => vi.fn(),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { enable_marketplace: boolean } }) => unknown) => selector({
- systemFeatures: { enable_marketplace: false },
- }),
-}))
-
const createBlock = (type: BlockEnum, title: string): NodeDefault => ({
metaData: {
type,
diff --git a/web/app/components/workflow/block-selector/__tests__/main.spec.tsx b/web/app/components/workflow/block-selector/__tests__/main.spec.tsx
index 1deb6ce84c7..2cb0d3e98fb 100644
--- a/web/app/components/workflow/block-selector/__tests__/main.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/main.spec.tsx
@@ -14,12 +14,6 @@ vi.mock('reactflow', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { enable_marketplace: boolean } }) => unknown) => selector({
- systemFeatures: { enable_marketplace: false },
- }),
-}))
-
vi.mock('@/service/use-plugins', () => ({
useFeaturedToolsRecommendations: () => ({
plugins: [],
diff --git a/web/app/components/workflow/block-selector/__tests__/tabs.spec.tsx b/web/app/components/workflow/block-selector/__tests__/tabs.spec.tsx
index 3ee21f9999c..3002cafa0aa 100644
--- a/web/app/components/workflow/block-selector/__tests__/tabs.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/tabs.spec.tsx
@@ -1,9 +1,13 @@
-import { fireEvent, render, screen } from '@testing-library/react'
+import { fireEvent, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import Tabs from '../tabs'
import { TabsEnum } from '../types'
+const render = (ui: React.ReactElement) =>
+ renderWithSystemFeatures(ui, { systemFeatures: { enable_marketplace: true } })
+
const {
mockSetState,
mockInvalidateBuiltInTools,
@@ -34,12 +38,6 @@ vi.mock('@/app/components/base/tooltip', () => ({
),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { enable_marketplace: boolean } }) => unknown) => selector({
- systemFeatures: { enable_marketplace: true },
- }),
-}))
-
vi.mock('@/service/use-plugins', () => ({
useFeaturedToolsRecommendations: () => ({
plugins: [],
diff --git a/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsx b/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsx
index 1a2f7a4c936..9c55d174fd6 100644
--- a/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsx
@@ -2,14 +2,13 @@ import type { ToolWithProvider } from '../../types'
import type { ToolValue } from '../types'
import type { Plugin } from '@/app/components/plugins/types'
import type { Tool } from '@/app/components/tools/types'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useTags } from '@/app/components/plugins/hooks'
import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/hooks'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { CollectionType } from '@/app/components/tools/types'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useGetLanguage } from '@/context/i18n'
import useTheme from '@/hooks/use-theme'
import { createCustomCollection } from '@/service/tools'
@@ -25,11 +24,9 @@ import {
useInvalidateAllWorkflowTools,
} from '@/service/use-tools'
import { Theme } from '@/types/app'
-import { defaultSystemFeatures } from '@/types/feature'
import ToolPicker from '../tool-picker'
const mockNotify = vi.fn()
-const mockSetSystemFeatures = vi.fn()
const mockInvalidateBuiltInTools = vi.fn()
const mockInvalidateCustomTools = vi.fn()
const mockInvalidateWorkflowTools = vi.fn()
@@ -39,7 +36,6 @@ const mockInstallPackageFromMarketPlace = vi.fn()
const mockCheckInstalled = vi.fn()
const mockRefreshPluginList = vi.fn()
-const mockUseGlobalPublicStore = vi.mocked(useGlobalPublicStore)
const mockUseGetLanguage = vi.mocked(useGetLanguage)
const mockUseTheme = vi.mocked(useTheme)
const mockUseTags = vi.mocked(useTags)
@@ -54,10 +50,6 @@ const mockUseInvalidateAllWorkflowTools = vi.mocked(useInvalidateAllWorkflowTool
const mockUseInvalidateAllMCPTools = vi.mocked(useInvalidateAllMCPTools)
const mockUseFeaturedToolsRecommendations = vi.mocked(useFeaturedToolsRecommendations)
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
vi.mock('@/context/i18n', () => ({
useGetLanguage: vi.fn(),
}))
@@ -313,27 +305,18 @@ const mcpTools = [
]
const renderToolPicker = (props: Partial<React.ComponentProps<typeof ToolPicker>> = {}) => {
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
- })
-
- return render(
- <QueryClientProvider client={queryClient}>
- <ToolPicker
- disabled={false}
- trigger={<button type="button">open-picker</button>}
- isShow={false}
- onShowChange={vi.fn()}
- onSelect={vi.fn()}
- onSelectMultiple={vi.fn()}
- selectedTools={[createToolValue()]}
- {...props}
- />
- </QueryClientProvider>,
+ return renderWithSystemFeatures(
+ <ToolPicker
+ disabled={false}
+ trigger={<button type="button">open-picker</button>}
+ isShow={false}
+ onShowChange={vi.fn()}
+ onSelect={vi.fn()}
+ onSelectMultiple={vi.fn()}
+ selectedTools={[createToolValue()]}
+ {...props}
+ />,
+ { systemFeatures: { enable_marketplace: true } },
)
}
@@ -341,13 +324,6 @@ describe('ToolPicker', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockUseGlobalPublicStore.mockImplementation(selector => selector({
- systemFeatures: {
- ...defaultSystemFeatures,
- enable_marketplace: true,
- },
- setSystemFeatures: mockSetSystemFeatures,
- }))
mockUseGetLanguage.mockReturnValue('en_US')
mockUseTheme.mockReturnValue({ theme: Theme.light } as ReturnType<typeof useTheme>)
mockUseTags.mockReturnValue({
diff --git a/web/app/components/workflow/block-selector/all-start-blocks.tsx b/web/app/components/workflow/block-selector/all-start-blocks.tsx
index 72a98bed008..b7f9ee7bbbf 100644
--- a/web/app/components/workflow/block-selector/all-start-blocks.tsx
+++ b/web/app/components/workflow/block-selector/all-start-blocks.tsx
@@ -8,6 +8,7 @@ import type { TriggerDefaultValue, TriggerWithProvider } from './types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { RiArrowRightUpLine } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import {
useCallback,
useEffect,
@@ -18,8 +19,8 @@ import {
import { useTranslation } from 'react-i18next'
import Divider from '@/app/components/base/divider'
import { SearchMenu } from '@/app/components/base/icons/src/vender/line/general'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import Link from '@/next/link'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useFeaturedTriggersRecommendations } from '@/service/use-plugins'
import { useAllTriggerPlugins, useInvalidateAllTriggerPlugins } from '@/service/use-triggers'
import { getMarketplaceUrl } from '@/utils/var'
@@ -54,7 +55,10 @@ const AllStartBlocks = ({
const { t } = useTranslation()
const [hasStartBlocksContent, setHasStartBlocksContent] = useState(false)
const [hasPluginContent, setHasPluginContent] = useState(false)
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const pluginRef = useRef<ListRef>(null)
const wrapElemRef = useRef<HTMLDivElement>(null)
diff --git a/web/app/components/workflow/block-selector/all-tools.tsx b/web/app/components/workflow/block-selector/all-tools.tsx
index 2483b92f90b..72389ec3765 100644
--- a/web/app/components/workflow/block-selector/all-tools.tsx
+++ b/web/app/components/workflow/block-selector/all-tools.tsx
@@ -14,14 +14,15 @@ import type { OnSelectBlock } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { RiArrowRightUpLine } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Divider from '@/app/components/base/divider'
import { SearchMenu } from '@/app/components/base/icons/src/vender/line/general'
import PluginList from '@/app/components/workflow/block-selector/market-place-plugin/list'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useGetLanguage } from '@/context/i18n'
import Link from '@/next/link'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { getMarketplaceUrl } from '@/utils/var'
import { useMarketplacePlugins } from '../../plugins/marketplace/hooks'
import { PluginCategoryEnum } from '../../plugins/types'
@@ -167,7 +168,10 @@ const AllTools = ({
plugins: notInstalledPlugins = [],
} = useMarketplacePlugins()
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
useEffect(() => {
if (!enable_marketplace)
diff --git a/web/app/components/workflow/block-selector/data-sources.tsx b/web/app/components/workflow/block-selector/data-sources.tsx
index 447442818a8..1ee2bf9b9bd 100644
--- a/web/app/components/workflow/block-selector/data-sources.tsx
+++ b/web/app/components/workflow/block-selector/data-sources.tsx
@@ -5,6 +5,7 @@ import type {
import type { DataSourceDefaultValue, ToolDefaultValue } from './types'
import type { ListRef } from '@/app/components/workflow/block-selector/market-place-plugin/list'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import {
useCallback,
useEffect,
@@ -12,8 +13,8 @@ import {
useRef,
} from 'react'
import PluginList from '@/app/components/workflow/block-selector/market-place-plugin/list'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useGetLanguage } from '@/context/i18n'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useMarketplacePlugins } from '../../plugins/marketplace/hooks'
import { PluginCategoryEnum } from '../../plugins/types'
import { BlockEnum } from '../types'
@@ -76,7 +77,10 @@ const DataSources = ({
onSelect(BlockEnum.DataSource, toolDefaultValue && defaultValue)
}, [onSelect])
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const {
queryPluginsWithDebounced: fetchPlugins,
diff --git a/web/app/components/workflow/block-selector/tabs.tsx b/web/app/components/workflow/block-selector/tabs.tsx
index 5605908b715..48af942df7e 100644
--- a/web/app/components/workflow/block-selector/tabs.tsx
+++ b/web/app/components/workflow/block-selector/tabs.tsx
@@ -6,10 +6,11 @@ import type {
ToolWithProvider,
} from '../types'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { memo, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import Tooltip from '@/app/components/base/tooltip'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useFeaturedToolsRecommendations } from '@/service/use-plugins'
import { useAllBuiltInTools, useAllCustomTools, useAllMCPTools, useAllWorkflowTools, useInvalidateAllBuiltInTools } from '@/service/use-tools'
import { basePath } from '@/utils/var'
@@ -180,7 +181,10 @@ const Tabs: FC<TabsProps> = ({
const { data: workflowTools } = useAllWorkflowTools()
const { data: mcpTools } = useAllMCPTools()
const invalidateBuiltInTools = useInvalidateAllBuiltInTools()
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const workflowStore = useWorkflowStore()
const inRAGPipeline = dataSources.length > 0
const {
diff --git a/web/app/components/workflow/block-selector/tool-picker.tsx b/web/app/components/workflow/block-selector/tool-picker.tsx
index 7ba93798e26..e7e948a54de 100644
--- a/web/app/components/workflow/block-selector/tool-picker.tsx
+++ b/web/app/components/workflow/block-selector/tool-picker.tsx
@@ -9,6 +9,7 @@ import type { CustomCollectionBackend } from '@/app/components/tools/types'
import type { BlockEnum, OnSelectBlock } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import { toast } from '@langgenius/dify-ui/toast'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useBoolean } from 'ahooks'
import * as React from 'react'
import { useMemo, useState } from 'react'
@@ -21,7 +22,7 @@ import {
import SearchBox from '@/app/components/plugins/marketplace/search-box'
import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'
import AllTools from '@/app/components/workflow/block-selector/all-tools'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import {
createCustomCollection,
} from '@/service/tools'
@@ -70,7 +71,10 @@ const ToolPicker: FC<Props> = ({
const [searchText, setSearchText] = useState('')
const [tags, setTags] = useState<string[]>([])
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const { data: buildInTools } = useAllBuiltInTools()
const { data: customTools } = useAllCustomTools()
const invalidateCustomTools = useInvalidateAllCustomTools()
diff --git a/web/app/components/workflow/collaboration/hooks/__tests__/use-collaboration.spec.ts b/web/app/components/workflow/collaboration/hooks/__tests__/use-collaboration.spec.ts
index 0f8a9e2c9ad..7c063ab2cf1 100644
--- a/web/app/components/workflow/collaboration/hooks/__tests__/use-collaboration.spec.ts
+++ b/web/app/components/workflow/collaboration/hooks/__tests__/use-collaboration.spec.ts
@@ -1,5 +1,6 @@
import type { CursorPosition, NodePanelPresenceMap, OnlineUser } from '../../types/collaboration'
-import { renderHook, waitFor } from '@testing-library/react'
+import { waitFor } from '@testing-library/react'
+import { renderHookWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useCollaboration } from '../use-collaboration'
type HookReactFlowStore = NonNullable<Parameters<typeof useCollaboration>[1]>
@@ -29,11 +30,6 @@ const mockStartTracking = vi.hoisted(() => vi.fn())
const mockStopTracking = vi.hoisted(() => vi.fn())
const cursorServiceInstances: Array<{ startTracking: typeof mockStartTracking, stopTracking: typeof mockStopTracking }> = []
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { enable_collaboration_mode: boolean } }) => boolean) =>
- selector({ systemFeatures: { enable_collaboration_mode: isCollaborationEnabled } }),
-}))
-
vi.mock('../../core/collaboration-manager', () => ({
collaborationManager: {
connect: (...args: unknown[]) => mockConnect(...args),
@@ -92,7 +88,9 @@ describe('useCollaboration', () => {
const reactFlowStore: HookReactFlowStore = {
getState: vi.fn(),
}
- const { result, unmount } = renderHook(() => useCollaboration('app-1', reactFlowStore))
+ const { result, unmount } = renderHookWithSystemFeatures(() => useCollaboration('app-1', reactFlowStore), {
+ systemFeatures: { enable_collaboration_mode: isCollaborationEnabled },
+ })
await waitFor(() => {
expect(mockConnect).toHaveBeenCalledWith('app-1', reactFlowStore)
@@ -138,7 +136,9 @@ describe('useCollaboration', () => {
it('does not connect or start cursor tracking when collaboration is disabled', async () => {
isCollaborationEnabled = false
- const { result } = renderHook(() => useCollaboration('app-1'))
+ const { result } = renderHookWithSystemFeatures(() => useCollaboration('app-1'), {
+ systemFeatures: { enable_collaboration_mode: isCollaborationEnabled },
+ })
await waitFor(() => {
expect(mockConnect).not.toHaveBeenCalled()
diff --git a/web/app/components/workflow/collaboration/hooks/use-collaboration.ts b/web/app/components/workflow/collaboration/hooks/use-collaboration.ts
index b24d9faea8b..0030ffb77c6 100644
--- a/web/app/components/workflow/collaboration/hooks/use-collaboration.ts
+++ b/web/app/components/workflow/collaboration/hooks/use-collaboration.ts
@@ -5,8 +5,9 @@ import type {
NodePanelPresenceMap,
OnlineUser,
} from '../types/collaboration'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { collaborationManager } from '../core/collaboration-manager'
import { CursorService } from '../services/cursor-service'
@@ -33,7 +34,10 @@ export function useCollaboration(appId: string, reactFlowStore?: ReactFlowStore)
const cursorServiceRef = useRef<CursorService | null>(null)
const lastDisconnectReasonRef = useRef<string | null>(null)
- const isCollaborationEnabled = useGlobalPublicStore(s => s.systemFeatures.enable_collaboration_mode)
+ const { data: isCollaborationEnabled } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_collaboration_mode,
+ })
useEffect(() => {
if (!appId || !isCollaborationEnabled) {
diff --git a/web/app/components/workflow/hooks/__tests__/use-leader-restore.spec.ts b/web/app/components/workflow/hooks/__tests__/use-leader-restore.spec.ts
index a050994f4c4..b0fb43f7687 100644
--- a/web/app/components/workflow/hooks/__tests__/use-leader-restore.spec.ts
+++ b/web/app/components/workflow/hooks/__tests__/use-leader-restore.spec.ts
@@ -2,6 +2,7 @@ import type { RestoreIntentData, RestoreRequestData } from '../../collaboration/
import type { SyncDraftCallback } from '../../hooks-store/store'
import type { Edge, Node } from '../../types'
import { act, renderHook } from '@testing-library/react'
+import { renderHookWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { ChatVarType } from '../../panel/chat-variable-panel/type'
import { useLeaderRestore, useLeaderRestoreListener } from '../use-leader-restore'
@@ -72,11 +73,6 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
},
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { enable_collaboration_mode: boolean } }) => boolean) =>
- selector({ systemFeatures: { enable_collaboration_mode: isCollaborationEnabled } }),
-}))
-
vi.mock('../../store', () => ({
useWorkflowStore: () => ({
getState: () => ({
@@ -155,7 +151,9 @@ describe('useLeaderRestore', () => {
const onSuccess = vi.fn()
const onSettled = vi.fn()
- const { result } = renderHook(() => useLeaderRestore())
+ const { result } = renderHookWithSystemFeatures(() => useLeaderRestore(), {
+ systemFeatures: { enable_collaboration_mode: isCollaborationEnabled },
+ })
await act(async () => {
result.current.requestRestore(restoreData, { onSuccess, onSettled })
@@ -186,7 +184,9 @@ describe('useLeaderRestore', () => {
const onError = vi.fn()
const onSettled = vi.fn()
- const { result } = renderHook(() => useLeaderRestore())
+ const { result } = renderHookWithSystemFeatures(() => useLeaderRestore(), {
+ systemFeatures: { enable_collaboration_mode: isCollaborationEnabled },
+ })
act(() => {
result.current.requestRestore(restoreData, { onSuccess, onError, onSettled })
diff --git a/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts b/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts
index 5745603a5ea..b2edfa5234a 100644
--- a/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts
+++ b/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts
@@ -1,5 +1,6 @@
import type { WorkflowCommentDetail, WorkflowCommentList } from '@/service/workflow-comment'
import { act, waitFor } from '@testing-library/react'
+import { createTestQueryClient, seedSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { renderWorkflowHook } from '../../__tests__/workflow-test-env'
import { ControlMode } from '../../types'
import { useWorkflowComment } from '../use-workflow-comment'
@@ -51,14 +52,6 @@ vi.mock('@/context/app-context', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { enable_collaboration_mode: boolean } }) => unknown) => selector({
- systemFeatures: {
- enable_collaboration_mode: globalFeatureState.enableCollaboration,
- },
- }),
-}))
-
vi.mock('@/service/workflow-comment', () => ({
createWorkflowComment: (...args: unknown[]) => mockCreateWorkflowComment(...args),
createWorkflowCommentReply: (...args: unknown[]) => mockCreateWorkflowCommentReply(...args),
@@ -120,6 +113,14 @@ const baseCommentDetail = (): WorkflowCommentDetail => ({
replies: [],
})
+const createSeededQueryClient = () => {
+ const queryClient = createTestQueryClient()
+ seedSystemFeatures(queryClient, {
+ enable_collaboration_mode: globalFeatureState.enableCollaboration,
+ })
+ return queryClient
+}
+
describe('useWorkflowComment', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -139,7 +140,9 @@ describe('useWorkflowComment', () => {
const comment = baseComment()
mockFetchWorkflowComments.mockResolvedValue([comment])
- const { store } = renderWorkflowHook(() => useWorkflowComment())
+ const { store } = renderWorkflowHook(() => useWorkflowComment(), {
+ queryClient: createSeededQueryClient(),
+ })
await waitFor(() => {
expect(mockFetchWorkflowComments).toHaveBeenCalledWith('app-1')
@@ -152,7 +155,9 @@ describe('useWorkflowComment', () => {
it('does not load comment list when collaboration is disabled', async () => {
globalFeatureState.enableCollaboration = false
- renderWorkflowHook(() => useWorkflowComment())
+ renderWorkflowHook(() => useWorkflowComment(), {
+ queryClient: createSeededQueryClient(),
+ })
await Promise.resolve()
@@ -161,6 +166,7 @@ describe('useWorkflowComment', () => {
it('creates a comment, updates local cache, and emits collaboration sync', async () => {
const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [],
pendingComment: { pageX: 100, pageY: 200, elementX: 10, elementY: 20 },
@@ -214,6 +220,7 @@ describe('useWorkflowComment', () => {
mockUpdateWorkflowComment.mockRejectedValue(new Error('update failed'))
const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [comment],
activeCommentId: comment.id,
@@ -254,6 +261,7 @@ describe('useWorkflowComment', () => {
mockFetchWorkflowComment.mockResolvedValue({ data: detail })
const { unmount } = renderWorkflowHook(() => useWorkflowComment(), {
+ queryClient: createSeededQueryClient(),
initialStoreState: {
activeCommentId: comment.id,
},
@@ -295,6 +303,7 @@ describe('useWorkflowComment', () => {
})
const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [commentA, commentB],
commentDetailCache: {
@@ -363,6 +372,7 @@ describe('useWorkflowComment', () => {
})
const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [commentA, commentB],
activeCommentId: commentA.id,
diff --git a/web/app/components/workflow/hooks/use-leader-restore.ts b/web/app/components/workflow/hooks/use-leader-restore.ts
index da0036a4ea3..9083767f40a 100644
--- a/web/app/components/workflow/hooks/use-leader-restore.ts
+++ b/web/app/components/workflow/hooks/use-leader-restore.ts
@@ -1,12 +1,13 @@
import type { RestoreCompleteData, RestoreIntentData, RestoreRequestData } from '../collaboration/types/collaboration'
import type { SyncCallback } from './use-nodes-sync-draft'
import { toast } from '@langgenius/dify-ui/toast'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useReactFlow } from 'reactflow'
import { useStore as useAppStore } from '@/app/components/app/store'
import { useFeaturesStore } from '@/app/components/base/features/hooks'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { collaborationManager } from '../collaboration/core/collaboration-manager'
import { useWorkflowStore } from '../store'
import { useNodesSyncDraft } from './use-nodes-sync-draft'
@@ -115,7 +116,10 @@ export const useLeaderRestore = () => {
versionId: string
callbacks: RestoreCallbacks | null
} | null>(null)
- const isCollaborationEnabled = useGlobalPublicStore(s => s.systemFeatures.enable_collaboration_mode)
+ const { data: isCollaborationEnabled } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_collaboration_mode,
+ })
const requestRestore = useCallback((data: RestoreRequestData, callbacks?: RestoreCallbacks) => {
if (!isCollaborationEnabled || !collaborationManager.isConnected() || collaborationManager.getIsLeader()) {
diff --git a/web/app/components/workflow/hooks/use-nodes-interactions.ts b/web/app/components/workflow/hooks/use-nodes-interactions.ts
index a29c88e9cb0..f0e23586eb0 100644
--- a/web/app/components/workflow/hooks/use-nodes-interactions.ts
+++ b/web/app/components/workflow/hooks/use-nodes-interactions.ts
@@ -14,6 +14,7 @@ import type { VariableAssignerNodeType } from '../nodes/variable-assigner/types'
import type { Edge, Node, OnNodeAdd } from '../types'
import type { RAGPipelineVariables } from '@/models/pipeline'
import { toast } from '@langgenius/dify-ui/toast'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { produce } from 'immer'
import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -22,7 +23,7 @@ import {
getOutgoers,
useReactFlow,
} from 'reactflow'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { collaborationManager } from '../collaboration/core/collaboration-manager'
import {
CUSTOM_EDGE,
@@ -138,7 +139,10 @@ const getUniquePastedNodeTitle = (
export const useNodesInteractions = () => {
const { t } = useTranslation()
- const appDslVersion = useGlobalPublicStore(s => s.systemFeatures.app_dsl_version)
+ const { data: appDslVersion } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.app_dsl_version,
+ })
const collaborativeWorkflow = useCollaborativeWorkflow()
const workflowStore = useWorkflowStore()
const reactflow = useReactFlow()
diff --git a/web/app/components/workflow/hooks/use-panel-interactions.ts b/web/app/components/workflow/hooks/use-panel-interactions.ts
index 37120068d49..3b7a2158a12 100644
--- a/web/app/components/workflow/hooks/use-panel-interactions.ts
+++ b/web/app/components/workflow/hooks/use-panel-interactions.ts
@@ -1,12 +1,16 @@
import type { MouseEvent } from 'react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback } from 'react'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useWorkflowStore } from '../store'
import { readWorkflowClipboard } from '../utils'
export const usePanelInteractions = () => {
const workflowStore = useWorkflowStore()
- const appDslVersion = useGlobalPublicStore(s => s.systemFeatures.app_dsl_version)
+ const { data: appDslVersion } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.app_dsl_version,
+ })
const handlePaneContextMenu = useCallback((e: MouseEvent) => {
e.preventDefault()
diff --git a/web/app/components/workflow/hooks/use-workflow-comment.ts b/web/app/components/workflow/hooks/use-workflow-comment.ts
index 5b3f2e17b0a..cdd14ceef11 100644
--- a/web/app/components/workflow/hooks/use-workflow-comment.ts
+++ b/web/app/components/workflow/hooks/use-workflow-comment.ts
@@ -1,10 +1,11 @@
import type { UserProfile, WorkflowCommentDetail, WorkflowCommentList } from '@/service/workflow-comment'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback, useEffect, useRef } from 'react'
import { useReactFlow } from 'reactflow'
import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'
import { useAppContext } from '@/context/app-context'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useParams } from '@/next/navigation'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { createWorkflowComment, createWorkflowCommentReply, deleteWorkflowComment, deleteWorkflowCommentReply, fetchWorkflowComment, fetchWorkflowComments, resolveWorkflowComment, updateWorkflowComment, updateWorkflowCommentReply } from '@/service/workflow-comment'
import { useStore } from '../store'
import { ControlMode } from '../types'
@@ -50,7 +51,10 @@ export const useWorkflowComment = () => {
appId ? state.mentionableUsersCache[appId] ?? EMPTY_USERS : EMPTY_USERS
))
const { userProfile } = useAppContext()
- const isCollaborationEnabled = useGlobalPublicStore(s => s.systemFeatures.enable_collaboration_mode)
+ const { data: isCollaborationEnabled } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_collaboration_mode,
+ })
const commentDetailCacheRef = useRef<Record<string, WorkflowCommentDetail>>(commentDetailCache)
const activeCommentIdRef = useRef<string | null>(null)
diff --git a/web/app/components/workflow/hooks/use-workflow-panel-interactions.ts b/web/app/components/workflow/hooks/use-workflow-panel-interactions.ts
index 62628c533e3..e7ca512d343 100644
--- a/web/app/components/workflow/hooks/use-workflow-panel-interactions.ts
+++ b/web/app/components/workflow/hooks/use-workflow-panel-interactions.ts
@@ -1,5 +1,6 @@
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback } from 'react'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useStore, useWorkflowStore } from '../store'
import { ControlMode } from '../types'
import { useEdgesInteractionsWithoutSync } from './use-edges-interactions-without-sync'
@@ -30,7 +31,10 @@ export const useWorkflowMoveMode = () => {
const setControlMode = useStore(s => s.setControlMode)
const { getNodesReadOnly } = useNodesReadOnly()
const { handleSelectionCancel } = useSelectionInteractions()
- const isCommentModeAvailable = useGlobalPublicStore(s => s.systemFeatures.enable_collaboration_mode)
+ const { data: isCommentModeAvailable } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_collaboration_mode,
+ })
const handleModePointer = useCallback(() => {
if (getNodesReadOnly())
diff --git a/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx b/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx
index 489c69412a5..8e7c1609d16 100644
--- a/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx
+++ b/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx
@@ -5,6 +5,7 @@ import type { StrategyPluginDetail } from '@/app/components/plugins/types'
import type { ListProps, ListRef } from '@/app/components/workflow/block-selector/market-place-plugin/list'
import { cn } from '@langgenius/dify-ui/cn'
import { RiArrowDownSLine, RiErrorWarningFill } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { memo, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { PortalToFollowElem, PortalToFollowElemContent, PortalToFollowElemTrigger } from '@/app/components/base/portal-to-follow-elem'
@@ -16,8 +17,8 @@ import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/hook
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { CollectionType } from '@/app/components/tools/types'
import PluginList from '@/app/components/workflow/block-selector/market-place-plugin/list'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import Link from '@/next/link'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useStrategyProviders } from '@/service/use-strategy'
import Tools from '../../../block-selector/tools'
import ViewTypeSelect, { ViewType } from '../../../block-selector/view-type-select'
@@ -95,7 +96,10 @@ type AgentStrategySelectorProps = {
}
export const AgentStrategySelector = memo((props: AgentStrategySelectorProps) => {
- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: enable_marketplace } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_marketplace,
+ })
const { value, onChange } = props
const [open, setOpen] = useState(false)
diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/import-from-tool.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/import-from-tool.spec.tsx
index f1da87bed27..7e13b8ef345 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/import-from-tool.spec.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/__tests__/import-from-tool.spec.tsx
@@ -2,6 +2,7 @@ import type { ToolParameter } from '@/app/components/tools/types'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createSystemFeaturesWrapper } from '@/__tests__/utils/mock-system-features'
import { CollectionType } from '@/app/components/tools/types'
import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { createTool, createToolProvider } from '@/app/components/workflow/block-selector/__tests__/factories'
@@ -15,12 +16,6 @@ vi.mock('reactflow', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { enable_marketplace: boolean } }) => unknown) => selector({
- systemFeatures: { enable_marketplace: false },
- }),
-}))
-
vi.mock('@/service/use-plugins', () => ({
useFeaturedToolsRecommendations: () => ({
plugins: [],
@@ -65,6 +60,20 @@ const createToolParameter = (overrides: Partial<ToolParameter> = {}): ToolParame
...overrides,
})
+const renderImportFromTool = (ui: React.ReactElement) => {
+ const { wrapper: SystemFeaturesWrapper } = createSystemFeaturesWrapper({
+ systemFeatures: { enable_marketplace: false },
+ })
+ return renderWorkflowComponent(
+ <SystemFeaturesWrapper>{ui}</SystemFeaturesWrapper>,
+ {
+ hooksStoreProps: {
+ availableNodesMetaData: { nodes: [] },
+ },
+ },
+ )
+}
+
describe('parameter-extractor/extract-parameter/import-from-tool', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -97,14 +106,7 @@ describe('parameter-extractor/extract-parameter/import-from-tool', () => {
provider.tools[0]!.parameters = builtInParameters
mockToolCollections.builtIn = [provider]
- renderWorkflowComponent(
- <ImportFromTool onImport={handleImport} />,
- {
- hooksStoreProps: {
- availableNodesMetaData: { nodes: [] },
- },
- },
- )
+ renderImportFromTool(<ImportFromTool onImport={handleImport} />)
await user.click(screen.getByText('workflow.nodes.parameterExtractor.importFromTool'))
await user.click(await screen.findByText('Provider One'))
@@ -136,14 +138,7 @@ describe('parameter-extractor/extract-parameter/import-from-tool', () => {
provider.tools[0]!.parameters = workflowParameters
mockToolCollections.workflow = [provider]
- renderWorkflowComponent(
- <ImportFromTool onImport={handleImport} />,
- {
- hooksStoreProps: {
- availableNodesMetaData: { nodes: [] },
- },
- },
- )
+ renderImportFromTool(<ImportFromTool onImport={handleImport} />)
await user.click(screen.getByText('workflow.nodes.parameterExtractor.importFromTool'))
await user.click(await screen.findByText('Workflow Tool'))
diff --git a/web/app/components/workflow/nodes/tool/components/__tests__/input-var-list.spec.tsx b/web/app/components/workflow/nodes/tool/components/__tests__/input-var-list.spec.tsx
index 9d38d112e98..990153d3085 100644
--- a/web/app/components/workflow/nodes/tool/components/__tests__/input-var-list.spec.tsx
+++ b/web/app/components/workflow/nodes/tool/components/__tests__/input-var-list.spec.tsx
@@ -1,10 +1,11 @@
import type { ToolVarInputs } from '../../types'
import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { App } from '@/types/app'
-import { render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { createMockProviderContextValue } from '@/__mocks__/provider-context'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import {
ConfigurationMethodEnum,
FormTypeEnum,
@@ -211,14 +212,6 @@ vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference
),
}))
-vi.mock('@/context/global-public-context', () => ({
- useSystemFeaturesQuery: () => ({
- data: {
- trial_models: [],
- },
- }),
-}))
-
vi.mock('@/app/components/header/account-setting/model-provider-page/provider-added-card/use-trial-credits', () => ({
useTrialCredits: () => ({
isExhausted: false,
@@ -341,7 +334,7 @@ const renderInputVarList = (ui: React.ReactElement) => {
}] as ReturnType<typeof createMockProviderContextValue>['modelProviders'],
})
- return render(
+ return renderWithSystemFeatures(
<ProviderContext.Provider value={providerContextValue}>
{ui}
</ProviderContext.Provider>,
diff --git a/web/app/components/workflow/operator/__tests__/zoom-in-out.spec.tsx b/web/app/components/workflow/operator/__tests__/zoom-in-out.spec.tsx
index 8b0f12c7d6c..a58bdef727b 100644
--- a/web/app/components/workflow/operator/__tests__/zoom-in-out.spec.tsx
+++ b/web/app/components/workflow/operator/__tests__/zoom-in-out.spec.tsx
@@ -1,4 +1,5 @@
-import { fireEvent, render, screen, within } from '@testing-library/react'
+import { fireEvent, screen, within } from '@testing-library/react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import ZoomInOut from '../zoom-in-out'
const {
@@ -46,18 +47,15 @@ vi.mock('@/app/components/workflow/hooks', () => ({
}),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: (selector: (state: { systemFeatures: { enable_collaboration_mode: boolean } }) => unknown) => selector({
- systemFeatures: {
- enable_collaboration_mode: collaborationEnabled,
- },
- }),
-}))
-
vi.mock('../tip-popup', () => ({
default: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}))
+const renderZoomInOut = (ui: React.ReactElement = <ZoomInOut />) =>
+ renderWithSystemFeatures(ui, {
+ systemFeatures: { enable_collaboration_mode: collaborationEnabled },
+ })
+
const getZoomControls = () => {
const label = Array.from(document.querySelectorAll('button')).find((element) => {
return /^\d+%$/.test(element.textContent ?? '') && element.className.includes('w-[34px]')
@@ -89,7 +87,7 @@ describe('workflow zoom controls', () => {
})
it('zooms out and zooms in when the viewport is within the supported range', () => {
- render(<ZoomInOut />)
+ renderZoomInOut()
const { zoomOutTrigger, zoomInTrigger } = getZoomControls()
@@ -101,7 +99,7 @@ describe('workflow zoom controls', () => {
})
it('zooms to a preset value and syncs the draft', () => {
- render(<ZoomInOut />)
+ renderZoomInOut()
const menu = openZoomMenu()
fireEvent.click(menu.getByText('50%'))
@@ -114,7 +112,7 @@ describe('workflow zoom controls', () => {
['100%', 1],
['200%', 2],
])('zooms to %s and syncs the draft', (label, zoom) => {
- render(<ZoomInOut />)
+ renderZoomInOut()
const menu = openZoomMenu()
fireEvent.click(menu.getByText(label))
@@ -124,7 +122,7 @@ describe('workflow zoom controls', () => {
})
it('toggles collaboration options without syncing the draft', () => {
- render(
+ renderZoomInOut(
<ZoomInOut
onToggleMiniMap={mockToggleMiniMap}
onToggleUserComments={mockToggleUserComments}
@@ -147,7 +145,7 @@ describe('workflow zoom controls', () => {
})
it('keeps the show-user-comments action disabled in comment mode', () => {
- render(
+ renderZoomInOut(
<ZoomInOut
isCommentMode
onToggleUserComments={mockToggleUserComments}
@@ -162,7 +160,7 @@ describe('workflow zoom controls', () => {
it('does not open the menu when the workflow is read only', () => {
workflowReadOnly = true
- render(<ZoomInOut />)
+ renderZoomInOut()
fireEvent.click(getZoomControls().label)
@@ -171,7 +169,7 @@ describe('workflow zoom controls', () => {
it('blocks inline zooming out at the minimum viewport scale', () => {
mockViewport.zoom = 0.25
- render(<ZoomInOut />)
+ renderZoomInOut()
fireEvent.click(getZoomControls().zoomOutTrigger)
expect(mockZoomOut).not.toHaveBeenCalled()
@@ -179,7 +177,7 @@ describe('workflow zoom controls', () => {
it('blocks inline zooming in at the maximum viewport scale', () => {
mockViewport.zoom = 2
- render(<ZoomInOut />)
+ renderZoomInOut()
fireEvent.click(getZoomControls().zoomInTrigger)
expect(mockZoomIn).not.toHaveBeenCalled()
@@ -187,7 +185,7 @@ describe('workflow zoom controls', () => {
it('renders collaboration menu entries only when collaboration is enabled', () => {
collaborationEnabled = false
- render(<ZoomInOut />)
+ renderZoomInOut()
const menu = openZoomMenu()
expect(menu.getByText('workflow.operator.showMiniMap')).toBeInTheDocument()
diff --git a/web/app/components/workflow/operator/zoom-in-out.tsx b/web/app/components/workflow/operator/zoom-in-out.tsx
index 78b07af347f..d7f172d2d1b 100644
--- a/web/app/components/workflow/operator/zoom-in-out.tsx
+++ b/web/app/components/workflow/operator/zoom-in-out.tsx
@@ -7,6 +7,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
+import { useSuspenseQuery } from '@tanstack/react-query'
import {
Fragment,
memo,
@@ -17,7 +18,7 @@ import {
useReactFlow,
useViewport,
} from 'reactflow'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import {
useNodesSyncDraft,
useWorkflowReadOnly,
@@ -70,7 +71,10 @@ const ZoomInOut: FC<ZoomInOutProps> = ({
workflowReadOnly,
getWorkflowReadOnly,
} = useWorkflowReadOnly()
- const isCollaborationEnabled = useGlobalPublicStore(s => s.systemFeatures.enable_collaboration_mode)
+ const { data: isCollaborationEnabled } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: s => s.enable_collaboration_mode,
+ })
const zoomOptions = [
[
diff --git a/web/app/forgot-password/page.tsx b/web/app/forgot-password/page.tsx
index b2ac8d26402..3f8f17c98ed 100644
--- a/web/app/forgot-password/page.tsx
+++ b/web/app/forgot-password/page.tsx
@@ -1,10 +1,11 @@
'use client'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import ChangePasswordForm from '@/app/forgot-password/ChangePasswordForm'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import useDocumentTitle from '@/hooks/use-document-title'
import { useSearchParams } from '@/next/navigation'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import Header from '../signin/_header'
import ForgotPasswordForm from './ForgotPasswordForm'
@@ -12,7 +13,7 @@ const ForgotPassword = () => {
useDocumentTitle('')
const searchParams = useSearchParams()
const token = searchParams.get('token')
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
return (
<div className={cn('flex min-h-screen w-full justify-center bg-background-default-burn p-6')}>
diff --git a/web/app/install/installForm.spec.tsx b/web/app/install/installForm.spec.tsx
index 1286d023431..a9b8cc02beb 100644
--- a/web/app/install/installForm.spec.tsx
+++ b/web/app/install/installForm.spec.tsx
@@ -1,9 +1,13 @@
+import type { ReactElement } from 'react'
import type { InitValidateStatusResponse, SetupStatusResponse } from '@/models/common'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { fetchInitValidateStatus, fetchSetupStatus, login, setup } from '@/service/common'
import { encryptPassword } from '@/utils/encryption'
import InstallForm from './installForm'
+const render = (ui: ReactElement) => renderWithSystemFeatures(ui)
+
const mockPush = vi.fn()
const mockReplace = vi.fn()
@@ -18,14 +22,6 @@ vi.mock('@/service/common', () => ({
login: vi.fn(),
}))
-vi.mock('@/context/global-public-context', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@/context/global-public-context')>()
- return {
- ...actual,
- useIsSystemFeaturesPending: () => false,
- }
-})
-
const mockFetchSetupStatus = vi.mocked(fetchSetupStatus)
const mockFetchInitValidateStatus = vi.mocked(fetchInitValidateStatus)
const mockSetup = vi.mocked(setup)
diff --git a/web/app/install/page.tsx b/web/app/install/page.tsx
index b5d92a3298e..8d1f71f817d 100644
--- a/web/app/install/page.tsx
+++ b/web/app/install/page.tsx
@@ -1,12 +1,13 @@
'use client'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import Header from '../signin/_header'
import InstallForm from './installForm'
const Install = () => {
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
return (
<div className={cn('flex min-h-screen w-full justify-center bg-background-default-burn p-6')}>
<div className={cn('flex w-full shrink-0 flex-col rounded-2xl border border-effects-highlight bg-background-default-subtle')}>
diff --git a/web/app/layout.tsx b/web/app/layout.tsx
index be0c854f02b..009f2ca5849 100644
--- a/web/app/layout.tsx
+++ b/web/app/layout.tsx
@@ -4,7 +4,6 @@ import { TooltipProvider } from '@langgenius/dify-ui/tooltip'
import { Provider as JotaiProvider } from 'jotai/react'
import { ThemeProvider } from 'next-themes'
import { NuqsAdapter } from 'nuqs/adapters/next/app'
-import GlobalPublicStoreProvider from '@/context/global-public-context'
import { TanstackQueryInitializer } from '@/context/query-client'
import { getDatasetMap } from '@/env'
import { getLocaleOnServer } from '@/i18n-config/server'
@@ -70,11 +69,9 @@ const LocaleLayout = async ({
<I18nServerProvider>
<ToastHost timeout={5000} limit={3} />
<PartnerStackCookieRecorder />
- <GlobalPublicStoreProvider>
- <TooltipProvider delay={300} closeDelay={200}>
- {children}
- </TooltipProvider>
- </GlobalPublicStoreProvider>
+ <TooltipProvider delay={300} closeDelay={200}>
+ {children}
+ </TooltipProvider>
</I18nServerProvider>
</TanstackQueryInitializer>
</NuqsAdapter>
diff --git a/web/app/loading.tsx b/web/app/loading.tsx
new file mode 100644
index 00000000000..b108baaa978
--- /dev/null
+++ b/web/app/loading.tsx
@@ -0,0 +1,9 @@
+import Loading from '@/app/components/base/loading'
+
+export default function RootLoading() {
+ return (
+ <div className="flex h-screen w-screen items-center justify-center bg-background-body">
+ <Loading />
+ </div>
+ )
+}
diff --git a/web/app/reset-password/layout.tsx b/web/app/reset-password/layout.tsx
index e9909fe4386..e2691a397e7 100644
--- a/web/app/reset-password/layout.tsx
+++ b/web/app/reset-password/layout.tsx
@@ -1,11 +1,12 @@
'use client'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import Header from '../signin/_header'
export default function SignInLayout({ children }: any) {
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
return (
<>
<div className={cn('flex min-h-screen w-full justify-center bg-background-default-burn p-6')}>
diff --git a/web/app/signin/_header.tsx b/web/app/signin/_header.tsx
index 7ebff9f73c9..0b424d45c20 100644
--- a/web/app/signin/_header.tsx
+++ b/web/app/signin/_header.tsx
@@ -1,12 +1,13 @@
'use client'
import type { Locale } from '@/i18n-config'
+import { useSuspenseQuery } from '@tanstack/react-query'
import Divider from '@/app/components/base/divider'
import LocaleSigninSelect from '@/app/components/base/select/locale-signin'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useLocale } from '@/context/i18n'
import { setLocaleOnClient } from '@/i18n-config'
import { languages } from '@/i18n-config/language'
import dynamic from '@/next/dynamic'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
// Avoid rendering the logo and theme selector on the server
const DifyLogo = dynamic(() => import('@/app/components/base/logo/dify-logo'), {
@@ -20,7 +21,7 @@ const ThemeSelector = dynamic(() => import('@/app/components/base/theme-selector
const Header = () => {
const locale = useLocale()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
return (
<div className="flex w-full items-center justify-between p-6">
diff --git a/web/app/signin/invite-settings/page.tsx b/web/app/signin/invite-settings/page.tsx
index fe3dac71531..6f198b99cae 100644
--- a/web/app/signin/invite-settings/page.tsx
+++ b/web/app/signin/invite-settings/page.tsx
@@ -3,6 +3,7 @@ import type { Locale } from '@/i18n-config'
import { Button } from '@langgenius/dify-ui/button'
import { toast } from '@langgenius/dify-ui/toast'
import { RiAccountCircleLine } from '@remixicon/react'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { noop } from 'es-toolkit/function'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -10,19 +11,19 @@ import Input from '@/app/components/base/input'
import Loading from '@/app/components/base/loading'
import { SimpleSelect } from '@/app/components/base/select'
import { LICENSE_LINK } from '@/constants/link'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { setLocaleOnClient } from '@/i18n-config'
import { languages, LanguagesSupported } from '@/i18n-config/language'
import Link from '@/next/link'
import { useRouter, useSearchParams } from '@/next/navigation'
import { activateMember } from '@/service/common'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useInvitationCheck } from '@/service/use-common'
import { timezones } from '@/utils/timezone'
import { resolvePostLoginRedirect } from '../utils/post-login-redirect'
export default function InviteSettingsPage() {
const { t } = useTranslation()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const router = useRouter()
const searchParams = useSearchParams()
const token = decodeURIComponent(searchParams.get('invite_token') as string)
diff --git a/web/app/signin/layout.tsx b/web/app/signin/layout.tsx
index ed32727ae2c..a6537793c80 100644
--- a/web/app/signin/layout.tsx
+++ b/web/app/signin/layout.tsx
@@ -1,12 +1,13 @@
'use client'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import useDocumentTitle from '@/hooks/use-document-title'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import Header from './_header'
export default function SignInLayout({ children }: any) {
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
useDocumentTitle('')
return (
<>
diff --git a/web/app/signin/normal-form.tsx b/web/app/signin/normal-form.tsx
index 2ead90f068c..779aba5c9ca 100644
--- a/web/app/signin/normal-form.tsx
+++ b/web/app/signin/normal-form.tsx
@@ -1,15 +1,16 @@
import { cn } from '@langgenius/dify-ui/cn'
import { toast } from '@langgenius/dify-ui/toast'
import { RiContractLine, RiDoorLockLine, RiErrorWarningFill } from '@remixicon/react'
+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { IS_CE_EDITION } from '@/config'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import Link from '@/next/link'
import { useRouter, useSearchParams } from '@/next/navigation'
import { invitationCheck } from '@/service/common'
-import { useIsLogin } from '@/service/use-common'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
+import { isLegacyBase401, userProfileQueryOptions } from '@/service/use-common'
import { LicenseStatus } from '@/types/feature'
import Loading from '../components/base/loading'
import MailAndCodeAuth from './components/mail-and-code-auth'
@@ -23,14 +24,20 @@ const NormalForm = () => {
const { t } = useTranslation()
const router = useRouter()
const searchParams = useSearchParams()
- const { isLoading: isCheckLoading, data: loginData } = useIsLogin()
- const isLoggedIn = loginData?.logged_in
+ // Login probe: 401 stays as `error` (legitimate "not logged in" state on /signin),
+ // other errors throw to error.tsx. jumpTo same-pathname guard in service/base.ts
+ // prevents the redirect loop on 401.
+ const { isPending: isCheckLoading, data: userResp, error: probeError } = useQuery({
+ ...userProfileQueryOptions(),
+ throwOnError: err => !isLegacyBase401(err),
+ })
+ const isLoggedIn = !!userResp && !probeError
const message = decodeURIComponent(searchParams.get('message') || '')
const invite_token = decodeURIComponent(searchParams.get('invite_token') || '')
const [isInitCheckLoading, setInitCheckLoading] = useState(true)
const [isRedirecting, setIsRedirecting] = useState(false)
const isLoading = isCheckLoading || isInitCheckLoading || isRedirecting
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const [authType, updateAuthType] = useState<'code' | 'password'>('password')
const [showORLine, setShowORLine] = useState(false)
const [allMethodsAreDisabled, setAllMethodsAreDisabled] = useState(false)
diff --git a/web/app/signup/components/input-mail.spec.tsx b/web/app/signup/components/input-mail.spec.tsx
index e16c3815857..9afea73df7e 100644
--- a/web/app/signup/components/input-mail.spec.tsx
+++ b/web/app/signup/components/input-mail.spec.tsx
@@ -1,29 +1,14 @@
import type { MockedFunction } from 'vitest'
-import type { SystemFeatures } from '@/types/feature'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { renderWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
import { useLocale } from '@/context/i18n'
import { useSendMail } from '@/service/use-common'
-import { defaultSystemFeatures } from '@/types/feature'
import Form from './input-mail'
const mockSubmitMail = vi.fn()
const mockOnSuccess = vi.fn()
-type SystemFeaturesOverrides = Partial<Omit<SystemFeatures, 'branding'>> & {
- branding?: Partial<SystemFeatures['branding']>
-}
-
-const buildSystemFeatures = (overrides: SystemFeaturesOverrides = {}): SystemFeatures => ({
- ...defaultSystemFeatures,
- ...overrides,
- branding: {
- ...defaultSystemFeatures.branding,
- ...overrides.branding,
- },
-})
-
vi.mock('@/next/link', () => ({
default: ({ children, href, className, target, rel }: { children: React.ReactNode, href: string, className?: string, target?: string, rel?: string }) => (
<a href={href} className={className} target={target} rel={rel}>
@@ -32,10 +17,6 @@ vi.mock('@/next/link', () => ({
),
}))
-vi.mock('@/context/global-public-context', () => ({
- useGlobalPublicStore: vi.fn(),
-}))
-
vi.mock('@/context/i18n', () => ({
useLocale: vi.fn(),
}))
@@ -46,7 +27,6 @@ vi.mock('@/service/use-common', () => ({
type UseSendMailResult = ReturnType<typeof useSendMail>
-const mockUseGlobalPublicStore = useGlobalPublicStore as unknown as MockedFunction<typeof useGlobalPublicStore>
const mockUseLocale = useLocale as unknown as MockedFunction<typeof useLocale>
const mockUseSendMail = useSendMail as unknown as MockedFunction<typeof useSendMail>
@@ -57,17 +37,14 @@ const renderForm = ({
brandingEnabled?: boolean
isPending?: boolean
} = {}) => {
- mockUseGlobalPublicStore.mockReturnValue({
- systemFeatures: buildSystemFeatures({
- branding: { enabled: brandingEnabled },
- }),
- })
mockUseLocale.mockReturnValue('en-US')
mockUseSendMail.mockReturnValue({
mutateAsync: mockSubmitMail,
isPending,
} as unknown as UseSendMailResult)
- return render(<Form onSuccess={mockOnSuccess} />)
+ return renderWithSystemFeatures(<Form onSuccess={mockOnSuccess} />, {
+ systemFeatures: { branding: { enabled: brandingEnabled } },
+ })
}
describe('InputMail Form', () => {
diff --git a/web/app/signup/components/input-mail.tsx b/web/app/signup/components/input-mail.tsx
index f4c5214c11a..a0a09001d20 100644
--- a/web/app/signup/components/input-mail.tsx
+++ b/web/app/signup/components/input-mail.tsx
@@ -2,14 +2,15 @@
import type { MailSendResponse } from '@/service/use-common'
import { Button } from '@langgenius/dify-ui/button'
import { toast } from '@langgenius/dify-ui/toast'
+import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '@/app/components/base/input'
import Split from '@/app/signin/split'
import { emailRegex } from '@/config'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useLocale } from '@/context/i18n'
import Link from '@/next/link'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useSendMail } from '@/service/use-common'
type Props = {
@@ -21,7 +22,7 @@ export default function Form({
const { t } = useTranslation()
const [email, setEmail] = useState('')
const locale = useLocale()
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { mutateAsync: submitMail, isPending } = useSendMail()
diff --git a/web/app/signup/layout.tsx b/web/app/signup/layout.tsx
index 16c5fcefd2a..3c1b17ae10e 100644
--- a/web/app/signup/layout.tsx
+++ b/web/app/signup/layout.tsx
@@ -1,12 +1,13 @@
'use client'
import { cn } from '@langgenius/dify-ui/cn'
+import { useSuspenseQuery } from '@tanstack/react-query'
import Header from '@/app/signin/_header'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import useDocumentTitle from '@/hooks/use-document-title'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
export default function RegisterLayout({ children }: any) {
- const { systemFeatures } = useGlobalPublicStore()
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
useDocumentTitle('')
return (
<>
diff --git a/web/context/app-context-provider.tsx b/web/context/app-context-provider.tsx
index 0bf38510462..fb17664d6da 100644
--- a/web/context/app-context-provider.tsx
+++ b/web/context/app-context-provider.tsx
@@ -2,7 +2,7 @@
import type { FC, ReactNode } from 'react'
import type { ICurrentWorkspace, LangGeniusVersionResponse, UserProfileResponse } from '@/models/common'
-import { useQueryClient } from '@tanstack/react-query'
+import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import { useCallback, useEffect, useMemo } from 'react'
import { setUserId, setUserProperties } from '@/app/components/base/amplitude'
import { setZendeskConversationFields } from '@/app/components/base/zendesk/utils'
@@ -16,12 +16,12 @@ import {
useSelector,
} from '@/context/app-context'
import { env } from '@/env'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import {
useCurrentWorkspace,
useLangGeniusVersion,
- useUserProfile,
+ userProfileQueryOptions,
} from '@/service/use-common'
-import { useGlobalPublicStore } from './global-public-context'
type AppContextProviderProps = {
children: ReactNode
@@ -29,8 +29,13 @@ type AppContextProviderProps = {
export const AppContextProvider: FC<AppContextProviderProps> = ({ children }) => {
const queryClient = useQueryClient()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
- const { data: userProfileResp } = useUserProfile()
+ // Boot point for the (commonLayout) tree:
+ // - useSuspenseQuery for systemFeatures triggers app/loading.tsx until cache is warm.
+ // - useSuspenseQuery for userProfile triggers (commonLayout)/loading.tsx until cache is warm.
+ // After this provider mounts, downstream components reading the same queryKeys hit cache
+ // and never suspend again, so their useSuspenseQuery calls return data synchronously.
+ const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
+ const { data: userProfileResp } = useSuspenseQuery(userProfileQueryOptions())
const { data: currentWorkspaceResp, isPending: isLoadingCurrentWorkspace, isFetching: isValidatingCurrentWorkspace } = useCurrentWorkspace()
const langGeniusVersionQuery = useLangGeniusVersion(
userProfileResp?.meta.currentVersion,
diff --git a/web/context/global-public-context.tsx b/web/context/global-public-context.tsx
deleted file mode 100644
index 190033bbf7d..00000000000
--- a/web/context/global-public-context.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-'use client'
-import type { FC, PropsWithChildren } from 'react'
-import type { SystemFeatures } from '@/types/feature'
-import { useQuery } from '@tanstack/react-query'
-import { create } from 'zustand'
-import Loading from '@/app/components/base/loading'
-import { consoleClient } from '@/service/client'
-import { defaultSystemFeatures } from '@/types/feature'
-import { fetchSetupStatusWithCache } from '@/utils/setup-status'
-
-type GlobalPublicStore = {
- systemFeatures: SystemFeatures
- setSystemFeatures: (systemFeatures: SystemFeatures) => void
-}
-
-export const useGlobalPublicStore = create<GlobalPublicStore>(set => ({
- systemFeatures: defaultSystemFeatures,
- setSystemFeatures: (systemFeatures: SystemFeatures) => set(() => ({ systemFeatures })),
-}))
-
-const systemFeaturesQueryKey = ['systemFeatures'] as const
-const setupStatusQueryKey = ['setupStatus'] as const
-
-async function fetchSystemFeatures() {
- const data = await consoleClient.systemFeatures()
- const { setSystemFeatures } = useGlobalPublicStore.getState()
- setSystemFeatures({ ...defaultSystemFeatures, ...data })
- return data
-}
-
-export function useSystemFeaturesQuery() {
- return useQuery({
- queryKey: systemFeaturesQueryKey,
- queryFn: fetchSystemFeatures,
- })
-}
-
-export function useIsSystemFeaturesPending() {
- const { isPending } = useSystemFeaturesQuery()
- return isPending
-}
-
-function useSetupStatusQuery() {
- return useQuery({
- queryKey: setupStatusQueryKey,
- queryFn: fetchSetupStatusWithCache,
- staleTime: Infinity,
- })
-}
-
-const GlobalPublicStoreProvider: FC<PropsWithChildren> = ({
- children,
-}) => {
- // Fetch systemFeatures and setupStatus in parallel to reduce waterfall.
- // setupStatus is prefetched here and cached in localStorage for AppInitializer.
- const { isPending } = useSystemFeaturesQuery()
-
- // Prefetch setupStatus for AppInitializer (result not needed here)
- useSetupStatusQuery()
-
- if (isPending)
- return <div className="flex h-screen w-screen items-center justify-center"><Loading /></div>
- return <>{children}</>
-}
-export default GlobalPublicStoreProvider
diff --git a/web/context/web-app-context.tsx b/web/context/web-app-context.tsx
index 33679fd44f5..be10a85f994 100644
--- a/web/context/web-app-context.tsx
+++ b/web/context/web-app-context.tsx
@@ -3,14 +3,15 @@
import type { FC, PropsWithChildren } from 'react'
import type { ChatConfig } from '@/app/components/base/chat/types'
import type { AppData, AppMeta } from '@/models/share'
+import { useQuery } from '@tanstack/react-query'
import { useEffect } from 'react'
import { create } from 'zustand'
import { getProcessedSystemVariablesFromUrlParams } from '@/app/components/base/chat/utils'
import Loading from '@/app/components/base/loading'
import { AccessMode } from '@/models/access-control'
import { usePathname, useSearchParams } from '@/next/navigation'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useGetWebAppAccessModeByCode } from '@/service/use-share'
-import { useIsSystemFeaturesPending } from './global-public-context'
type WebAppStore = {
shareCode: string | null
@@ -65,7 +66,7 @@ const getShareCodeFromPathname = (pathname: string): string | null => {
}
const WebAppStoreProvider: FC<PropsWithChildren> = ({ children }) => {
- const isGlobalPending = useIsSystemFeaturesPending()
+ const { isPending: isGlobalPending } = useQuery(systemFeaturesQueryOptions())
const updateWebAppAccessMode = useWebAppStore(state => state.updateWebAppAccessMode)
const updateShareCode = useWebAppStore(state => state.updateShareCode)
const updateEmbeddedUserId = useWebAppStore(state => state.updateEmbeddedUserId)
diff --git a/web/contract/console/system.ts b/web/contract/console/system.ts
index bce0a8226e9..73e920b8044 100644
--- a/web/contract/console/system.ts
+++ b/web/contract/console/system.ts
@@ -7,5 +7,4 @@ export const systemFeaturesContract = base
path: '/system-features',
method: 'GET',
})
- .input(type<unknown>())
.output(type<SystemFeatures>())
diff --git a/web/hooks/use-document-title.spec.ts b/web/hooks/use-document-title.spec.ts
index 7ce1e693dbc..36a7bcc83b8 100644
--- a/web/hooks/use-document-title.spec.ts
+++ b/web/hooks/use-document-title.spec.ts
@@ -1,5 +1,4 @@
-import { act, renderHook } from '@testing-library/react'
-import { useGlobalPublicStore, useIsSystemFeaturesPending } from '@/context/global-public-context'
+import { renderHookWithSystemFeatures } from '@/__tests__/utils/mock-system-features'
/**
* Test suite for useDocumentTitle hook
*
@@ -12,42 +11,20 @@ import { useGlobalPublicStore, useIsSystemFeaturesPending } from '@/context/glob
* Title format: "[Page Title] - [Brand Name]"
* If no page title: "[Brand Name]"
*/
-import { defaultSystemFeatures } from '@/types/feature'
import useDocumentTitle from './use-document-title'
-vi.mock('@/context/global-public-context', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@/context/global-public-context')>()
- return {
- ...actual,
- useIsSystemFeaturesPending: vi.fn(() => false),
- }
-})
-
/**
* Test behavior when system features are still loading
* Title should remain empty to prevent flicker
*/
describe('title should be empty if systemFeatures is pending', () => {
- beforeEach(() => {
- vi.mocked(useIsSystemFeaturesPending).mockReturnValue(true)
- act(() => {
- useGlobalPublicStore.setState({
- systemFeatures: { ...defaultSystemFeatures, branding: { ...defaultSystemFeatures.branding, enabled: false } },
- })
- })
- })
- /**
- * Test that title stays empty during loading even when a title is provided
- */
it('document title should be empty if set title', () => {
- renderHook(() => useDocumentTitle('test'))
+ renderHookWithSystemFeatures(() => useDocumentTitle('test'), { systemFeatures: null })
expect(document.title).toBe('')
})
- /**
- * Test that title stays empty during loading when no title is provided
- */
+
it('document title should be empty if not set title', () => {
- renderHook(() => useDocumentTitle(''))
+ renderHookWithSystemFeatures(() => useDocumentTitle(''), { systemFeatures: null })
expect(document.title).toBe('')
})
})
@@ -57,29 +34,17 @@ describe('title should be empty if systemFeatures is pending', () => {
* When custom branding is disabled, should use "Dify" as the brand name
*/
describe('use default branding', () => {
- beforeEach(() => {
- vi.mocked(useIsSystemFeaturesPending).mockReturnValue(false)
- act(() => {
- useGlobalPublicStore.setState({
- systemFeatures: { ...defaultSystemFeatures, branding: { ...defaultSystemFeatures.branding, enabled: false } },
- })
- })
- })
- /**
- * Test title format with page title and default branding
- * Format: "[page] - Dify"
- */
it('document title should be test-Dify if set title', () => {
- renderHook(() => useDocumentTitle('test'))
+ renderHookWithSystemFeatures(() => useDocumentTitle('test'), {
+ systemFeatures: { branding: { enabled: false } },
+ })
expect(document.title).toBe('test - Dify')
})
- /**
- * Test title with only default branding (no page title)
- * Format: "Dify"
- */
it('document title should be Dify if not set title', () => {
- renderHook(() => useDocumentTitle(''))
+ renderHookWithSystemFeatures(() => useDocumentTitle(''), {
+ systemFeatures: { branding: { enabled: false } },
+ })
expect(document.title).toBe('Dify')
})
})
@@ -89,29 +54,17 @@ describe('use default branding', () => {
* When custom branding is enabled, should use the configured application_title
*/
describe('use specific branding', () => {
- beforeEach(() => {
- vi.mocked(useIsSystemFeaturesPending).mockReturnValue(false)
- act(() => {
- useGlobalPublicStore.setState({
- systemFeatures: { ...defaultSystemFeatures, branding: { ...defaultSystemFeatures.branding, enabled: true, application_title: 'Test' } },
- })
- })
- })
- /**
- * Test title format with page title and custom branding
- * Format: "[page] - [Custom Brand]"
- */
it('document title should be test-Test if set title', () => {
- renderHook(() => useDocumentTitle('test'))
+ renderHookWithSystemFeatures(() => useDocumentTitle('test'), {
+ systemFeatures: { branding: { enabled: true, application_title: 'Test' } },
+ })
expect(document.title).toBe('test - Test')
})
- /**
- * Test title with only custom branding (no page title)
- * Format: "[Custom Brand]"
- */
it('document title should be Test if not set title', () => {
- renderHook(() => useDocumentTitle(''))
+ renderHookWithSystemFeatures(() => useDocumentTitle(''), {
+ systemFeatures: { branding: { enabled: true, application_title: 'Test' } },
+ })
expect(document.title).toBe('Test')
})
})
diff --git a/web/hooks/use-document-title.ts b/web/hooks/use-document-title.ts
index 37b31a7dea9..ad275f55c96 100644
--- a/web/hooks/use-document-title.ts
+++ b/web/hooks/use-document-title.ts
@@ -1,12 +1,14 @@
'use client'
+import { useQuery } from '@tanstack/react-query'
import { useFavicon, useTitle } from 'ahooks'
import { useEffect } from 'react'
-import { useGlobalPublicStore, useIsSystemFeaturesPending } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
+import { defaultSystemFeatures } from '@/types/feature'
import { basePath } from '@/utils/var'
export default function useDocumentTitle(title: string) {
- const isPending = useIsSystemFeaturesPending()
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ const { data, isPending } = useQuery(systemFeaturesQueryOptions())
+ const systemFeatures = data ?? defaultSystemFeatures
const prefix = title ? `${title} - ` : ''
let titleStr = ''
let favicon = ''
diff --git a/web/next.config.ts b/web/next.config.ts
index aa4d9318f47..db44f5b9ede 100644
--- a/web/next.config.ts
+++ b/web/next.config.ts
@@ -34,9 +34,6 @@ const nextConfig: NextConfig = {
compiler: {
removeConsole: isDev ? false : { exclude: ['warn', 'error'] },
},
- experimental: {
- turbopackFileSystemCacheForDev: false,
- },
}
export default withMDX(nextConfig)
diff --git a/web/service/access-control.ts b/web/service/access-control.ts
index c87e01f4827..fa7cfd7055b 100644
--- a/web/service/access-control.ts
+++ b/web/service/access-control.ts
@@ -1,7 +1,7 @@
import type { AccessControlAccount, AccessControlGroup, AccessMode, Subject } from '@/models/access-control'
import type { App } from '@/types/app'
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { useGlobalPublicStore } from '@/context/global-public-context'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { get, post } from './base'
import { getUserCanAccess } from './share'
@@ -71,11 +71,15 @@ export const useUpdateAccessMode = () => {
}
export const useGetUserCanAccessApp = ({ appId, isInstalledApp = true, enabled }: { appId?: string, isInstalledApp?: boolean, enabled?: boolean }) => {
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ // useQuery (not useSuspenseQuery) to keep this service hook's call contract
+ // unchanged from the zustand era: callers should not need a Suspense boundary.
+ // First-fetch undefined is bridged via `?? false` so the inner queryKey is stable.
+ const { data: systemFeatures } = useQuery(systemFeaturesQueryOptions())
+ const webappAuthEnabled = systemFeatures?.webapp_auth.enabled ?? false
return useQuery({
- queryKey: [NAME_SPACE, 'user-can-access-app', appId, systemFeatures.webapp_auth.enabled, isInstalledApp],
+ queryKey: [NAME_SPACE, 'user-can-access-app', appId, webappAuthEnabled, isInstalledApp],
queryFn: () => {
- if (systemFeatures.webapp_auth.enabled)
+ if (webappAuthEnabled)
return getUserCanAccess(appId!, isInstalledApp)
else
return { result: true }
diff --git a/web/service/system-features.ts b/web/service/system-features.ts
new file mode 100644
index 00000000000..4bf79a16fde
--- /dev/null
+++ b/web/service/system-features.ts
@@ -0,0 +1,33 @@
+import type { SystemFeatures } from '@/types/feature'
+import { queryOptions } from '@tanstack/react-query'
+import { defaultSystemFeatures } from '@/types/feature'
+import { consoleClient, consoleQuery } from './client'
+
+/**
+ * Soft-fallback to defaults so the dashboard stays usable when /system-features fails.
+ *
+ * No `retry`: the queryFn never throws (errors are caught and turned into the
+ * default payload), so react-query's retry would never fire under this model.
+ * This trades main's transient-blip resilience for guaranteed dashboard
+ * availability via defaults; the trade-off is acceptable because /system-features
+ * is a small, dependency-free endpoint in the community edition.
+ *
+ * No `staleTime` override either: inherit the 5-minute default from
+ * query-client-server.ts. Combined with `refetchOnWindowFocus`, this lets us
+ * recover from a transient startup failure (which got cached as "successful
+ * defaults") within ~5 minutes or on tab focus. `staleTime: Infinity` would
+ * pin the whole tab to defaults until reload — strictly worse than main.
+ */
+export const systemFeaturesQueryOptions = () =>
+ queryOptions<SystemFeatures>({
+ queryKey: consoleQuery.systemFeatures.queryKey(),
+ queryFn: async () => {
+ try {
+ return await consoleClient.systemFeatures()
+ }
+ catch (err) {
+ console.error('[systemFeatures] fetch failed, using defaults', err)
+ return defaultSystemFeatures
+ }
+ },
+ })
diff --git a/web/service/use-common.ts b/web/service/use-common.ts
index 238f4f6ecfc..0154be09ff4 100644
--- a/web/service/use-common.ts
+++ b/web/service/use-common.ts
@@ -21,10 +21,20 @@ import type {
UserProfileResponse,
} from '@/models/common'
import type { RETRIEVE_METHOD } from '@/types/app'
-import { useMutation, useQuery } from '@tanstack/react-query'
+import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { IS_DEV } from '@/config'
import { get, post } from './base'
+/**
+ * True iff `err` is a 401 Response thrown by `service/base.ts`.
+ *
+ * Narrow on purpose: oRPC throws `ORPCError`, not `Response`, so this predicate
+ * returns `false` for oRPC 401s. Naming makes that scope visible. If you need
+ * 401 detection for an oRPC path, add a separate `isOrpc401` helper.
+ */
+export const isLegacyBase401 = (err: unknown): boolean =>
+ err instanceof Response && err.status === 401
+
const NAME_SPACE = 'common'
export const commonQueryKeys = {
@@ -35,7 +45,6 @@ export const commonQueryKeys = {
members: [NAME_SPACE, 'members'] as const,
filePreview: (fileID: string) => [NAME_SPACE, 'file-preview', fileID] as const,
schemaDefinitions: [NAME_SPACE, 'schema-type-definitions'] as const,
- isLogin: [NAME_SPACE, 'is-login'] as const,
modelProviders: [NAME_SPACE, 'model-providers'] as const,
modelList: (type: ModelTypeEnum) => [NAME_SPACE, 'model-list', type] as const,
defaultModel: (type: ModelTypeEnum) => [NAME_SPACE, 'default-model', type] as const,
@@ -74,11 +83,25 @@ type UserProfileWithMeta = {
}
}
-export const useUserProfile = () => {
- return useQuery<UserProfileWithMeta>({
+/**
+ * Session probe for `/account/profile`. Helper (not hook) because oRPC can't
+ * express the `x-version` / `x-env` response headers we post-process.
+ *
+ * Bindings:
+ * commonLayout -> `useSuspenseQuery(userProfileQueryOptions())`
+ * signin/oauth -> `useQuery({ ...userProfileQueryOptions(), throwOnError: err => !isLegacyBase401(err) })`
+ *
+ * `silent: true` + `retry: !isLegacyBase401` makes 401 a synchronous *state* (no toast,
+ * no ~7s retry storm). Transient errors still get the default 3 retries.
+ */
+export const userProfileQueryOptions = () =>
+ queryOptions<UserProfileWithMeta>({
queryKey: commonQueryKeys.userProfile,
queryFn: async () => {
- const response = await get<Response>('/account/profile', {}, { needAllResponseContent: true }) as Response
+ const response = await get<Response>('/account/profile', {}, {
+ needAllResponseContent: true,
+ silent: true,
+ }) as Response
const profile = await response.clone().json() as UserProfileResponse
return {
profile,
@@ -92,8 +115,8 @@ export const useUserProfile = () => {
},
staleTime: 0,
gcTime: 0,
+ retry: (failureCount, error) => !isLegacyBase401(error) && failureCount < 3,
})
-}
export const useLangGeniusVersion = (currentVersion?: string | null, enabled?: boolean) => {
return useQuery<LangGeniusVersionResponse>({
@@ -205,34 +228,21 @@ export const useSchemaTypeDefinitions = () => {
})
}
-type isLogin = {
- logged_in: boolean
-}
-
-export const useIsLogin = () => {
- return useQuery<isLogin>({
- queryKey: commonQueryKeys.isLogin,
- staleTime: 0,
- gcTime: 0,
- queryFn: async (): Promise<isLogin> => {
- try {
- await get('/account/profile', {}, {
- silent: true,
- })
- return { logged_in: true }
- }
- catch {
- // Any error (401, 500, network error, etc.) means not logged in
- return { logged_in: false }
- }
- },
- })
-}
-
export const useLogout = () => {
+ const queryClient = useQueryClient()
return useMutation({
mutationKey: [NAME_SPACE, 'logout'],
mutationFn: () => post('/logout'),
+ onSuccess: () => {
+ // Drop all cached queries so the post-logout /signin probe doesn't read
+ // the previous user's profile (the userProfile queryKey is shared with
+ // the (commonLayout) tree, which keeps observing it during React's
+ // concurrent transition — gcTime: 0 is not enough on its own).
+ // Nuclear over targeted: every new user-scoped query would otherwise
+ // need to be remembered here. systemFeatures (user-agnostic) just
+ // refetches once on the way to /signin, which is cheap.
+ queryClient.clear()
+ },
})
}
diff --git a/web/service/use-explore.ts b/web/service/use-explore.ts
index 1f3c0ed6b93..de508b642f8 100644
--- a/web/service/use-explore.ts
+++ b/web/service/use-explore.ts
@@ -1,8 +1,8 @@
import type { App, AppCategory } from '@/models/explore'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { useGlobalPublicStore } from '@/context/global-public-context'
import { useLocale } from '@/context/i18n'
import { AccessMode } from '@/models/access-control'
+import { systemFeaturesQueryOptions } from '@/service/system-features'
import { consoleQuery } from './client'
import { fetchAppList, fetchBanners, fetchInstalledAppList, fetchInstalledAppMeta, fetchInstalledAppParams, getAppAccessModeByAppId, uninstallApp, updatePinStatus } from './explore'
@@ -66,18 +66,22 @@ export const useUpdateAppPinStatus = () => {
}
export const useGetInstalledAppAccessModeByAppId = (appId: string | null) => {
- const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
+ // useQuery (not useSuspenseQuery) to keep this service hook's call contract
+ // unchanged from the zustand era: callers should not need a Suspense boundary.
+ // First-fetch undefined is bridged via `?? false` so the inner queryKey is stable.
+ const { data: systemFeatures } = useQuery(systemFeaturesQueryOptions())
+ const webappAuthEnabled = systemFeatures?.webapp_auth.enabled ?? false
const appAccessModeInput = { query: { appId: appId ?? '' } }
const installedAppId = appAccessModeInput.query.appId
return useQuery({
queryKey: [
...consoleQuery.explore.appAccessMode.queryKey({ input: appAccessModeInput }),
- systemFeatures.webapp_auth.enabled,
+ webappAuthEnabled,
installedAppId,
],
queryFn: () => {
- if (systemFeatures.webapp_auth.enabled === false) {
+ if (webappAuthEnabled === false) {
return {
accessMode: AccessMode.PUBLIC,
}