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.

fix(web): redirect legacy plugin fallbacks (#40051)

Jingyi18f740402f84
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 499be156a77..9006044d536 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -1996,17 +1996,6 @@
"count": 1
}
},
- "web/app/components/base/tab-slider/index.tsx": {
- "eslint-react/set-state-in-effect": {
- "count": 2
- },
- "jsx_a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx_a11y/no-static-element-interactions": {
- "count": 1
- }
- },
"web/app/components/base/tag-input/index.stories.tsx": {
"jsx_a11y/label-has-associated-control": {
"count": 12
diff --git a/web/app/(commonLayout)/plugins/page.spec.tsx b/web/app/(commonLayout)/plugins/page.spec.tsx
new file mode 100644
index 00000000000..7db7b32af5c
--- /dev/null
+++ b/web/app/(commonLayout)/plugins/page.spec.tsx
@@ -0,0 +1,75 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ fetch: vi.fn(),
+ redirect: vi.fn((url: string) => {
+ throw new Error(`NEXT_REDIRECT:${url}`)
+ }),
+}))
+
+vi.mock('@/next/navigation', () => ({
+ redirect: (url: string) => mocks.redirect(url),
+}))
+
+describe('PluginList', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.stubGlobal('fetch', mocks.fetch)
+ })
+
+ it('redirects a package install link to its category integration', async () => {
+ mocks.fetch.mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ data: {
+ plugin: {
+ category: 'tool',
+ },
+ },
+ }),
+ })
+ const { default: PluginList } = await import('./page')
+
+ await expect(
+ PluginList({
+ searchParams: Promise.resolve({
+ 'package-ids': '["langgenius/example-tool"]',
+ }),
+ }),
+ ).rejects.toThrow('NEXT_REDIRECT')
+
+ expect(mocks.redirect).toHaveBeenCalledWith(
+ '/integrations/tools/built-in?package-ids=%5B%22langgenius%2Fexample-tool%22%5D',
+ )
+ })
+
+ it('redirects to integrations when category resolution fails', async () => {
+ mocks.fetch.mockResolvedValue({ ok: false })
+ const { default: PluginList } = await import('./page')
+
+ await expect(
+ PluginList({
+ searchParams: Promise.resolve({
+ 'package-ids': '["langgenius/example-tool"]',
+ }),
+ }),
+ ).rejects.toThrow('NEXT_REDIRECT')
+
+ expect(mocks.redirect).toHaveBeenCalledWith('/integrations')
+ })
+
+ it('redirects to integrations when category resolution request rejects', async () => {
+ mocks.fetch.mockRejectedValue(new Error('Marketplace unavailable'))
+ const { default: PluginList } = await import('./page')
+
+ await expect(
+ PluginList({
+ searchParams: Promise.resolve({
+ 'package-ids': '["langgenius/example-tool"]',
+ }),
+ }),
+ ).rejects.toThrow('NEXT_REDIRECT')
+
+ expect(mocks.redirect).toHaveBeenCalledWith('/integrations')
+ })
+})
diff --git a/web/app/(commonLayout)/plugins/page.tsx b/web/app/(commonLayout)/plugins/page.tsx
index f815ed0e1b2..f22d0e2a811 100644
--- a/web/app/(commonLayout)/plugins/page.tsx
+++ b/web/app/(commonLayout)/plugins/page.tsx
@@ -1,7 +1,4 @@
import type { LegacyPluginsSearchParams } from '@/app/components/plugins/plugin-routes'
-import Marketplace from '@/app/components/plugins/marketplace'
-import PluginPage from '@/app/components/plugins/plugin-page'
-import PluginsPanel from '@/app/components/plugins/plugin-page/plugins-panel'
import {
getFirstPackageIdFromSearchParams,
getInstallRedirectPathByPluginCategory,
@@ -60,14 +57,7 @@ const PluginList = async ({ searchParams }: PluginListProps) => {
const redirectPath = getLegacyPluginRedirectPath(resolvedSearchParams)
- if (redirectPath) redirect(redirectPath)
-
- return (
- <PluginPage
- plugins={<PluginsPanel />}
- marketplace={<Marketplace showInstallButton pluginTypeSwitchClassName="top-[60px]" />}
- />
- )
+ redirect(redirectPath)
}
export default PluginList
diff --git a/web/app/components/base/tab-slider/__tests__/index.spec.tsx b/web/app/components/base/tab-slider/__tests__/index.spec.tsx
deleted file mode 100644
index a1591b20048..00000000000
--- a/web/app/components/base/tab-slider/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { useInstalledPluginList } from '@/service/use-plugins'
-import TabSlider from '../index'
-
-vi.mock('@/service/use-plugins', () => ({
- useInstalledPluginList: vi.fn(),
-}))
-
-const options = [
- { value: 'all', text: 'All' },
- { value: 'plugins', text: 'Plugins' },
-]
-
-describe('TabSlider', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- vi.mocked(useInstalledPluginList).mockReturnValue({
- data: { total: 0 },
- isLoading: false,
- } as ReturnType<typeof useInstalledPluginList>)
- })
-
- it('changes only when users select an inactive tab', async () => {
- const user = userEvent.setup()
- const onChange = vi.fn()
- render(<TabSlider value="all" options={options} onChange={onChange} />)
-
- await user.click(screen.getByText('All'))
- expect(onChange).not.toHaveBeenCalled()
-
- await user.click(screen.getByText('Plugins'))
- expect(onChange).toHaveBeenCalledWith('plugins')
- })
-
- it('shows the installed plugin count', () => {
- vi.mocked(useInstalledPluginList).mockReturnValue({
- data: { total: 5 },
- isLoading: false,
- } as ReturnType<typeof useInstalledPluginList>)
-
- render(<TabSlider value="all" options={options} onChange={vi.fn()} />)
-
- expect(screen.getByText('5')).toBeInTheDocument()
- })
-})
diff --git a/web/app/components/base/tab-slider/index.stories.tsx b/web/app/components/base/tab-slider/index.stories.tsx
deleted file mode 100644
index 2e5e7d01c71..00000000000
--- a/web/app/components/base/tab-slider/index.stories.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import { useEffect, useState } from 'react'
-import TabSlider from '.'
-
-const OPTIONS = [
- { value: 'models', text: 'Models' },
- { value: 'datasets', text: 'Datasets' },
- { value: 'plugins', text: 'Plugins' },
-]
-
-const TabSliderDemo = ({ initialValue = 'models' }: { initialValue?: string }) => {
- const [value, setValue] = useState(initialValue)
-
- useEffect(() => {
- const originalFetch = globalThis.fetch?.bind(globalThis)
-
- const handler = async (input: RequestInfo | URL, init?: RequestInit) => {
- const url =
- typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url
-
- if (url.includes('/workspaces/current/plugin/list')) {
- return new Response(
- JSON.stringify({
- total: 6,
- plugins: [],
- }),
- {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- },
- )
- }
-
- if (originalFetch) return originalFetch(input, init)
-
- throw new Error(`Unhandled request for ${url}`)
- }
-
- globalThis.fetch = handler as typeof globalThis.fetch
-
- return () => {
- if (originalFetch) globalThis.fetch = originalFetch
- }
- }, [])
-
- return (
- <div className="flex w-full max-w-lg flex-col gap-4 rounded-2xl border border-divider-subtle bg-components-panel-bg p-6">
- <div className="text-xs tracking-[0.18em] text-text-tertiary uppercase">Segmented tabs</div>
- <TabSlider value={value} options={OPTIONS} onChange={setValue} />
- </div>
- )
-}
-
-const meta = {
- title: 'Base/Navigation/TabSlider',
- component: TabSliderDemo,
- parameters: {
- layout: 'centered',
- docs: {
- description: {
- component:
- 'Animated segmented control with sliding highlight. A badge appears when plugins are installed (mocked in Storybook).',
- },
- },
- },
- argTypes: {
- initialValue: {
- control: 'radio',
- options: OPTIONS.map((option) => option.value),
- },
- },
- args: {
- initialValue: 'models',
- },
- tags: ['autodocs'],
-} satisfies Meta<typeof TabSliderDemo>
-
-export default meta
-type Story = StoryObj<typeof meta>
-
-export const Playground: Story = {}
diff --git a/web/app/components/base/tab-slider/index.tsx b/web/app/components/base/tab-slider/index.tsx
deleted file mode 100644
index eb29ca908a0..00000000000
--- a/web/app/components/base/tab-slider/index.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import type { FC, ReactNode } from 'react'
-import { cn } from '@langgenius/dify-ui/cn'
-import { useEffect, useState } from 'react'
-import Badge, { BadgeState } from '@/app/components/base/badge/index'
-import { useInstalledPluginList } from '@/service/use-plugins'
-
-type Option = {
- value: string
- text: ReactNode
-}
-
-type TabSliderProps = {
- className?: string
- value: string
- itemClassName?: string | ((active: boolean) => string)
- onChange: (v: string) => void
- options: Option[]
-}
-
-const TabSlider: FC<TabSliderProps> = ({ className, itemClassName, value, onChange, options }) => {
- const [activeIndex, setActiveIndex] = useState(() =>
- options.findIndex((option) => option.value === value),
- )
- const [sliderStyle, setSliderStyle] = useState({})
- const { data: pluginList } = useInstalledPluginList()
-
- const updateSliderStyle = (index: number) => {
- const tabElement = document.getElementById(`tab-${index}`)
- if (tabElement) {
- const { offsetLeft, offsetWidth } = tabElement
- setSliderStyle({
- transform: `translateX(${offsetLeft}px)`,
- width: `${offsetWidth}px`,
- })
- }
- }
-
- useEffect(() => {
- const newIndex = options.findIndex((option) => option.value === value)
- setActiveIndex(newIndex)
- updateSliderStyle(newIndex)
- }, [value, options, pluginList?.total])
-
- return (
- <div
- data-testid="tab-slider-container"
- className={cn(
- className,
- 'relative inline-flex items-center justify-center rounded-[10px] bg-components-segmented-control-bg-normal p-0.5',
- )}
- >
- <div
- data-testid="tab-slider-bg"
- className="shadows-shadow-xs absolute top-0.5 right-0 bottom-0.5 left-0 rounded-[10px] bg-components-panel-bg transition-transform duration-300 ease-in-out"
- style={sliderStyle}
- />
- {options.map((option, index) => (
- <div
- id={`tab-${index}`}
- key={option.value}
- data-testid={`tab-item-${option.value}`}
- className={cn(
- 'relative z-10 flex cursor-pointer items-center justify-center gap-1 rounded-[10px] px-2.5 py-1.5 transition-colors duration-300 ease-in-out',
- 'system-md-semibold',
- index === activeIndex ? 'text-text-primary' : 'text-text-tertiary',
- typeof itemClassName === 'function'
- ? itemClassName(index === activeIndex)
- : itemClassName,
- )}
- onClick={() => {
- if (index !== activeIndex) {
- onChange(option.value)
- updateSliderStyle(index)
- }
- }}
- >
- {option.text}
- {/* if no plugin installed, the badge won't show */}
- {option.value === 'plugins' && (pluginList?.total ?? 0) > 0 && (
- <Badge size="s" uppercase={true} state={BadgeState.Default}>
- {pluginList?.total}
- </Badge>
- )}
- </div>
- ))}
- </div>
- )
-}
-
-export default TabSlider
diff --git a/web/app/components/plugins/__tests__/plugin-routes.spec.ts b/web/app/components/plugins/__tests__/plugin-routes.spec.ts
index eea3d5a0d30..482a3e75bf2 100644
--- a/web/app/components/plugins/__tests__/plugin-routes.spec.ts
+++ b/web/app/components/plugins/__tests__/plugin-routes.spec.ts
@@ -32,12 +32,15 @@ describe('plugin routes', () => {
})
it.each([
- { 'package-ids': '["langgenius/telegram_trigger"]' },
- { tab: 'plugins', 'package-ids': '["langgenius/telegram_trigger"]' },
- { 'bundle-info': '{"org":"langgenius","name":"bundle","version":"1.0.0"}' },
- ])('keeps install deep links on the legacy plugin page for search params %j', (searchParams) => {
- expect(getLegacyPluginRedirectPath(searchParams)).toBeUndefined()
- })
+ [{ 'package-ids': '["langgenius/telegram_trigger"]' }, '/integrations'],
+ [{ tab: 'plugins', 'package-ids': '["langgenius/telegram_trigger"]' }, '/integrations'],
+ [{ 'bundle-info': '{"org":"langgenius","name":"bundle","version":"1.0.0"}' }, '/integrations'],
+ ])(
+ 'redirects unresolved install deep links to integrations for search params %j',
+ (searchParams, expected) => {
+ expect(getLegacyPluginRedirectPath(searchParams)).toBe(expected)
+ },
+ )
it('parses the first package id from marketplace install search params', () => {
expect(
@@ -149,10 +152,10 @@ describe('plugin routes', () => {
expect(getLegacyPluginRedirectPath(searchParams)).toBe(expected)
})
- it.each([{ tab: 'unsupported' }, { tab: 'toString' }])(
- 'does not redirect unsupported plugin URLs for search params %j',
- (searchParams) => {
- expect(getLegacyPluginRedirectPath(searchParams)).toBeUndefined()
- },
- )
+ it.each([
+ [{ tab: 'unsupported' }, '/integrations'],
+ [{ tab: 'toString' }, '/integrations'],
+ ])('redirects unsupported plugin URLs for search params %j', (searchParams, expected) => {
+ expect(getLegacyPluginRedirectPath(searchParams)).toBe(expected)
+ })
})
diff --git a/web/app/components/plugins/plugin-page/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/index.spec.tsx
deleted file mode 100644
index bea42215031..00000000000
--- a/web/app/components/plugins/plugin-page/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,1167 +0,0 @@
-import type { ReactElement } from 'react'
-import type { PluginPageProps } from '../index'
-import { act, fireEvent, screen, waitFor } from '@testing-library/react'
-import { useQueryState } from 'nuqs'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-import useDocumentTitle from '@/hooks/use-document-title'
-import { usePluginInstallation } from '@/hooks/use-query-params'
-// Import mocked modules for assertions
-import { fetchBundleInfoFromMarketPlace, fetchManifestFromMarketPlace } from '@/service/plugins'
-import { renderWithConsoleQuery } from '@/test/console/query-data'
-import PluginPageWithContext from '../index'
-
-let mockEnableMarketplace = true
-const { mockRouterReplace } = vi.hoisted(() => ({
- mockRouterReplace: vi.fn(),
-}))
-
-const render = (ui: ReactElement, options: Parameters<typeof renderWithConsoleQuery>[1] = {}) =>
- renderWithConsoleQuery(ui, {
- systemFeatures: { enable_marketplace: mockEnableMarketplace },
- ...options,
- })
-
-// Mock external dependencies
-vi.mock('@/service/plugins', () => ({
- fetchManifestFromMarketPlace: vi.fn(),
- fetchBundleInfoFromMarketPlace: vi.fn(),
-}))
-
-vi.mock('@/hooks/use-query-params', () => ({
- usePluginInstallation: vi.fn(() => [{ packageId: null, bundleInfo: null }, vi.fn()]),
-}))
-
-vi.mock('@/hooks/use-document-title', () => ({
- default: vi.fn(),
-}))
-
-vi.mock('@/next/navigation', () => ({
- useRouter: () => ({
- replace: mockRouterReplace,
- }),
-}))
-
-vi.mock('@/context/i18n', () => ({
- useLocale: () => 'en-US',
- useDocLink: () => (path: string) => `https://docs.example.com${path}`,
-}))
-
-vi.mock('@/context/workspace-state', async () => {
- const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture')
- return createWorkspaceStateModuleMock(() => ({
- isCurrentWorkspaceManager: true,
- isCurrentWorkspaceOwner: false,
- langGeniusVersionInfo: {
- current_env: 'CLOUD',
- current_version: '1.0.0',
- latest_version: '1.0.0',
- version: '1.0.0',
- release_date: '',
- release_notes: '',
- can_auto_update: false,
- },
- workspacePermissionKeys: [
- 'plugin.install',
- 'plugin.delete',
- 'plugin.debug',
- 'plugin.plugin_preferences',
- ],
- }))
-})
-vi.mock('@/context/permission-state', async () => {
- const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
- return createPermissionStateModuleMock(() => ({
- isCurrentWorkspaceManager: true,
- isCurrentWorkspaceOwner: false,
- langGeniusVersionInfo: {
- current_env: 'CLOUD',
- current_version: '1.0.0',
- latest_version: '1.0.0',
- version: '1.0.0',
- release_date: '',
- release_notes: '',
- can_auto_update: false,
- },
- workspacePermissionKeys: [
- 'plugin.install',
- 'plugin.delete',
- 'plugin.debug',
- 'plugin.plugin_preferences',
- ],
- }))
-})
-vi.mock('@/context/version-state', async () => {
- const { createVersionStateModuleMock } = await import('@/test/console/state-fixture')
- return createVersionStateModuleMock(() => ({
- isCurrentWorkspaceManager: true,
- isCurrentWorkspaceOwner: false,
- langGeniusVersionInfo: {
- current_env: 'CLOUD',
- current_version: '1.0.0',
- latest_version: '1.0.0',
- version: '1.0.0',
- release_date: '',
- release_notes: '',
- can_auto_update: false,
- },
- workspacePermissionKeys: [
- 'plugin.install',
- 'plugin.delete',
- 'plugin.debug',
- 'plugin.plugin_preferences',
- ],
- }))
-})
-
-vi.mock('@/service/use-plugins', () => ({
- hasPluginPermission: (permission: string | undefined, isAdmin: boolean) => {
- if (!permission) return false
- if (permission === 'noone') return false
- if (permission === 'everyone') return true
- return isAdmin
- },
- useReferenceSettings: () => ({
- data: {
- permission: {
- install_permission: 'everyone',
- debug_permission: 'admins',
- },
- auto_upgrade: {
- strategy_setting: 'fix_only',
- upgrade_time_of_day: 0,
- upgrade_mode: 'all',
- exclude_plugins: [],
- include_plugins: [],
- },
- },
- }),
- usePluginPermissionSettings: () => ({
- data: {
- install_permission: 'everyone',
- debug_permission: 'admins',
- },
- }),
- useMutationPluginPermissionSettings: () => ({
- mutate: vi.fn(),
- isPending: false,
- }),
- usePluginAutoUpgradeSettings: () => ({
- data: {
- auto_upgrade: {
- strategy_setting: 'fix_only',
- upgrade_time_of_day: 0,
- upgrade_mode: 'all',
- exclude_plugins: [],
- include_plugins: [],
- },
- },
- }),
- useMutationReferenceSettings: () => ({
- mutate: vi.fn(),
- isPending: false,
- }),
- useInvalidateReferenceSettings: () => vi.fn(),
- usePluginTaskList: () => ({
- pluginTasks: [],
- handleRefetch: vi.fn(),
- }),
- useMutationClearTaskPlugin: () => ({
- mutateAsync: vi.fn(),
- }),
- useInstalledPluginList: () => ({
- data: [],
- isLoading: false,
- isFetching: false,
- isLastPage: true,
- loadNextPage: vi.fn(),
- }),
- useInstalledLatestVersion: () => ({
- data: {},
- }),
- useInvalidateInstalledPluginList: () => vi.fn(),
-}))
-
-vi.mock('nuqs', () => ({
- parseAsStringEnum: vi.fn(() => ({
- withDefault: vi.fn(() => ({})),
- })),
- useQueryState: vi.fn(() => ['plugins', vi.fn()]),
-}))
-
-vi.mock('../plugin-tasks', () => ({
- default: () => <div data-testid="plugin-tasks">PluginTasks</div>,
-}))
-
-vi.mock('../debug-info', () => ({
- default: () => <div data-testid="debug-info">DebugInfo</div>,
-}))
-
-vi.mock('../install-plugin-dropdown', () => ({
- default: ({ onSwitchToMarketplaceTab }: { onSwitchToMarketplaceTab: () => void }) => (
- <button data-testid="install-dropdown" onClick={onSwitchToMarketplaceTab}>
- Install
- </button>
- ),
-}))
-
-vi.mock('../../install-plugin/install-from-local-package', () => ({
- default: ({ onClose }: { onClose: () => void }) => (
- <div data-testid="install-local-modal">
- <button onClick={onClose}>Close</button>
- </div>
- ),
-}))
-
-vi.mock('../../install-plugin/install-from-marketplace', () => ({
- default: ({ onClose }: { onClose: () => void }) => (
- <div data-testid="install-marketplace-modal">
- <button onClick={onClose}>Close</button>
- </div>
- ),
-}))
-
-vi.mock('@/app/components/plugins/reference-setting-modal', () => ({
- default: ({ onHide }: { onHide: () => void }) => (
- <div data-testid="reference-setting-modal">
- <button onClick={onHide}>Close Settings</button>
- </div>
- ),
-}))
-
-// Helper to create default props
-const createDefaultProps = (): PluginPageProps => ({
- plugins: <div data-testid="plugins-content">Plugins Content</div>,
- marketplace: <div data-testid="marketplace-content">Marketplace Content</div>,
-})
-
-// ============================================================================
-// PluginPage Component Tests
-// ============================================================================
-describe('PluginPage Component', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockEnableMarketplace = true
- // Reset to default mock values
- vi.mocked(usePluginInstallation).mockReturnValue([
- { packageId: null, bundleInfo: null },
- vi.fn(),
- ])
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
- })
-
- // ============================================================================
- // Rendering Tests
- // ============================================================================
- describe('Rendering', () => {
- it('should render with correct container id', () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const container = document.getElementById('marketplace-container')
- expect(container).toBeInTheDocument()
- })
-
- it('should render PluginTasks component', () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(screen.getByTestId('plugin-tasks')).toBeInTheDocument()
- })
-
- it('should render plugins content when on plugins tab', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(screen.getByTestId('plugins-content')).toBeInTheDocument()
- })
-
- it('should render marketplace content when on marketplace tab', () => {
- vi.mocked(useQueryState).mockReturnValue(['discover', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- // The marketplace content should be visible when enable_marketplace is true and on discover tab
- const container = document.getElementById('marketplace-container')
- expect(container).toBeInTheDocument()
- // Check that marketplace-specific links are shown
- expect(screen.getByText(/requestAPlugin/i)).toBeInTheDocument()
- })
-
- it('should use plugins as document title on plugins tab', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(useDocumentTitle).toHaveBeenCalledWith('plugin.metadata.title')
- })
-
- it('should use marketplace as document title when exploring marketplace', () => {
- vi.mocked(useQueryState).mockReturnValue(['discover', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(useDocumentTitle).toHaveBeenCalledWith('common.mainNav.marketplace')
- })
-
- it('should render TabSlider', () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- // TabSlider renders tab options
- expect(document.querySelector('.flex-1')).toBeInTheDocument()
- })
-
- it('should render drag and drop hint when on plugins tab', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(screen.getByText(/dropPluginToInstall/i)).toBeInTheDocument()
- })
-
- it('should render file input for plugin upload', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const fileInput = document.getElementById('fileUploader')
- expect(fileInput).toBeInTheDocument()
- expect(fileInput).toHaveAttribute('type', 'file')
- })
- })
-
- // ============================================================================
- // Tab Navigation Tests
- // ============================================================================
- describe('Tab Navigation', () => {
- it('should display plugins tab as active by default', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(screen.getByTestId('plugins-content')).toBeInTheDocument()
- })
-
- it('should show marketplace links when on marketplace tab', () => {
- vi.mocked(useQueryState).mockReturnValue(['discover', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- // Check for marketplace-specific buttons
- expect(screen.getByText(/requestAPlugin/i)).toBeInTheDocument()
- expect(screen.getByText(/publishPlugins/i)).toBeInTheDocument()
- })
-
- it('should not show marketplace links when on plugins tab', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(screen.queryByText(/requestAPlugin/i)).not.toBeInTheDocument()
- })
- })
-
- // ============================================================================
- // Permission-based Rendering Tests
- // ============================================================================
- describe('Permission-based Rendering', () => {
- it('should render InstallPluginDropdown when canManagement is true', () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(screen.getByTestId('install-dropdown')).toBeInTheDocument()
- })
-
- it('should render DebugInfo when canDebugger is true', () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(screen.getByTestId('debug-info')).toBeInTheDocument()
- })
-
- it('should render settings button when canSetPermissions is true', () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- // Settings button with RiEqualizer2Line icon
- const settingsButtons = document.querySelectorAll('button')
- expect(settingsButtons.length).toBeGreaterThan(0)
- })
-
- it('should call setActiveTab when onSwitchToMarketplaceTab is called', async () => {
- const mockSetActiveTab = vi.fn()
- vi.mocked(useQueryState).mockReturnValue(['plugins', mockSetActiveTab])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // Click the install dropdown button which triggers onSwitchToMarketplaceTab
- fireEvent.click(screen.getByTestId('install-dropdown'))
-
- // The mock onSwitchToMarketplaceTab calls setActiveTab('discover')
- // Since our mock InstallPluginDropdown calls onSwitchToMarketplaceTab on click
- // we verify that setActiveTab was called with 'discover'.
- expect(mockSetActiveTab).toHaveBeenCalledWith('discover')
- })
-
- it('should use noop for file handlers when canManagement is false', () => {
- // Override mock to disable management permission
- vi.doMock('@/service/use-plugins', () => ({
- hasPluginPermission: (permission: string | undefined, isAdmin: boolean) => {
- if (!permission) return false
- if (permission === 'noone') return false
- if (permission === 'everyone') return true
- return isAdmin
- },
- useReferenceSettings: () => ({
- data: {
- permission: {
- install_permission: 'noone',
- debug_permission: 'noone',
- },
- auto_upgrade: {
- strategy_setting: 'fix_only',
- upgrade_time_of_day: 0,
- upgrade_mode: 'all',
- exclude_plugins: [],
- include_plugins: [],
- },
- },
- }),
- usePluginPermissionSettings: () => ({
- data: {
- install_permission: 'noone',
- debug_permission: 'noone',
- },
- }),
- useMutationReferenceSettings: () => ({
- mutate: vi.fn(),
- isPending: false,
- }),
- useInvalidateReferenceSettings: () => vi.fn(),
- usePluginTaskList: () => ({
- pluginTasks: [],
- handleRefetch: vi.fn(),
- }),
- useMutationClearTaskPlugin: () => ({
- mutateAsync: vi.fn(),
- }),
- useInstalledPluginList: () => ({
- data: [],
- isLoading: false,
- isFetching: false,
- isLastPage: true,
- loadNextPage: vi.fn(),
- }),
- useInstalledLatestVersion: () => ({
- data: {},
- }),
- useInvalidateInstalledPluginList: () => vi.fn(),
- }))
-
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // File input should still be in the document (even if handlers are noop)
- const fileInput = document.getElementById('fileUploader')
- expect(fileInput).toBeInTheDocument()
- })
- })
-
- // ============================================================================
- // File Upload Tests
- // ============================================================================
- describe('File Upload', () => {
- it('should have hidden file input', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const fileInput = document.getElementById('fileUploader') as HTMLInputElement
- expect(fileInput).toHaveClass('hidden')
- })
-
- it('should accept .difypkg files', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const fileInput = document.getElementById('fileUploader') as HTMLInputElement
- expect(fileInput.accept).toContain('.difypkg')
- })
-
- it('should show InstallFromLocalPackage modal when valid file is selected', async () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const fileInput = document.getElementById('fileUploader') as HTMLInputElement
-
- const file = new File(['content'], 'plugin.difypkg', { type: 'application/octet-stream' })
- Object.defineProperty(fileInput, 'files', {
- value: [file],
- })
-
- fireEvent.change(fileInput)
-
- await waitFor(() => {
- expect(screen.getByTestId('install-local-modal')).toBeInTheDocument()
- })
- })
-
- it('should not show modal for non-.difypkg files', async () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const fileInput = document.getElementById('fileUploader') as HTMLInputElement
-
- const file = new File(['content'], 'plugin.txt', { type: 'text/plain' })
- Object.defineProperty(fileInput, 'files', {
- value: [file],
- })
-
- fireEvent.change(fileInput)
-
- await waitFor(() => {
- expect(screen.queryByTestId('install-local-modal')).not.toBeInTheDocument()
- })
- })
- })
-
- // ============================================================================
- // Marketplace Installation Tests
- // ============================================================================
- describe('Marketplace Installation', () => {
- it('should fetch manifest when packageId is provided', async () => {
- const mockSetInstallState = vi.fn()
- vi.mocked(usePluginInstallation).mockReturnValue([
- { packageId: 'test-package-id', bundleInfo: null },
- mockSetInstallState,
- ])
-
- vi.mocked(fetchManifestFromMarketPlace).mockResolvedValue({
- data: {
- plugin: { org: 'test-org', name: 'test-plugin', category: 'tool' },
- version: { version: '1.0.0' },
- },
- } as unknown as Awaited<ReturnType<typeof fetchManifestFromMarketPlace>>)
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- await waitFor(() => {
- expect(fetchManifestFromMarketPlace).toHaveBeenCalledWith('test-package-id')
- })
- })
-
- it('should fetch bundle info when bundleInfo is provided', async () => {
- const mockSetInstallState = vi.fn()
- vi.mocked(usePluginInstallation).mockReturnValue([
- { packageId: null, bundleInfo: 'test-bundle-info' as unknown },
- mockSetInstallState,
- ] as ReturnType<typeof usePluginInstallation>)
-
- vi.mocked(fetchBundleInfoFromMarketPlace).mockResolvedValue({
- data: { version: { dependencies: [] } },
- } as unknown as Awaited<ReturnType<typeof fetchBundleInfoFromMarketPlace>>)
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- await waitFor(() => {
- expect(fetchBundleInfoFromMarketPlace).toHaveBeenCalledWith('test-bundle-info')
- })
- })
-
- it('should show InstallFromMarketplace modal after fetching manifest', async () => {
- const mockSetInstallState = vi.fn()
- vi.mocked(usePluginInstallation).mockReturnValue([
- { packageId: 'test-package-id', bundleInfo: null },
- mockSetInstallState,
- ])
-
- vi.mocked(fetchManifestFromMarketPlace).mockResolvedValue({
- data: {
- plugin: { org: 'test-org', name: 'test-plugin', category: 'unknown' },
- version: { version: '1.0.0' },
- },
- } as unknown as Awaited<ReturnType<typeof fetchManifestFromMarketPlace>>)
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- await waitFor(
- () => {
- expect(screen.getByTestId('install-marketplace-modal')).toBeInTheDocument()
- },
- { timeout: 3000 },
- )
- })
-
- it('should redirect supported plugin categories to integrations before opening the modal', async () => {
- const mockSetInstallState = vi.fn()
- vi.mocked(usePluginInstallation).mockReturnValue([
- { packageId: 'junjiem/mcp_see_agent:0.2.4@test', bundleInfo: null },
- mockSetInstallState,
- ])
-
- vi.mocked(fetchManifestFromMarketPlace).mockResolvedValue({
- data: {
- plugin: { org: 'junjiem', name: 'mcp_see_agent', category: 'agent-strategy' },
- version: { version: '0.2.4' },
- },
- } as unknown as Awaited<ReturnType<typeof fetchManifestFromMarketPlace>>)
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- await waitFor(() => {
- expect(mockRouterReplace).toHaveBeenCalledWith(
- '/integrations/agent-strategy?package-ids=%5B%22junjiem%2Fmcp_see_agent%3A0.2.4%40test%22%5D',
- )
- })
- expect(screen.queryByTestId('install-marketplace-modal')).not.toBeInTheDocument()
- })
-
- it('should handle fetch error gracefully', async () => {
- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
-
- vi.mocked(usePluginInstallation).mockReturnValue([
- { packageId: null, bundleInfo: 'invalid-bundle' as unknown },
- vi.fn(),
- ] as ReturnType<typeof usePluginInstallation>)
-
- vi.mocked(fetchBundleInfoFromMarketPlace).mockRejectedValue(new Error('Network error'))
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- await waitFor(() => {
- expect(consoleSpy).toHaveBeenCalledWith('Failed to load bundle info:', expect.any(Error))
- })
-
- consoleSpy.mockRestore()
- })
- })
-
- // ============================================================================
- // Settings Modal Tests
- // ============================================================================
- describe('Settings Modal', () => {
- it('should open settings modal when settings button is clicked', async () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- fireEvent.click(screen.getByRole('button', { name: /plugin\.privilege\.title/i }))
-
- await waitFor(() => {
- expect(screen.getByTestId('reference-setting-modal')).toBeInTheDocument()
- })
- })
-
- it('should close settings modal when onHide is called', async () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // Open modal
- fireEvent.click(screen.getByRole('button', { name: /plugin\.privilege\.title/i }))
-
- await waitFor(() => {
- expect(screen.getByTestId('reference-setting-modal')).toBeInTheDocument()
- })
-
- // Close modal
- fireEvent.click(screen.getByText('Close Settings'))
-
- await waitFor(() => {
- expect(screen.queryByTestId('reference-setting-modal')).not.toBeInTheDocument()
- })
- })
- })
-
- // ============================================================================
- // Drag and Drop Tests
- // ============================================================================
- describe('Drag and Drop', () => {
- it('should show dragging overlay when dragging files over container', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const container = document.getElementById('marketplace-container')!
-
- // Simulate drag enter
- const dragEnterEvent = new Event('dragenter', { bubbles: true })
- Object.defineProperty(dragEnterEvent, 'dataTransfer', {
- value: { types: ['Files'] },
- })
- container.dispatchEvent(dragEnterEvent)
-
- // Check for dragging overlay styles
- expect(container).toBeInTheDocument()
- })
-
- it('should highlight drop zone text when dragging', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // The drag hint should be visible
- const dragHint = screen.getByText(/dropPluginToInstall/i)
- expect(dragHint).toBeInTheDocument()
- })
- })
-
- // ============================================================================
- // Memoization Tests
- // ============================================================================
- describe('Memoization', () => {
- it('should recognize plugin type tabs as marketplace', () => {
- // Test with a plugin type tab like 'tool'
- vi.mocked(useQueryState).mockReturnValue(['tool', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // Should show marketplace links when on a plugin type tab
- expect(screen.getByText(/requestAPlugin/i)).toBeInTheDocument()
- expect(screen.getByText(/publishPlugins/i)).toBeInTheDocument()
- })
-
- it('should render marketplace content when isExploringMarketplace and enable_marketplace are true', () => {
- vi.mocked(useQueryState).mockReturnValue(['discover', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // The marketplace prop content should be rendered
- // Since we mock the marketplace as a div, check it's not hidden
- const container = document.getElementById('marketplace-container')
- expect(container).toBeInTheDocument()
- expect(container).toHaveClass('bg-background-body')
- })
- })
-
- // ============================================================================
- // Context Provider Tests
- // ============================================================================
- describe('Context Provider', () => {
- it('should wrap component with PluginPageContextProvider', () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // The component should render, indicating context is working
- expect(document.getElementById('marketplace-container')).toBeInTheDocument()
- })
-
- it('should filter out marketplace tab when enable_marketplace is false', () => {
- // This tests line 69 in context.tsx - the false branch of enable_marketplace
- // The marketplace tab should be filtered out from options
- render(<PluginPageWithContext {...createDefaultProps()} />)
- // Component should still work without marketplace
- expect(document.getElementById('marketplace-container')).toBeInTheDocument()
- })
- })
-
- // ============================================================================
- // Edge Cases and Error Handling
- // ============================================================================
- describe('Edge Cases', () => {
- it('should handle null plugins prop', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext plugins={null} marketplace={null} />)
- expect(document.getElementById('marketplace-container')).toBeInTheDocument()
- })
-
- it('should handle empty marketplace prop', () => {
- vi.mocked(useQueryState).mockReturnValue(['discover', vi.fn()])
-
- render(<PluginPageWithContext plugins={null} marketplace={null} />)
- expect(document.getElementById('marketplace-container')).toBeInTheDocument()
- })
-
- it('should handle rapid tab switches', async () => {
- const mockSetActiveTab = vi.fn()
- vi.mocked(useQueryState).mockReturnValue(['plugins', mockSetActiveTab])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // Simulate rapid switches by updating state
- act(() => {
- vi.mocked(useQueryState).mockReturnValue(['discover', mockSetActiveTab])
- })
-
- expect(document.getElementById('marketplace-container')).toBeInTheDocument()
- })
-
- it('should handle marketplace disabled', () => {
- mockEnableMarketplace = false
- vi.mocked(useQueryState).mockReturnValue(['discover', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // Component should still render but without marketplace content when disabled
- expect(document.getElementById('marketplace-container')).toBeInTheDocument()
- })
-
- it('should handle file with empty name', async () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const fileInput = document.getElementById('fileUploader') as HTMLInputElement
-
- const file = new File(['content'], '', { type: 'application/octet-stream' })
- Object.defineProperty(fileInput, 'files', {
- value: [file],
- })
-
- fireEvent.change(fileInput)
-
- // Should not show modal for file without proper extension
- await waitFor(() => {
- expect(screen.queryByTestId('install-local-modal')).not.toBeInTheDocument()
- })
- })
-
- it('should handle no files selected', async () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const fileInput = document.getElementById('fileUploader') as HTMLInputElement
-
- Object.defineProperty(fileInput, 'files', {
- value: [],
- })
-
- fireEvent.change(fileInput)
-
- // Should not show modal
- expect(screen.queryByTestId('install-local-modal')).not.toBeInTheDocument()
- })
- })
-
- // ============================================================================
- // Cleanup Tests
- // ============================================================================
- describe('Cleanup', () => {
- it('should reset install state when hiding marketplace modal', async () => {
- const mockSetInstallState = vi.fn()
- vi.mocked(usePluginInstallation).mockReturnValue([
- { packageId: 'test-package', bundleInfo: null },
- mockSetInstallState,
- ])
-
- vi.mocked(fetchManifestFromMarketPlace).mockResolvedValue({
- data: {
- plugin: { org: 'test-org', name: 'test-plugin', category: 'unknown' },
- version: { version: '1.0.0' },
- },
- } as unknown as Awaited<ReturnType<typeof fetchManifestFromMarketPlace>>)
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // Wait for modal to appear
- await waitFor(
- () => {
- expect(screen.getByTestId('install-marketplace-modal')).toBeInTheDocument()
- },
- { timeout: 3000 },
- )
-
- // Close modal
- fireEvent.click(screen.getByText('Close'))
-
- await waitFor(() => {
- expect(mockSetInstallState).toHaveBeenCalledWith(null)
- })
- })
- })
-
- // ============================================================================
- // Styling Tests
- // ============================================================================
- describe('Styling', () => {
- it('should apply correct background for plugins tab', () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const container = document.getElementById('marketplace-container')
-
- expect(container).toHaveClass('bg-components-panel-bg')
- })
-
- it('should apply correct background for marketplace tab', () => {
- vi.mocked(useQueryState).mockReturnValue(['discover', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const container = document.getElementById('marketplace-container')
-
- expect(container).toHaveClass('bg-background-body')
- })
- })
-})
-
-// ============================================================================
-// Uploader Hook Integration Tests
-// ============================================================================
-describe('Uploader Hook Integration', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
- })
-
- describe('Drag Events', () => {
- it('should handle dragover event', async () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const container = document.getElementById('marketplace-container')!
-
- const dragOverEvent = new Event('dragover', { bubbles: true, cancelable: true })
- Object.defineProperty(dragOverEvent, 'dataTransfer', {
- value: { types: ['Files'] },
- })
-
- act(() => {
- container.dispatchEvent(dragOverEvent)
- })
-
- expect(container).toBeInTheDocument()
- })
-
- it('should handle dragleave event when leaving container', async () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const container = document.getElementById('marketplace-container')!
-
- const dragEnterEvent = new Event('dragenter', { bubbles: true })
- Object.defineProperty(dragEnterEvent, 'dataTransfer', {
- value: { types: ['Files'] },
- })
- act(() => {
- container.dispatchEvent(dragEnterEvent)
- })
-
- const dragLeaveEvent = new Event('dragleave', { bubbles: true })
- Object.defineProperty(dragLeaveEvent, 'relatedTarget', {
- value: null,
- })
- act(() => {
- container.dispatchEvent(dragLeaveEvent)
- })
-
- expect(container).toBeInTheDocument()
- })
-
- it('should handle dragleave event when moving to element outside container', async () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const container = document.getElementById('marketplace-container')!
-
- const dragEnterEvent = new Event('dragenter', { bubbles: true })
- Object.defineProperty(dragEnterEvent, 'dataTransfer', {
- value: { types: ['Files'] },
- })
- act(() => {
- container.dispatchEvent(dragEnterEvent)
- })
-
- const outsideElement = document.createElement('div')
- document.body.appendChild(outsideElement)
-
- const dragLeaveEvent = new Event('dragleave', { bubbles: true })
- Object.defineProperty(dragLeaveEvent, 'relatedTarget', {
- value: outsideElement,
- })
- act(() => {
- container.dispatchEvent(dragLeaveEvent)
- })
-
- expect(container).toBeInTheDocument()
- document.body.removeChild(outsideElement)
- })
-
- it('should handle drop event with files', async () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const container = document.getElementById('marketplace-container')!
-
- const dragEnterEvent = new Event('dragenter', { bubbles: true })
- Object.defineProperty(dragEnterEvent, 'dataTransfer', {
- value: { types: ['Files'] },
- })
- act(() => {
- container.dispatchEvent(dragEnterEvent)
- })
-
- const file = new File(['content'], 'test-plugin.difypkg', {
- type: 'application/octet-stream',
- })
- const dropEvent = new Event('drop', { bubbles: true, cancelable: true })
- Object.defineProperty(dropEvent, 'dataTransfer', {
- value: { files: [file] },
- })
-
- act(() => {
- container.dispatchEvent(dropEvent)
- })
-
- await waitFor(() => {
- expect(screen.getByTestId('install-local-modal')).toBeInTheDocument()
- })
- })
-
- it('should handle drop event without dataTransfer', async () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const container = document.getElementById('marketplace-container')!
-
- const dropEvent = new Event('drop', { bubbles: true, cancelable: true })
-
- act(() => {
- container.dispatchEvent(dropEvent)
- })
-
- expect(screen.queryByTestId('install-local-modal')).not.toBeInTheDocument()
- })
-
- it('should handle drop event with empty files array', async () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const container = document.getElementById('marketplace-container')!
-
- const dropEvent = new Event('drop', { bubbles: true, cancelable: true })
- Object.defineProperty(dropEvent, 'dataTransfer', {
- value: { files: [] },
- })
-
- act(() => {
- container.dispatchEvent(dropEvent)
- })
-
- expect(screen.queryByTestId('install-local-modal')).not.toBeInTheDocument()
- })
- })
-
- describe('File Change Handler', () => {
- it('should handle file change with null file', async () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const fileInput = document.getElementById('fileUploader') as HTMLInputElement
-
- Object.defineProperty(fileInput, 'files', { value: null })
-
- fireEvent.change(fileInput)
-
- expect(screen.queryByTestId('install-local-modal')).not.toBeInTheDocument()
- })
- })
-
- describe('Remove File', () => {
- it('should clear file input when removeFile is called', async () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- const fileInput = document.getElementById('fileUploader') as HTMLInputElement
-
- const file = new File(['content'], 'plugin.difypkg', { type: 'application/octet-stream' })
- Object.defineProperty(fileInput, 'files', { value: [file] })
- fireEvent.change(fileInput)
-
- await waitFor(() => {
- expect(screen.getByTestId('install-local-modal')).toBeInTheDocument()
- })
-
- fireEvent.click(screen.getByText('Close'))
-
- await waitFor(() => {
- expect(screen.queryByTestId('install-local-modal')).not.toBeInTheDocument()
- })
- })
- })
-})
-
-// ============================================================================
-// Reference Setting Hook Integration Tests
-// ============================================================================
-describe('Reference Setting Hook Integration', () => {
- describe('Permission Handling', () => {
- it('should render InstallPluginDropdown when permission is everyone', () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(screen.getByTestId('install-dropdown')).toBeInTheDocument()
- })
-
- it('should render DebugInfo when permission is admins and user is manager', () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(screen.getByTestId('debug-info')).toBeInTheDocument()
- })
- })
-})
-
-// ============================================================================
-// Marketplace Installation Permission Tests
-// ============================================================================
-describe('Marketplace Installation Permission', () => {
- it('should show InstallPluginDropdown when marketplace is enabled and has permission', () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
- expect(screen.getByTestId('install-dropdown')).toBeInTheDocument()
- })
-})
-
-// ============================================================================
-// Integration Tests
-// ============================================================================
-describe('PluginPage Integration', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- vi.mocked(usePluginInstallation).mockReturnValue([
- { packageId: null, bundleInfo: null },
- vi.fn(),
- ])
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
- })
-
- it('should render complete plugin page with all features', () => {
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // Check all major elements are present
- expect(document.getElementById('marketplace-container')).toBeInTheDocument()
- expect(screen.getByTestId('plugin-tasks')).toBeInTheDocument()
- expect(screen.getByTestId('install-dropdown')).toBeInTheDocument()
- expect(screen.getByTestId('debug-info')).toBeInTheDocument()
- expect(screen.getByTestId('plugins-content')).toBeInTheDocument()
- })
-
- it('should handle full install from marketplace flow', async () => {
- const mockSetInstallState = vi.fn()
- vi.mocked(usePluginInstallation).mockReturnValue([
- { packageId: 'test-package', bundleInfo: null },
- mockSetInstallState,
- ])
-
- vi.mocked(fetchManifestFromMarketPlace).mockResolvedValue({
- data: {
- plugin: { org: 'langgenius', name: 'test-plugin', category: 'unknown' },
- version: { version: '1.0.0' },
- },
- } as unknown as Awaited<ReturnType<typeof fetchManifestFromMarketPlace>>)
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // Wait for API call
- await waitFor(() => {
- expect(fetchManifestFromMarketPlace).toHaveBeenCalled()
- })
-
- // Wait for modal
- await waitFor(
- () => {
- expect(screen.getByTestId('install-marketplace-modal')).toBeInTheDocument()
- },
- { timeout: 3000 },
- )
-
- // Close modal
- fireEvent.click(screen.getByText('Close'))
-
- // Verify state reset
- await waitFor(() => {
- expect(mockSetInstallState).toHaveBeenCalledWith(null)
- })
- })
-
- it('should handle full local plugin install flow', async () => {
- vi.mocked(useQueryState).mockReturnValue(['plugins', vi.fn()])
-
- render(<PluginPageWithContext {...createDefaultProps()} />)
-
- const fileInput = document.getElementById('fileUploader') as HTMLInputElement
- const file = new File(['plugin content'], 'my-plugin.difypkg', {
- type: 'application/octet-stream',
- })
-
- Object.defineProperty(fileInput, 'files', { value: [file] })
- fireEvent.change(fileInput)
-
- await waitFor(() => {
- expect(screen.getByTestId('install-local-modal')).toBeInTheDocument()
- })
-
- // Close modal (triggers removeFile via onClose)
- fireEvent.click(screen.getByText('Close'))
-
- await waitFor(() => {
- expect(screen.queryByTestId('install-local-modal')).not.toBeInTheDocument()
- })
- })
-
- it('should render marketplace content only when enable_marketplace is true', () => {
- vi.mocked(useQueryState).mockReturnValue(['discover', vi.fn()])
-
- const { rerender } = render(<PluginPageWithContext {...createDefaultProps()} />)
-
- // With enable_marketplace: true (default mock), marketplace links should show
- expect(screen.getByText(/requestAPlugin/i)).toBeInTheDocument()
-
- // Rerender to verify consistent behavior
- rerender(<PluginPageWithContext {...createDefaultProps()} />)
- expect(screen.getByText(/publishPlugins/i)).toBeInTheDocument()
- })
-})
diff --git a/web/app/components/plugins/plugin-page/index.tsx b/web/app/components/plugins/plugin-page/index.tsx
deleted file mode 100644
index 3a36218fcbb..00000000000
--- a/web/app/components/plugins/plugin-page/index.tsx
+++ /dev/null
@@ -1,331 +0,0 @@
-'use client'
-
-import type { PluginPageTab } from './context'
-import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
-import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { RiBookOpenLine, RiBugLine, RiDragDropLine, RiEqualizer2Line } from '@remixicon/react'
-import { useSuspenseQuery } from '@tanstack/react-query'
-import { useBoolean } from 'ahooks'
-import { noop } from 'es-toolkit/function'
-import { cloneElement, isValidElement, useCallback, useMemo, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import TabSlider from '@/app/components/base/tab-slider'
-import ReferenceSettingModal from '@/app/components/plugins/reference-setting-modal'
-import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
-import { useDocLink } from '@/context/i18n'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
-import useDocumentTitle from '@/hooks/use-document-title'
-import Link from '@/next/link'
-import { useRouter } from '@/next/navigation'
-import { PLUGIN_PAGE_TABS_MAP } from '../hooks'
-import { PluginInstallPermissionProvider } from '../install-plugin/components/plugin-install-permission-provider'
-import InstallFromLocalPackage from '../install-plugin/install-from-local-package'
-import InstallFromMarketplaceQuery from '../install-plugin/install-from-marketplace-query'
-import { PLUGIN_TYPE_SEARCH_MAP } from '../marketplace/constants'
-import { getInstallRedirectPathByPluginCategory } from '../plugin-routes'
-import { PluginCategoryEnum } from '../types'
-import { usePluginPageContext } from './context'
-import { PluginPageContextProvider } from './context-provider'
-import DebugInfo from './debug-info'
-import InstallPluginDropdown from './install-plugin-dropdown'
-import PluginTasks from './plugin-tasks'
-import useReferenceSetting from './use-reference-setting'
-import { useUploader } from './use-uploader'
-
-const pluginPageTabSet = new Set<string>([
- PLUGIN_PAGE_TABS_MAP.plugins,
- PLUGIN_PAGE_TABS_MAP.marketplace,
- ...Object.values(PLUGIN_TYPE_SEARCH_MAP),
-])
-
-const isPluginPageTab = (value: string): value is PluginPageTab => {
- return pluginPageTabSet.has(value)
-}
-
-const getCurrentInstallSearchParams = (packageId: string) => {
- const searchParams: Record<string, string | string[]> = {}
-
- new URLSearchParams(window.location.search).forEach((value, key) => {
- const existing = searchParams[key]
- if (existing === undefined) {
- searchParams[key] = value
- return
- }
-
- if (Array.isArray(existing)) {
- existing.push(value)
- return
- }
-
- searchParams[key] = [existing, value]
- })
-
- searchParams['package-ids'] ??= JSON.stringify([packageId])
-
- return searchParams
-}
-
-export type PluginPageProps = {
- plugins: React.ReactNode
- marketplace: React.ReactNode
-}
-type PluginPanelPermissionProps = {
- canInstall?: boolean
- canDeletePlugin?: boolean
- canUpdatePlugin?: boolean
-}
-const PluginPage = ({ plugins, marketplace }: PluginPageProps) => {
- const { t } = useTranslation()
- const docLink = useDocLink()
- const { replace } = useRouter()
-
- const {
- referenceSetting,
- canInstallPlugin,
- canUpdatePlugin,
- canDeletePlugin,
- canDebugger,
- canSetPermissions,
- canSetPluginPreferences,
- currentDifyVersion,
- isPermissionLoading,
- isReferenceSettingLoading,
- setReferenceSettings,
- } = useReferenceSetting(PluginCategoryEnum.tool)
-
- const handlePackageCategoryResolved = useCallback(
- (category: string | undefined, packageId: string) => {
- const installRedirectPath = getInstallRedirectPathByPluginCategory(
- category,
- getCurrentInstallSearchParams(packageId),
- )
- if (!installRedirectPath) return false
-
- replace(installRedirectPath)
- return true
- },
- [replace],
- )
-
- const [
- showPluginSettingModal,
- { setTrue: setShowPluginSettingModal, setFalse: setHidePluginSettingModal },
- ] = useBoolean(false)
- const [currentFile, setCurrentFile] = useState<File | null>(null)
- const containerRef = usePluginPageContext((v) => v.containerRef)
- const options = usePluginPageContext((v) => v.options)
- const activeTab = usePluginPageContext((v) => v.activeTab)
- const setActiveTab = usePluginPageContext((v) => v.setActiveTab)
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
-
- const isPluginsTab = useMemo(() => activeTab === PLUGIN_PAGE_TABS_MAP.plugins, [activeTab])
- const isExploringMarketplace = useMemo(() => {
- const values = Object.values(PLUGIN_TYPE_SEARCH_MAP)
- return activeTab === PLUGIN_PAGE_TABS_MAP.marketplace || values.includes(activeTab)
- }, [activeTab])
- useDocumentTitle(
- isExploringMarketplace
- ? t(($) => $['mainNav.marketplace'], { ns: 'common' })
- : t(($) => $['metadata.title'], { ns: 'plugin' }),
- )
-
- const handleFileChange = (file: File | null) => {
- if (!canInstallPlugin) {
- setCurrentFile(null)
- return
- }
-
- if (!file || !file.name.endsWith('.difypkg')) {
- setCurrentFile(null)
- return
- }
-
- setCurrentFile(file)
- }
- const uploaderProps = useUploader({
- onFileChange: handleFileChange,
- containerRef,
- enabled: isPluginsTab && canInstallPlugin,
- })
-
- const { dragging, fileUploader, fileChangeHandle, removeFile } = uploaderProps
- const pluginsWithPermission = useMemo(() => {
- if (!isValidElement(plugins) || typeof plugins.type === 'string') return plugins
-
- return cloneElement(plugins as React.ReactElement<PluginPanelPermissionProps>, {
- canInstall: canInstallPlugin,
- canDeletePlugin,
- canUpdatePlugin,
- })
- }, [canInstallPlugin, canDeletePlugin, canUpdatePlugin, plugins])
-
- return (
- <div
- id="marketplace-container"
- ref={containerRef}
- style={{ scrollbarGutter: 'stable' }}
- className={cn(
- 'relative flex grow flex-col overflow-y-auto border-t border-divider-subtle',
- isPluginsTab ? 'rounded-t-xl bg-components-panel-bg' : 'bg-background-body',
- )}
- >
- <div
- className={cn(
- 'sticky top-0 z-10 flex min-h-15 items-center gap-1 self-stretch bg-components-panel-bg px-12 pt-4 pb-2',
- isExploringMarketplace && 'bg-background-body',
- )}
- >
- <div className="flex w-full items-center justify-between">
- <div className="flex-1">
- <TabSlider
- value={isPluginsTab ? PLUGIN_PAGE_TABS_MAP.plugins : PLUGIN_PAGE_TABS_MAP.marketplace}
- onChange={(nextTab) => {
- if (isPluginPageTab(nextTab)) setActiveTab(nextTab)
- }}
- options={options}
- />
- </div>
- <div className="flex shrink-0 items-center gap-1">
- {isExploringMarketplace && (
- <>
- <Link
- href="https://github.com/langgenius/dify-plugins/issues/new?template=plugin_request.yaml"
- target="_blank"
- >
- <Button variant="ghost" className="text-text-tertiary">
- {t(($) => $.requestAPlugin, { ns: 'plugin' })}
- </Button>
- </Link>
- <Link
- href={docLink(
- '/develop-plugin/publishing/marketplace-listing/release-to-dify-marketplace',
- )}
- target="_blank"
- >
- <Button className="px-3" variant="secondary-accent">
- <RiBookOpenLine className="size-4" />
- {t(($) => $.publishPlugins, { ns: 'plugin' })}
- </Button>
- </Link>
- <div className="mx-1 h-3.5 w-px shrink-0 bg-divider-regular"></div>
- </>
- )}
- <PluginTasks />
- {(canInstallPlugin || isPermissionLoading) && (
- <InstallPluginDropdown
- disabled={isPermissionLoading || !canInstallPlugin}
- onSwitchToMarketplaceTab={() => setActiveTab('discover')}
- />
- )}
- {canDebugger && <DebugInfo />}
- {isPermissionLoading && (
- <Button
- className="h-full w-full p-2 text-components-button-secondary-text"
- disabled
- loading
- >
- <RiBugLine className="h-4 w-4" />
- </Button>
- )}
- {(canSetPermissions || canSetPluginPreferences) && (
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- aria-label={t(($) => $['privilege.title'], { ns: 'plugin' })}
- className="group size-full p-2 text-components-button-secondary-text"
- disabled={isReferenceSettingLoading || !referenceSetting}
- loading={isReferenceSettingLoading}
- onClick={setShowPluginSettingModal}
- >
- <RiEqualizer2Line className="size-4" aria-hidden="true" />
- </Button>
- }
- />
- <TooltipContent>{t(($) => $['privilege.title'], { ns: 'plugin' })}</TooltipContent>
- </Tooltip>
- )}
- </div>
- </div>
- </div>
- {isPluginsTab && (
- <>
- <PluginInstallPermissionProvider
- canInstallPlugin={canInstallPlugin}
- canUpdatePlugin={canUpdatePlugin}
- currentDifyVersion={currentDifyVersion}
- >
- {pluginsWithPermission}
- </PluginInstallPermissionProvider>
- {dragging && (
- <div className="absolute inset-0 m-0.5 rounded-2xl border-2 border-dashed border-components-dropzone-border-accent bg-[rgba(21,90,239,0.14)] p-2"></div>
- )}
- {canInstallPlugin && (
- <div
- className={`flex items-center justify-center gap-2 py-4 ${dragging ? 'text-text-accent' : 'text-text-quaternary'}`}
- >
- <RiDragDropLine className="size-4" />
- <span className="system-xs-regular">
- {t(($) => $['installModal.dropPluginToInstall'], { ns: 'plugin' })}
- </span>
- </div>
- )}
- {currentFile && (
- <InstallFromLocalPackage
- file={currentFile}
- onClose={removeFile ?? noop}
- onSuccess={noop}
- />
- )}
- <input
- ref={fileUploader}
- className="hidden"
- type="file"
- id="fileUploader"
- accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
- onChange={fileChangeHandle ?? noop}
- />
- </>
- )}
- {isExploringMarketplace && enable_marketplace && (
- <PluginInstallPermissionProvider
- canInstallPlugin={canInstallPlugin}
- canUpdatePlugin={canUpdatePlugin}
- currentDifyVersion={currentDifyVersion}
- >
- {marketplace}
- </PluginInstallPermissionProvider>
- )}
-
- {showPluginSettingModal && referenceSetting && (
- <ReferenceSettingModal
- payload={referenceSetting}
- canSetPermissions={canSetPermissions}
- canSetAutoUpdate={canSetPluginPreferences}
- onHide={setHidePluginSettingModal}
- onSave={setReferenceSettings}
- />
- )}
-
- <InstallFromMarketplaceQuery
- canInstallPlugin={canInstallPlugin}
- isPermissionLoading={isPermissionLoading}
- onPackageCategoryResolved={handlePackageCategoryResolved}
- />
- </div>
- )
-}
-
-const PluginPageWithContext = (props: PluginPageProps) => {
- return (
- <PluginPageContextProvider>
- <PluginPage {...props} />
- </PluginPageContextProvider>
- )
-}
-
-export default PluginPageWithContext
diff --git a/web/app/components/plugins/plugin-routes.ts b/web/app/components/plugins/plugin-routes.ts
index bf8d7fbf52e..dcfd6614b2b 100644
--- a/web/app/components/plugins/plugin-routes.ts
+++ b/web/app/components/plugins/plugin-routes.ts
@@ -142,9 +142,6 @@ const buildMarketplaceRedirectPath = (searchParams: LegacyPluginsSearchParams, t
export const getLegacyPluginRedirectPath = (searchParams: LegacyPluginsSearchParams = {}) => {
const tab = getFirstSearchParamValue(searchParams.tab)
- if ((!tab || tab === INSTALLED_PLUGINS_TAB) && hasInstallSearchParams(searchParams))
- return undefined
-
if (!tab || tab === INSTALLED_PLUGINS_TAB) return '/integrations'
const integrationPluginPath = getIntegrationPluginPathByTab(tab)
@@ -156,5 +153,5 @@ export const getLegacyPluginRedirectPath = (searchParams: LegacyPluginsSearchPar
if (marketplacePluginTabs.has(tab)) return buildMarketplaceRedirectPath(searchParams, tab)
- return undefined
+ return '/integrations'
}
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
deleted file mode 100644
index 83398241363..00000000000
--- a/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,968 +0,0 @@
-import type { ReactElement } from 'react'
-import type { AutoUpdateConfig } from '../auto-update-setting/types'
-import type { Permissions, ReferenceSetting } from '@/app/components/plugins/types'
-import { fireEvent, screen, waitFor } from '@testing-library/react'
-import * as React from 'react'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { PermissionType } from '@/app/components/plugins/types'
-import { renderWithConsoleQuery } from '@/test/console/query-data'
-import { AUTO_UPDATE_MODE, AUTO_UPDATE_STRATEGY } from '../auto-update-setting/types'
-import ReferenceSettingModal from '../index'
-
-const mockSystemFeatures = {
- enable_marketplace: true,
- rbac_enabled: false,
-}
-
-const render = (ui: ReactElement) =>
- renderWithConsoleQuery(ui, { systemFeatures: mockSystemFeatures })
-
-// Mock OptionCard component
-vi.mock('@/app/components/workflow/nodes/_base/components/option-card', () => ({
- default: ({
- title,
- onSelect,
- selected,
- className,
- disabled,
- tooltip,
- }: {
- title: string
- onSelect: () => void
- selected: boolean
- className?: string
- disabled?: boolean
- tooltip?: string
- }) => (
- <button
- data-testid={`option-card-${title.toLowerCase().replace(/\s+/g, '-')}`}
- onClick={() => {
- if (!disabled) onSelect()
- }}
- aria-pressed={selected}
- disabled={disabled}
- className={className}
- >
- {title}
- {tooltip && <span>{tooltip}</span>}
- </button>
- ),
-}))
-
-// Mock AutoUpdateSetting component
-const mockAutoUpdateSettingOnChange = vi.fn()
-vi.mock('../auto-update-setting', () => ({
- default: ({
- payload,
- onChange,
- }: {
- payload: AutoUpdateConfig
- onChange: (payload: AutoUpdateConfig) => void
- }) => {
- mockAutoUpdateSettingOnChange.mockImplementation(onChange)
- return (
- <div data-testid="auto-update-setting">
- <span data-testid="auto-update-strategy">{payload.strategy_setting}</span>
- <span data-testid="auto-update-mode">{payload.upgrade_mode}</span>
- <button
- data-testid="auto-update-change"
- onClick={() =>
- onChange({
- ...payload,
- strategy_setting: AUTO_UPDATE_STRATEGY.latest,
- })
- }
- >
- Change Strategy
- </button>
- </div>
- )
- },
-}))
-
-// ================================
-// Test Data Factories
-// ================================
-
-const createMockPermissions = (overrides: Partial<Permissions> = {}): Permissions => ({
- install_permission: PermissionType.everyone,
- debug_permission: PermissionType.admin,
- ...overrides,
-})
-
-const createMockAutoUpdateConfig = (
- overrides: Partial<AutoUpdateConfig> = {},
-): AutoUpdateConfig => ({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_time_of_day: 36000,
- upgrade_mode: AUTO_UPDATE_MODE.update_all,
- exclude_plugins: [],
- include_plugins: [],
- ...overrides,
-})
-
-const createMockReferenceSetting = (
- overrides: Partial<ReferenceSetting> = {},
-): ReferenceSetting => ({
- permission: createMockPermissions(),
- auto_upgrade: createMockAutoUpdateConfig(),
- ...overrides,
-})
-
-// ================================
-// Test Suites
-// ================================
-
-describe('reference-setting-modal', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockSystemFeatures.enable_marketplace = true
- mockSystemFeatures.rbac_enabled = false
- })
-
- // Label component tests moved to label.spec.tsx
-
- // ============================================================
- // ReferenceSettingModal (PluginSettingModal) Component Tests
- // ============================================================
- describe('ReferenceSettingModal (index.tsx)', () => {
- const defaultProps = {
- payload: createMockReferenceSetting(),
- canSetPermissions: true,
- canSetAutoUpdate: true,
- onHide: vi.fn(),
- onSave: vi.fn(),
- }
-
- describe('Rendering', () => {
- it('should render modal with correct title', () => {
- // Arrange & Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert
- // Assert
- expect(screen.getByText('plugin.privilege.title'))!.toBeInTheDocument()
- })
-
- it('should render install permission section', () => {
- // Arrange & Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert
- // Assert
- expect(screen.getByText('plugin.privilege.whoCanInstall'))!.toBeInTheDocument()
- })
-
- it('should render debug permission section', () => {
- // Arrange & Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert
- // Assert
- expect(screen.getByText('plugin.privilege.whoCanDebug'))!.toBeInTheDocument()
- })
-
- it('should render all permission options for install', () => {
- // Arrange & Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert - should have 6 option cards total (3 for install, 3 for debug)
- expect(screen.getAllByTestId(/option-card/)).toHaveLength(6)
- })
-
- it('should render cancel and save buttons', () => {
- // Arrange & Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert
- // Assert
- expect(screen.getByText('common.operation.cancel'))!.toBeInTheDocument()
- expect(screen.getByText('common.operation.save'))!.toBeInTheDocument()
- })
-
- it('should render AutoUpdateSetting when marketplace is enabled', () => {
- // Arrange
- mockSystemFeatures.enable_marketplace = true
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('auto-update-setting'))!.toBeInTheDocument()
- })
-
- it('should not render AutoUpdateSetting when marketplace is disabled', () => {
- // Arrange
- mockSystemFeatures.enable_marketplace = false
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- // Assert
- expect(screen.queryByTestId('auto-update-setting')).not.toBeInTheDocument()
- })
-
- it('should hide permission controls when permission editing is disabled', () => {
- render(<ReferenceSettingModal {...defaultProps} canSetPermissions={false} />)
-
- expect(screen.queryByText('plugin.privilege.whoCanInstall')).not.toBeInTheDocument()
- expect(screen.queryByText('plugin.privilege.whoCanDebug')).not.toBeInTheDocument()
- })
-
- it('should hide AutoUpdateSetting when auto update editing is disabled', () => {
- render(<ReferenceSettingModal {...defaultProps} canSetAutoUpdate={false} />)
-
- expect(screen.queryByTestId('auto-update-setting')).not.toBeInTheDocument()
- })
-
- it('should render modal with closable attribute', () => {
- // Arrange & Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert
- // Assert
- expect(screen.getByRole('button', { name: 'Close' }))!.toBeInTheDocument()
- })
-
- it('should disable permission controls with settings permissions tooltip beside titles when RBAC is enabled', () => {
- mockSystemFeatures.rbac_enabled = true
-
- render(<ReferenceSettingModal {...defaultProps} />)
-
- expect(
- screen.getAllByLabelText('plugin.privilege.configurePermissionsInSettings'),
- ).toHaveLength(2)
- expect(
- screen.queryByText('plugin.privilege.configurePermissionsInSettings'),
- ).not.toBeInTheDocument()
- expect(
- screen.getAllByTestId(/option-card/).every((option) => option.hasAttribute('disabled')),
- ).toBe(true)
- })
- })
-
- describe('State Management', () => {
- it('should initialize with payload permission values', () => {
- // Arrange
- const payload = createMockReferenceSetting({
- permission: {
- install_permission: PermissionType.admin,
- debug_permission: PermissionType.noOne,
- },
- })
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} payload={payload} />)
-
- // Assert - admin option should be selected for install (first one)
- const adminOptions = screen.getAllByTestId('option-card-plugin.privilege.admins')
- expect(adminOptions[0])!.toHaveAttribute('aria-pressed', 'true') // Install permission
-
- // Assert - noOne option should be selected for debug (second one)
- const noOneOptions = screen.getAllByTestId('option-card-plugin.privilege.noone')
- expect(noOneOptions[1])!.toHaveAttribute('aria-pressed', 'true') // Debug permission
- })
-
- it('should update tempPrivilege when permission option is clicked', () => {
- // Arrange
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Act - click on "No One" for install permission
- const noOneOptions = screen.getAllByTestId('option-card-plugin.privilege.noone')
- fireEvent.click(noOneOptions[0]!) // First one is for install permission
-
- // Assert - the option should now be selected
- // Assert - the option should now be selected
- expect(noOneOptions[0])!.toHaveAttribute('aria-pressed', 'true')
- })
-
- it('should not update permission when RBAC disables permission controls', () => {
- mockSystemFeatures.rbac_enabled = true
- render(<ReferenceSettingModal {...defaultProps} />)
-
- const noOneOptions = screen.getAllByTestId('option-card-plugin.privilege.noone')
- fireEvent.click(noOneOptions[0]!)
-
- expect(noOneOptions[0])!.toHaveAttribute('aria-pressed', 'false')
- })
-
- it('should initialize with payload auto_upgrade values', () => {
- // Arrange
- const payload = createMockReferenceSetting({
- auto_upgrade: createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.latest,
- }),
- })
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} payload={payload} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('auto-update-strategy'))!.toHaveTextContent('latest')
- })
- })
-
- describe('User Interactions', () => {
- it('should call onHide when cancel button is clicked', () => {
- // Arrange
- const onHide = vi.fn()
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} onHide={onHide} />)
- fireEvent.click(screen.getByText('common.operation.cancel'))
-
- // Assert
- expect(onHide).toHaveBeenCalledTimes(1)
- })
-
- it('should call onHide when modal close button is clicked', () => {
- // Arrange
- const onHide = vi.fn()
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} onHide={onHide} />)
- fireEvent.click(screen.getByRole('button', { name: 'Close' }))
-
- // Assert
- expect(onHide).toHaveBeenCalledTimes(1)
- })
-
- it('should call onSave with correct payload when save button is clicked', async () => {
- // Arrange
- const onSave = vi.fn().mockResolvedValue(undefined)
- const onHide = vi.fn()
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} onSave={onSave} onHide={onHide} />)
- fireEvent.click(screen.getByText('common.operation.save'))
-
- // Assert
- await waitFor(() => {
- expect(onSave).toHaveBeenCalledWith(
- expect.objectContaining({
- permission: expect.any(Object),
- auto_upgrade: expect.any(Object),
- }),
- )
- })
- })
-
- it('should call onHide after successful save', async () => {
- // Arrange
- const onSave = vi.fn().mockResolvedValue(undefined)
- const onHide = vi.fn()
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} onSave={onSave} onHide={onHide} />)
- fireEvent.click(screen.getByText('common.operation.save'))
-
- // Assert
- await waitFor(() => {
- expect(onHide).toHaveBeenCalledTimes(1)
- })
- })
-
- it('should update install permission when Everyone option is clicked', () => {
- // Arrange
- const payload = createMockReferenceSetting({
- permission: {
- install_permission: PermissionType.noOne,
- debug_permission: PermissionType.noOne,
- },
- })
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} payload={payload} />)
-
- // Click Everyone for install permission
- const everyoneOptions = screen.getAllByTestId('option-card-plugin.privilege.everyone')
- fireEvent.click(everyoneOptions[0]!)
-
- // Assert
- // Assert
- expect(everyoneOptions[0])!.toHaveAttribute('aria-pressed', 'true')
- })
-
- it('should update debug permission when Admins Only option is clicked', () => {
- // Arrange
- const payload = createMockReferenceSetting({
- permission: {
- install_permission: PermissionType.everyone,
- debug_permission: PermissionType.everyone,
- },
- })
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} payload={payload} />)
-
- // Click Admins Only for debug permission (second set of options)
- const adminOptions = screen.getAllByTestId('option-card-plugin.privilege.admins')
- fireEvent.click(adminOptions[1]!) // Second one is for debug permission
-
- // Assert
- // Assert
- expect(adminOptions[1])!.toHaveAttribute('aria-pressed', 'true')
- })
-
- it('should update auto_upgrade config when changed in AutoUpdateSetting', async () => {
- // Arrange
- const onSave = vi.fn().mockResolvedValue(undefined)
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} onSave={onSave} />)
-
- // Change auto update strategy
- fireEvent.click(screen.getByTestId('auto-update-change'))
-
- // Save to verify the change
- fireEvent.click(screen.getByText('common.operation.save'))
-
- // Assert
- await waitFor(() => {
- expect(onSave).toHaveBeenCalledWith(
- expect.objectContaining({
- auto_upgrade: expect.objectContaining({
- strategy_setting: AUTO_UPDATE_STRATEGY.latest,
- }),
- }),
- )
- })
- })
-
- it('should preserve permission values when permission editing is disabled', async () => {
- const onSave = vi.fn().mockResolvedValue(undefined)
- const payload = createMockReferenceSetting({
- permission: {
- install_permission: PermissionType.admin,
- debug_permission: PermissionType.noOne,
- },
- })
-
- render(
- <ReferenceSettingModal
- {...defaultProps}
- payload={payload}
- canSetPermissions={false}
- onSave={onSave}
- />,
- )
- fireEvent.click(screen.getByTestId('auto-update-change'))
- fireEvent.click(screen.getByText('common.operation.save'))
-
- await waitFor(() => {
- expect(onSave).toHaveBeenCalledWith(
- expect.objectContaining({
- permission: payload.permission,
- auto_upgrade: expect.objectContaining({
- strategy_setting: AUTO_UPDATE_STRATEGY.latest,
- }),
- }),
- )
- })
- })
-
- it('should preserve auto update values when auto update editing is disabled', async () => {
- const onSave = vi.fn().mockResolvedValue(undefined)
- const payload = createMockReferenceSetting({
- auto_upgrade: createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- }),
- })
-
- render(
- <ReferenceSettingModal
- {...defaultProps}
- payload={payload}
- canSetAutoUpdate={false}
- onSave={onSave}
- />,
- )
- const noOneOptions = screen.getAllByTestId('option-card-plugin.privilege.noone')
- fireEvent.click(noOneOptions[0]!)
- fireEvent.click(screen.getByText('common.operation.save'))
-
- await waitFor(() => {
- expect(onSave).toHaveBeenCalledWith(
- expect.objectContaining({
- permission: expect.objectContaining({
- install_permission: PermissionType.noOne,
- }),
- auto_upgrade: payload.auto_upgrade,
- }),
- )
- })
- })
- })
-
- describe('Callback Stability and Memoization', () => {
- it('handlePrivilegeChange should create new handler with correct key', () => {
- // Arrange
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Act - click install permission option
- const everyoneOptions = screen.getAllByTestId('option-card-plugin.privilege.everyone')
- fireEvent.click(everyoneOptions[0]!)
-
- // Assert - install permission should be updated
- // Assert - install permission should be updated
- expect(everyoneOptions[0])!.toHaveAttribute('aria-pressed', 'true')
- })
- })
-
- describe('Edge Cases and Error Handling', () => {
- it('should handle undefined permission values', () => {
- // Arrange
- const payload = {
- permission: undefined as unknown as Permissions,
- auto_upgrade: createMockAutoUpdateConfig(),
- }
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} payload={payload} />)
-
- // Assert - should use default PermissionType.noOne
- const noOneOptions = screen.getAllByTestId('option-card-plugin.privilege.noone')
- expect(noOneOptions[0])!.toHaveAttribute('aria-pressed', 'true')
- })
-
- it('should handle missing install_permission', () => {
- // Arrange
- const payload = createMockReferenceSetting({
- permission: {
- install_permission: undefined as unknown as PermissionType,
- debug_permission: PermissionType.everyone,
- },
- })
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} payload={payload} />)
-
- // Assert - should fall back to PermissionType.noOne
- // Assert - should fall back to PermissionType.noOne
- expect(screen.getByText('plugin.privilege.title'))!.toBeInTheDocument()
- })
-
- it('should handle missing debug_permission', () => {
- // Arrange
- const payload = createMockReferenceSetting({
- permission: {
- install_permission: PermissionType.everyone,
- debug_permission: undefined as unknown as PermissionType,
- },
- })
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} payload={payload} />)
-
- // Assert - should fall back to PermissionType.noOne
- // Assert - should fall back to PermissionType.noOne
- expect(screen.getByText('plugin.privilege.title'))!.toBeInTheDocument()
- })
-
- it('should handle slow async onSave gracefully', async () => {
- // Arrange - test that the component handles async save correctly
- let resolvePromise: () => void
- const onSave = vi.fn().mockImplementation(() => {
- return new Promise<void>((resolve) => {
- resolvePromise = resolve
- })
- })
- const onHide = vi.fn()
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} onSave={onSave} onHide={onHide} />)
- fireEvent.click(screen.getByText('common.operation.save'))
-
- // Assert - onSave should be called immediately
- expect(onSave).toHaveBeenCalledTimes(1)
-
- // onHide should not be called until save resolves
- expect(onHide).not.toHaveBeenCalled()
-
- // Resolve the promise
- resolvePromise!()
-
- // Now onHide should be called
- await waitFor(() => {
- expect(onHide).toHaveBeenCalledTimes(1)
- })
- })
- })
-
- describe('Props Variations', () => {
- it('should render with all PermissionType combinations', () => {
- // Test each permission type
- const permissionTypes = [
- PermissionType.everyone,
- PermissionType.admin,
- PermissionType.noOne,
- ]
-
- permissionTypes.forEach((installPerm) => {
- permissionTypes.forEach((debugPerm) => {
- // Arrange
- const payload = createMockReferenceSetting({
- permission: {
- install_permission: installPerm,
- debug_permission: debugPerm,
- },
- })
-
- // Act
- const { unmount } = render(
- <ReferenceSettingModal {...defaultProps} payload={payload} />,
- )
-
- expect(screen.getByText('plugin.privilege.title'))!.toBeInTheDocument()
-
- unmount()
- })
- })
- })
-
- it('should render with all AUTO_UPDATE_STRATEGY values', () => {
- // Test each strategy
- const strategies = [
- AUTO_UPDATE_STRATEGY.disabled,
- AUTO_UPDATE_STRATEGY.fixOnly,
- AUTO_UPDATE_STRATEGY.latest,
- ]
-
- strategies.forEach((strategy) => {
- // Arrange
- const payload = createMockReferenceSetting({
- auto_upgrade: createMockAutoUpdateConfig({
- strategy_setting: strategy,
- }),
- })
-
- // Act
- const { unmount } = render(<ReferenceSettingModal {...defaultProps} payload={payload} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('auto-update-strategy'))!.toHaveTextContent(strategy)
-
- unmount()
- })
- })
-
- it('should render with all AUTO_UPDATE_MODE values', () => {
- // Test each mode
- const modes = [
- AUTO_UPDATE_MODE.update_all,
- AUTO_UPDATE_MODE.partial,
- AUTO_UPDATE_MODE.exclude,
- ]
-
- modes.forEach((mode) => {
- // Arrange
- const payload = createMockReferenceSetting({
- auto_upgrade: createMockAutoUpdateConfig({
- upgrade_mode: mode,
- }),
- })
-
- // Act
- const { unmount } = render(<ReferenceSettingModal {...defaultProps} payload={payload} />)
-
- // Assert
- // Assert
- expect(screen.getByTestId('auto-update-mode'))!.toHaveTextContent(mode)
-
- unmount()
- })
- })
- })
-
- describe('State Updates', () => {
- it('should preserve tempPrivilege when changing install_permission', async () => {
- // Arrange
- const onSave = vi.fn().mockResolvedValue(undefined)
- const payload = createMockReferenceSetting({
- permission: {
- install_permission: PermissionType.everyone,
- debug_permission: PermissionType.admin,
- },
- })
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} payload={payload} onSave={onSave} />)
-
- // Change install permission to noOne
- const noOneOptions = screen.getAllByTestId('option-card-plugin.privilege.noone')
- fireEvent.click(noOneOptions[0]!)
-
- // Save
- fireEvent.click(screen.getByText('common.operation.save'))
-
- // Assert - debug_permission should still be admin
- await waitFor(() => {
- expect(onSave).toHaveBeenCalledWith(
- expect.objectContaining({
- permission: expect.objectContaining({
- install_permission: PermissionType.noOne,
- debug_permission: PermissionType.admin,
- }),
- }),
- )
- })
- })
-
- it('should preserve tempPrivilege when changing debug_permission', async () => {
- // Arrange
- const onSave = vi.fn().mockResolvedValue(undefined)
- const payload = createMockReferenceSetting({
- permission: {
- install_permission: PermissionType.admin,
- debug_permission: PermissionType.everyone,
- },
- })
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} payload={payload} onSave={onSave} />)
-
- // Change debug permission to noOne
- const noOneOptions = screen.getAllByTestId('option-card-plugin.privilege.noone')
- fireEvent.click(noOneOptions[1]!) // Second one is for debug
-
- // Save
- fireEvent.click(screen.getByText('common.operation.save'))
-
- // Assert - install_permission should still be admin
- await waitFor(() => {
- expect(onSave).toHaveBeenCalledWith(
- expect.objectContaining({
- permission: expect.objectContaining({
- install_permission: PermissionType.admin,
- debug_permission: PermissionType.noOne,
- }),
- }),
- )
- })
- })
-
- it('should update tempAutoUpdateConfig independently of permissions', async () => {
- // Arrange
- const onSave = vi.fn().mockResolvedValue(undefined)
- const initialPayload = createMockReferenceSetting()
-
- // Act
- render(<ReferenceSettingModal {...defaultProps} payload={initialPayload} onSave={onSave} />)
-
- // Change auto update
- fireEvent.click(screen.getByTestId('auto-update-change'))
-
- // Change install permission
- const everyoneOptions = screen.getAllByTestId('option-card-plugin.privilege.everyone')
- fireEvent.click(everyoneOptions[0]!)
-
- // Save
- fireEvent.click(screen.getByText('common.operation.save'))
-
- // Assert - both changes should be saved
- await waitFor(() => {
- expect(onSave).toHaveBeenCalledWith(
- expect.objectContaining({
- permission: expect.objectContaining({
- install_permission: PermissionType.everyone,
- }),
- auto_upgrade: expect.objectContaining({
- strategy_setting: AUTO_UPDATE_STRATEGY.latest,
- }),
- }),
- )
- })
- })
- })
-
- describe('Modal Integration', () => {
- it('should pass isShow=true to Modal', () => {
- // Arrange & Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert - modal should be visible
- // Assert - modal should be visible
- expect(screen.getByRole('dialog'))!.toBeInTheDocument()
- })
- })
-
- describe('Layout and Structure', () => {
- it('should render permission sections in correct order', () => {
- // Arrange & Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert - check order by getting all section labels
- const labels = screen.getAllByText(/plugin\.privilege\.whoCan/)
- expect(labels[0])!.toHaveTextContent('plugin.privilege.whoCanInstall')
- expect(labels[1])!.toHaveTextContent('plugin.privilege.whoCanDebug')
- })
-
- it('should render three options per permission section', () => {
- // Arrange & Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert
- const everyoneOptions = screen.getAllByTestId('option-card-plugin.privilege.everyone')
- const adminOptions = screen.getAllByTestId('option-card-plugin.privilege.admins')
- const noOneOptions = screen.getAllByTestId('option-card-plugin.privilege.noone')
-
- expect(everyoneOptions).toHaveLength(2) // One for install, one for debug
- expect(adminOptions).toHaveLength(2)
- expect(noOneOptions).toHaveLength(2)
- })
-
- it('should render footer with action buttons', () => {
- // Arrange & Act
- render(<ReferenceSettingModal {...defaultProps} />)
-
- // Assert
- const cancelButton = screen.getByText('common.operation.cancel')
- const saveButton = screen.getByText('common.operation.save')
-
- expect(cancelButton)!.toBeInTheDocument()
- expect(saveButton)!.toBeInTheDocument()
- })
- })
- })
-
- // ============================================================
- // Integration Tests
- // ============================================================
- describe('Integration', () => {
- it('should handle complete workflow: change permissions, update auto-update, save', async () => {
- // Arrange
- const onSave = vi.fn().mockResolvedValue(undefined)
- const onHide = vi.fn()
- const initialPayload = createMockReferenceSetting({
- permission: {
- install_permission: PermissionType.noOne,
- debug_permission: PermissionType.noOne,
- },
- auto_upgrade: createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.disabled,
- }),
- })
-
- // Act
- render(
- <ReferenceSettingModal
- payload={initialPayload}
- canSetPermissions
- canSetAutoUpdate
- onHide={onHide}
- onSave={onSave}
- />,
- )
-
- // Change install permission to Everyone
- const everyoneOptions = screen.getAllByTestId('option-card-plugin.privilege.everyone')
- fireEvent.click(everyoneOptions[0]!)
-
- // Change debug permission to Admins Only
- const adminOptions = screen.getAllByTestId('option-card-plugin.privilege.admins')
- fireEvent.click(adminOptions[1]!)
-
- // Change auto-update strategy
- fireEvent.click(screen.getByTestId('auto-update-change'))
-
- // Save
- fireEvent.click(screen.getByText('common.operation.save'))
-
- // Assert
- await waitFor(() => {
- expect(onSave).toHaveBeenCalledWith({
- permission: {
- install_permission: PermissionType.everyone,
- debug_permission: PermissionType.admin,
- },
- auto_upgrade: expect.objectContaining({
- strategy_setting: AUTO_UPDATE_STRATEGY.latest,
- }),
- })
- expect(onHide).toHaveBeenCalled()
- })
- })
-
- it('should cancel without saving changes', () => {
- // Arrange
- const onSave = vi.fn()
- const onHide = vi.fn()
- const initialPayload = createMockReferenceSetting()
-
- // Act
- render(
- <ReferenceSettingModal
- payload={initialPayload}
- canSetPermissions
- canSetAutoUpdate
- onHide={onHide}
- onSave={onSave}
- />,
- )
-
- // Make some changes
- const noOneOptions = screen.getAllByTestId('option-card-plugin.privilege.noone')
- fireEvent.click(noOneOptions[0]!)
-
- // Cancel
- fireEvent.click(screen.getByText('common.operation.cancel'))
-
- // Assert
- expect(onSave).not.toHaveBeenCalled()
- expect(onHide).toHaveBeenCalledTimes(1)
- })
-
- it('Label component should work correctly within modal context', () => {
- // Arrange
- const props = {
- payload: createMockReferenceSetting(),
- canSetPermissions: true,
- canSetAutoUpdate: true,
- onHide: vi.fn(),
- onSave: vi.fn(),
- }
-
- // Act
- render(<ReferenceSettingModal {...props} />)
-
- // Assert - Labels are rendered correctly
- // Assert - Labels are rendered correctly
- expect(screen.getByText('plugin.privilege.whoCanInstall'))!.toBeInTheDocument()
- expect(screen.getByText('plugin.privilege.whoCanDebug'))!.toBeInTheDocument()
- })
- })
-})
diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/index.spec.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/index.spec.tsx
deleted file mode 100644
index 29e1d4aed0d..00000000000
--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,1473 +0,0 @@
-import type { AutoUpdateConfig } from '../types'
-import type { PluginDeclaration, PluginDetail } from '@/app/components/plugins/types'
-import { QueryClientProvider } from '@tanstack/react-query'
-import { fireEvent, render as rtlRender, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import dayjs from 'dayjs'
-import timezone from 'dayjs/plugin/timezone'
-import utc from 'dayjs/plugin/utc'
-import * as React from 'react'
-import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { createAccountProfileQueryClient } from '@/test/console/account-profile'
-import { PluginCategoryEnum, PluginSource } from '../../../types'
-import AutoUpdateSetting from '../index'
-import NoDataPlaceholder from '../no-data-placeholder'
-import NoPluginSelected from '../no-plugin-selected'
-import PluginsPicker from '../plugins-picker'
-import PluginsSelected from '../plugins-selected'
-import StrategyPicker from '../strategy-picker'
-import ToolItem from '../tool-item'
-import ToolPicker from '../tool-picker'
-import { AUTO_UPDATE_MODE, AUTO_UPDATE_STRATEGY } from '../types'
-import {
- convertLocalSecondsToUTCDaySeconds,
- convertUTCDaySecondsToLocalSeconds,
- dayjsToTimeOfDay,
- timeOfDayToDayjs,
-} from '../utils'
-
-// Setup dayjs plugins
-dayjs.extend(utc)
-dayjs.extend(timezone)
-
-// Mock app context
-const mockTimezone = 'America/New_York'
-
-const mockSetSettingsDestination = vi.fn()
-vi.mock('nuqs', async (importOriginal) => {
- const actual = await importOriginal<typeof import('nuqs')>()
- return { ...actual, useQueryState: () => [null, mockSetSettingsDestination] }
-})
-
-// Mock i18n context
-
-vi.mock('react-i18next', async () => {
- const { withSelectorKey, withSelectorKeyProps } = await import('@/test/i18n-mock')
- return {
- useTranslation: (defaultNs?: string) => ({
- t: withSelectorKey((key: string, options?: Record<string, unknown>) => {
- const ns = (options?.ns as string | undefined) ?? defaultNs
- const params = { ...options }
- delete params.ns
- const suffix = Object.keys(params).length > 0 ? `:${JSON.stringify(params)}` : ''
- return `${ns ? `${ns}.` : ''}${key}${suffix}`
- }),
- i18n: {
- language: 'en',
- changeLanguage: vi.fn(),
- },
- }),
- Trans: withSelectorKeyProps(
- ({
- i18nKey,
- components,
- }: {
- i18nKey: string
- components?: Record<string, React.ReactElement>
- }) => {
- const setTimezone = components?.setTimezone
- if (setTimezone)
- return React.createElement(
- setTimezone.type as React.ElementType,
- setTimezone.props,
- i18nKey,
- )
-
- return <span>{i18nKey}</span>
- },
- ),
- }
-})
-
-// Mock plugins service
-const mockPluginsData: { plugins: PluginDetail[] } = { plugins: [] }
-vi.mock('@/service/use-plugins', () => ({
- useInstalledPluginList: () => ({
- data: mockPluginsData,
- isLoading: false,
- }),
-}))
-
-// Mock utils from date-and-time-picker
-vi.mock('@/app/components/base/date-and-time-picker/utils/dayjs', async (importOriginal) => ({
- ...(await importOriginal<
- typeof import('@/app/components/base/date-and-time-picker/utils/dayjs')
- >()),
- convertTimezoneToOffsetStr: (tz: string) => {
- if (tz === 'America/New_York') return 'GMT-5'
- if (tz === 'Asia/Shanghai') return 'GMT+8'
- return 'GMT+0'
- },
-}))
-
-// Mock SearchBox component
-vi.mock('@/app/components/plugins/marketplace/search-box', () => ({
- default: ({
- search,
- onSearchChange,
- tags: _tags,
- onTagsChange: _onTagsChange,
- placeholder,
- }: {
- search: string
- onSearchChange: (v: string) => void
- tags: string[]
- onTagsChange: (v: string[]) => void
- placeholder: string
- }) => (
- <div data-testid="search-box">
- <input
- data-testid="search-input"
- value={search}
- onChange={(e) => onSearchChange(e.target.value)}
- placeholder={placeholder}
- />
- </div>
- ),
-}))
-
-// Mock Icon component
-vi.mock('@/app/components/plugins/card/base/card-icon', () => ({
- default: ({ size, src }: { size: string; src: string }) => (
- <img data-testid="plugin-icon" data-size={size} src={src} alt="plugin icon" />
- ),
-}))
-
-// Mock icons
-vi.mock('@/app/components/base/icons/src/vender/line/general', () => ({
- SearchMenu: ({ className }: { className?: string }) => (
- <span data-testid="search-menu-icon" className={className}>
- 🔍
- </span>
- ),
-}))
-
-vi.mock('@/app/components/base/icons/src/vender/other', () => ({
- Group: ({ className }: { className?: string }) => (
- <span data-testid="group-icon" className={className}>
- 📦
- </span>
- ),
-}))
-
-// Mock PLUGIN_TYPE_SEARCH_MAP
-vi.mock('../../../marketplace/constants', () => ({
- PLUGIN_TYPE_SEARCH_MAP: {
- all: 'all',
- model: 'model',
- tool: 'tool',
- agent: 'agent',
- extension: 'extension',
- datasource: 'datasource',
- trigger: 'trigger',
- bundle: 'bundle',
- },
-}))
-
-// Mock i18n renderI18nObject
-vi.mock('@/i18n-config', () => ({
- renderI18nObject: (obj: Record<string, string>, lang: string) => obj[lang] || obj['en-US'] || '',
-}))
-
-// ================================
-// Test Data Factories
-// ================================
-
-const createMockPluginDeclaration = (
- overrides: Partial<PluginDeclaration> = {},
-): PluginDeclaration => ({
- plugin_unique_identifier: 'test-plugin-id',
- version: '1.0.0',
- author: 'test-author',
- icon: 'test-icon.png',
- name: 'Test Plugin',
- category: PluginCategoryEnum.tool,
- label: { 'en-US': 'Test Plugin' } as PluginDeclaration['label'],
- description: { 'en-US': 'A test plugin' } as PluginDeclaration['description'],
- created_at: '2024-01-01',
- resource: {},
- plugins: {},
- verified: true,
- endpoint: { settings: [], endpoints: [] },
- model: {},
- tags: ['tag1', 'tag2'],
- agent_strategy: {},
- meta: { version: '1.0.0' },
- trigger: {
- events: [],
- identity: {
- author: 'test',
- name: 'test',
- label: { 'en-US': 'Test' } as PluginDeclaration['label'],
- description: { 'en-US': 'Test' } as PluginDeclaration['description'],
- icon: 'test.png',
- tags: [],
- },
- subscription_constructor: {
- credentials_schema: [],
- oauth_schema: { client_schema: [], credentials_schema: [] },
- parameters: [],
- },
- subscription_schema: [],
- },
- ...overrides,
-})
-
-const createMockPluginDetail = (overrides: Partial<PluginDetail> = {}): PluginDetail => ({
- id: 'plugin-1',
- created_at: '2024-01-01',
- updated_at: '2024-01-01',
- name: 'test-plugin',
- plugin_id: 'test-plugin-id',
- plugin_unique_identifier: 'test-plugin-unique',
- declaration: createMockPluginDeclaration(),
- installation_id: 'install-1',
- tenant_id: 'tenant-1',
- endpoints_setups: 0,
- endpoints_active: 0,
- version: '1.0.0',
- latest_version: '1.1.0',
- latest_unique_identifier: 'test-plugin-latest',
- source: PluginSource.marketplace,
- status: 'active',
- deprecated_reason: '',
- alternative_plugin_id: '',
- ...overrides,
-})
-
-const createMockAutoUpdateConfig = (
- overrides: Partial<AutoUpdateConfig> = {},
-): AutoUpdateConfig => ({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_time_of_day: 36000, // 10:00 UTC
- upgrade_mode: AUTO_UPDATE_MODE.update_all,
- exclude_plugins: [],
- include_plugins: [],
- ...overrides,
-})
-
-// ================================
-// Helper Functions
-// ================================
-
-const createQueryClient = () => createAccountProfileQueryClient({ timezone: mockTimezone })
-
-const render = (ui: React.ReactElement) => {
- const queryClient = createQueryClient()
- const Wrapper = ({ children }: { children: React.ReactNode }) => (
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
- )
- return rtlRender(ui, { wrapper: Wrapper })
-}
-
-const renderWithQueryClient = (ui: React.ReactElement) => {
- const queryClient = createQueryClient()
- const Wrapper = ({ children }: { children: React.ReactNode }) => (
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
- )
- return rtlRender(ui, { wrapper: Wrapper })
-}
-
-// ================================
-// Test Suites
-// ================================
-
-describe('auto-update-setting', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockPluginsData.plugins = []
- })
-
- // ============================================================
- // Types and Config Tests
- // ============================================================
- describe('types.ts', () => {
- describe('AUTO_UPDATE_STRATEGY enum', () => {
- it('should have correct values', () => {
- expect(AUTO_UPDATE_STRATEGY.fixOnly).toBe('fix_only')
- expect(AUTO_UPDATE_STRATEGY.disabled).toBe('disabled')
- expect(AUTO_UPDATE_STRATEGY.latest).toBe('latest')
- })
-
- it('should contain exactly 3 strategies', () => {
- const values = Object.values(AUTO_UPDATE_STRATEGY)
- expect(values).toHaveLength(3)
- })
- })
-
- describe('AUTO_UPDATE_MODE enum', () => {
- it('should have correct values', () => {
- expect(AUTO_UPDATE_MODE.partial).toBe('partial')
- expect(AUTO_UPDATE_MODE.exclude).toBe('exclude')
- expect(AUTO_UPDATE_MODE.update_all).toBe('all')
- })
-
- it('should contain exactly 3 modes', () => {
- const values = Object.values(AUTO_UPDATE_MODE)
- expect(values).toHaveLength(3)
- })
- })
- })
-
- // ============================================================
- // Utils Tests (Extended coverage beyond utils.spec.ts)
- // ============================================================
- describe('utils.ts', () => {
- describe('timeOfDayToDayjs', () => {
- it('should convert 0 seconds to midnight', () => {
- const result = timeOfDayToDayjs(0)
- expect(result.hour()).toBe(0)
- expect(result.minute()).toBe(0)
- })
-
- it('should convert 3600 seconds to 1:00', () => {
- const result = timeOfDayToDayjs(3600)
- expect(result.hour()).toBe(1)
- expect(result.minute()).toBe(0)
- })
-
- it('should convert 36000 seconds to 10:00', () => {
- const result = timeOfDayToDayjs(36000)
- expect(result.hour()).toBe(10)
- expect(result.minute()).toBe(0)
- })
-
- it('should convert 43200 seconds to 12:00 (noon)', () => {
- const result = timeOfDayToDayjs(43200)
- expect(result.hour()).toBe(12)
- expect(result.minute()).toBe(0)
- })
-
- it('should convert 82800 seconds to 23:00', () => {
- const result = timeOfDayToDayjs(82800)
- expect(result.hour()).toBe(23)
- expect(result.minute()).toBe(0)
- })
-
- it('should handle minutes correctly', () => {
- const result = timeOfDayToDayjs(5400) // 1:30
- expect(result.hour()).toBe(1)
- expect(result.minute()).toBe(30)
- })
-
- it('should handle 15 minute intervals', () => {
- expect(timeOfDayToDayjs(900).minute()).toBe(15)
- expect(timeOfDayToDayjs(1800).minute()).toBe(30)
- expect(timeOfDayToDayjs(2700).minute()).toBe(45)
- })
- })
-
- describe('dayjsToTimeOfDay', () => {
- it('should return 0 for undefined input', () => {
- expect(dayjsToTimeOfDay(undefined)).toBe(0)
- })
-
- it('should convert midnight to 0', () => {
- const midnight = dayjs().hour(0).minute(0)
- expect(dayjsToTimeOfDay(midnight)).toBe(0)
- })
-
- it('should convert 1:00 to 3600', () => {
- const time = dayjs().hour(1).minute(0)
- expect(dayjsToTimeOfDay(time)).toBe(3600)
- })
-
- it('should convert 10:30 to 37800', () => {
- const time = dayjs().hour(10).minute(30)
- expect(dayjsToTimeOfDay(time)).toBe(37800)
- })
-
- it('should convert 23:59 to 86340', () => {
- const time = dayjs().hour(23).minute(59)
- expect(dayjsToTimeOfDay(time)).toBe(86340)
- })
- })
-
- describe('convertLocalSecondsToUTCDaySeconds', () => {
- it('should convert local midnight to UTC for positive offset timezone', () => {
- // Shanghai is UTC+8, local midnight should be 16:00 UTC previous day
- const result = convertLocalSecondsToUTCDaySeconds(0, 'Asia/Shanghai')
- expect(result).toBe((24 - 8) * 3600)
- })
-
- it('should handle negative offset timezone', () => {
- // New York is UTC-5 (or -4 during DST), local midnight should be 5:00 UTC
- const result = convertLocalSecondsToUTCDaySeconds(0, 'America/New_York')
- // Result depends on DST, but should be in valid range
- expect(result).toBeGreaterThanOrEqual(0)
- expect(result).toBeLessThan(86400)
- })
-
- it('should be reversible with convertUTCDaySecondsToLocalSeconds', () => {
- const localSeconds = 36000 // 10:00 local
- const utcSeconds = convertLocalSecondsToUTCDaySeconds(localSeconds, 'Asia/Shanghai')
- const backToLocal = convertUTCDaySecondsToLocalSeconds(utcSeconds, 'Asia/Shanghai')
- expect(backToLocal).toBe(localSeconds)
- })
- })
-
- describe('convertUTCDaySecondsToLocalSeconds', () => {
- it('should convert UTC midnight to local time for positive offset timezone', () => {
- // UTC midnight in Shanghai (UTC+8) is 8:00 local
- const result = convertUTCDaySecondsToLocalSeconds(0, 'Asia/Shanghai')
- expect(result).toBe(8 * 3600)
- })
-
- it('should handle edge cases near day boundaries', () => {
- // UTC 23:00 in Shanghai is 7:00 next day
- const result = convertUTCDaySecondsToLocalSeconds(23 * 3600, 'Asia/Shanghai')
- expect(result).toBeGreaterThanOrEqual(0)
- expect(result).toBeLessThan(86400)
- })
- })
- })
-
- // ============================================================
- // NoDataPlaceholder Component Tests
- // ============================================================
- describe('NoDataPlaceholder (no-data-placeholder.tsx)', () => {
- describe('Rendering', () => {
- it('should render with noPlugins=true showing group icon', () => {
- // Act
- render(<NoDataPlaceholder className="test-class" noPlugins={true} />)
-
- // Assert
- expect(screen.getByTestId('group-icon')).toBeInTheDocument()
- expect(
- screen.getByText('plugin.autoUpdate.noPluginPlaceholder.noInstalled'),
- ).toBeInTheDocument()
- })
-
- it('should render with noPlugins=false showing search icon', () => {
- // Act
- render(<NoDataPlaceholder className="test-class" noPlugins={false} />)
-
- // Assert
- expect(screen.getByTestId('search-menu-icon')).toBeInTheDocument()
- expect(
- screen.getByText('plugin.autoUpdate.noPluginPlaceholder.noFound'),
- ).toBeInTheDocument()
- })
-
- it('should render with noPlugins=undefined (default) showing search icon', () => {
- // Act
- render(<NoDataPlaceholder className="test-class" />)
-
- // Assert
- expect(screen.getByTestId('search-menu-icon')).toBeInTheDocument()
- })
- })
- })
-
- describe('NoPluginSelected (no-plugin-selected.tsx)', () => {
- describe('Rendering', () => {
- it('should render partial mode placeholder', () => {
- // Act
- render(<NoPluginSelected updateMode={AUTO_UPDATE_MODE.partial} />)
-
- // Assert
- expect(
- screen.getByText('plugin.autoUpdate.upgradeModePlaceholder.partial'),
- ).toBeInTheDocument()
- })
-
- it('should render exclude mode placeholder', () => {
- // Act
- render(<NoPluginSelected updateMode={AUTO_UPDATE_MODE.exclude} />)
-
- // Assert
- expect(
- screen.getByText('plugin.autoUpdate.upgradeModePlaceholder.exclude'),
- ).toBeInTheDocument()
- })
- })
- })
-
- describe('PluginsSelected (plugins-selected.tsx)', () => {
- describe('Rendering', () => {
- it('should render empty when no plugins', () => {
- // Act
- const { container } = render(<PluginsSelected plugins={[]} />)
-
- // Assert
- expect(container.querySelectorAll('[data-testid="plugin-icon"]')).toHaveLength(0)
- })
-
- it('should render all plugins when count is below MAX_DISPLAY_COUNT (14)', () => {
- // Arrange
- const plugins = Array.from({ length: 10 }, (_, i) => `plugin-${i}`)
-
- // Act
- render(<PluginsSelected plugins={plugins} />)
-
- // Assert
- const icons = screen.getAllByTestId('plugin-icon')
- expect(icons).toHaveLength(10)
- })
-
- it('should render MAX_DISPLAY_COUNT plugins with overflow indicator when count exceeds limit', () => {
- // Arrange
- const plugins = Array.from({ length: 20 }, (_, i) => `plugin-${i}`)
-
- // Act
- render(<PluginsSelected plugins={plugins} />)
-
- // Assert
- const icons = screen.getAllByTestId('plugin-icon')
- expect(icons).toHaveLength(14)
- expect(screen.getByText('+6')).toBeInTheDocument()
- })
-
- it('should render correct icon URLs', () => {
- // Arrange
- const plugins = ['plugin-a', 'plugin-b']
-
- // Act
- render(<PluginsSelected plugins={plugins} />)
-
- // Assert
- const icons = screen.getAllByTestId('plugin-icon')
- expect(icons[0]).toHaveAttribute('src', expect.stringContaining('plugin-a'))
- expect(icons[1]).toHaveAttribute('src', expect.stringContaining('plugin-b'))
- })
- })
-
- describe('Edge Cases', () => {
- it('should handle exactly MAX_DISPLAY_COUNT plugins without overflow', () => {
- // Arrange - exactly 14 plugins (MAX_DISPLAY_COUNT)
- const plugins = Array.from({ length: 14 }, (_, i) => `plugin-${i}`)
-
- // Act
- render(<PluginsSelected plugins={plugins} />)
-
- // Assert - all 14 icons are displayed
- expect(screen.getAllByTestId('plugin-icon')).toHaveLength(14)
- expect(screen.queryByText('+0')).not.toBeInTheDocument()
- })
-
- it('should handle MAX_DISPLAY_COUNT + 1 plugins showing overflow', () => {
- // Arrange - 15 plugins
- const plugins = Array.from({ length: 15 }, (_, i) => `plugin-${i}`)
-
- // Act
- render(<PluginsSelected plugins={plugins} />)
-
- // Assert
- expect(screen.getAllByTestId('plugin-icon')).toHaveLength(14)
- expect(screen.getByText('+1')).toBeInTheDocument()
- })
- })
- })
-
- describe('ToolItem (tool-item.tsx)', () => {
- const defaultProps = {
- payload: createMockPluginDetail(),
- isChecked: false,
- onCheckChange: vi.fn(),
- }
-
- describe('Rendering', () => {
- it('should render plugin icon', () => {
- // Act
- render(<ToolItem {...defaultProps} />)
-
- // Assert
- expect(screen.getByTestId('plugin-icon')).toBeInTheDocument()
- })
-
- it('should render plugin label', () => {
- // Arrange
- const props = {
- ...defaultProps,
- payload: createMockPluginDetail({
- declaration: createMockPluginDeclaration({
- label: { 'en-US': 'My Test Plugin' } as PluginDeclaration['label'],
- }),
- }),
- }
-
- // Act
- render(<ToolItem {...props} />)
-
- // Assert
- expect(screen.getByText('My Test Plugin')).toBeInTheDocument()
- })
-
- it('should render plugin author', () => {
- // Arrange
- const props = {
- ...defaultProps,
- payload: createMockPluginDetail({
- declaration: createMockPluginDeclaration({
- author: 'Plugin Author',
- }),
- }),
- }
-
- // Act
- render(<ToolItem {...props} />)
-
- // Assert
- expect(screen.getByText('Plugin Author')).toBeInTheDocument()
- })
-
- it('should render checkbox unchecked when isChecked is false', () => {
- // Act
- render(<ToolItem {...defaultProps} isChecked={false} />)
-
- // Assert
- expect(screen.getByRole('checkbox')).not.toBeChecked()
- })
-
- it('should render checkbox checked when isChecked is true', () => {
- // Act
- render(<ToolItem {...defaultProps} isChecked={true} />)
-
- // Assert
- expect(screen.getByRole('checkbox')).toBeChecked()
- })
- })
-
- describe('User Interactions', () => {
- it('should call onCheckChange when checkbox is clicked', () => {
- // Arrange
- const onCheckChange = vi.fn()
-
- // Act
- render(<ToolItem {...defaultProps} onCheckChange={onCheckChange} />)
- fireEvent.click(screen.getByRole('checkbox'))
-
- // Assert
- expect(onCheckChange).toHaveBeenCalledTimes(1)
- })
- })
- })
-
- describe('StrategyPicker (strategy-picker.tsx)', () => {
- const i18nKeyByStrategy: Record<AUTO_UPDATE_STRATEGY, 'disabled' | 'fixOnly' | 'latest'> = {
- [AUTO_UPDATE_STRATEGY.disabled]: 'disabled',
- [AUTO_UPDATE_STRATEGY.fixOnly]: 'fixOnly',
- [AUTO_UPDATE_STRATEGY.latest]: 'latest',
- }
-
- const triggerName = (strategy: AUTO_UPDATE_STRATEGY) =>
- new RegExp(`plugin\\.autoUpdate\\.strategy\\.${i18nKeyByStrategy[strategy]}\\.name`, 'i')
-
- const findOption = (key: 'disabled' | 'fixOnly' | 'latest') => {
- const options = screen.getAllByRole('button')
- const option = options.find((item) =>
- item.textContent?.includes(`plugin.autoUpdate.strategy.${key}.name`),
- )
- if (!option) throw new Error(`Strategy option "${key}" not found`)
- return option
- }
-
- describe('Rendering', () => {
- it('should render the segmented control with all strategies', () => {
- render(<StrategyPicker value={AUTO_UPDATE_STRATEGY.disabled} onChange={vi.fn()} />)
-
- expect(
- screen.getByRole('group', { name: 'plugin.autoUpdate.automaticUpdates' }),
- ).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: triggerName(AUTO_UPDATE_STRATEGY.disabled) }),
- ).toBeInTheDocument()
- const options = screen.getAllByRole('button')
- expect(options).toHaveLength(3)
- expect(
- options.some((o) => o.textContent?.includes('plugin.autoUpdate.strategy.disabled.name')),
- ).toBe(true)
- expect(
- options.some((o) => o.textContent?.includes('plugin.autoUpdate.strategy.fixOnly.name')),
- ).toBe(true)
- expect(
- options.some((o) => o.textContent?.includes('plugin.autoUpdate.strategy.latest.name')),
- ).toBe(true)
- })
- })
-
- describe('User Interactions', () => {
- it.each<[AUTO_UPDATE_STRATEGY, 'disabled' | 'fixOnly' | 'latest', AUTO_UPDATE_STRATEGY]>([
- [AUTO_UPDATE_STRATEGY.disabled, 'fixOnly', AUTO_UPDATE_STRATEGY.fixOnly],
- [AUTO_UPDATE_STRATEGY.disabled, 'latest', AUTO_UPDATE_STRATEGY.latest],
- [AUTO_UPDATE_STRATEGY.fixOnly, 'disabled', AUTO_UPDATE_STRATEGY.disabled],
- ])(
- 'should call onChange with %s -> %s when option is selected',
- async (initial, optionKey, expected) => {
- const user = userEvent.setup()
- const onChange = vi.fn()
- render(<StrategyPicker value={initial} onChange={onChange} />)
-
- await user.click(findOption(optionKey))
-
- expect(onChange).toHaveBeenCalledWith(expected)
- },
- )
-
- it('should mark only the currently selected option with aria-pressed', () => {
- render(<StrategyPicker value={AUTO_UPDATE_STRATEGY.fixOnly} onChange={vi.fn()} />)
-
- const options = screen.getAllByRole('button')
- const checked = options.filter((o) => o.getAttribute('aria-pressed') === 'true')
-
- expect(checked).toHaveLength(1)
- expect(checked[0]).toHaveTextContent('plugin.autoUpdate.strategy.fixOnly.name')
- })
- })
- })
-
- describe('ToolPicker (tool-picker.tsx)', () => {
- const defaultProps = {
- trigger: <button>Select Plugins</button>,
- value: [] as string[],
- onChange: vi.fn(),
- isShow: false,
- onShowChange: vi.fn(),
- }
-
- describe('Rendering', () => {
- it('should render trigger element', () => {
- // Act
- render(<ToolPicker {...defaultProps} />)
-
- // Assert
- expect(screen.getByRole('button', { name: 'Select Plugins' })).toBeInTheDocument()
- })
-
- it('should not render content when isShow is false', () => {
- // Act
- render(<ToolPicker {...defaultProps} isShow={false} />)
-
- // Assert
- expect(screen.queryByTestId('popover-content')).not.toBeInTheDocument()
- })
-
- it('should render search box and tabs when isShow is true', () => {
- // Arrange
-
- // Act
- render(<ToolPicker {...defaultProps} isShow={true} />)
-
- // Assert
- expect(screen.getByTestId('search-box')).toBeInTheDocument()
- })
-
- it('should show NoDataPlaceholder when no plugins and no search query', () => {
- // Arrange
- mockPluginsData.plugins = []
-
- // Act
- renderWithQueryClient(<ToolPicker {...defaultProps} isShow={true} />)
-
- // Assert - should show "No plugins installed" when no query
- expect(screen.getByTestId('group-icon')).toBeInTheDocument()
- })
- })
-
- describe('Filtering', () => {
- beforeEach(() => {
- mockPluginsData.plugins = [
- createMockPluginDetail({
- plugin_id: 'tool-plugin',
- source: PluginSource.marketplace,
- declaration: createMockPluginDeclaration({
- category: PluginCategoryEnum.tool,
- label: { 'en-US': 'Tool Plugin' } as PluginDeclaration['label'],
- }),
- }),
- createMockPluginDetail({
- plugin_id: 'model-plugin',
- source: PluginSource.marketplace,
- declaration: createMockPluginDeclaration({
- category: PluginCategoryEnum.model,
- label: { 'en-US': 'Model Plugin' } as PluginDeclaration['label'],
- }),
- }),
- createMockPluginDetail({
- plugin_id: 'github-plugin',
- source: PluginSource.github,
- declaration: createMockPluginDeclaration({
- label: { 'en-US': 'GitHub Plugin' } as PluginDeclaration['label'],
- }),
- }),
- ]
- })
-
- it('should filter out non-marketplace plugins', () => {
- // Arrange
-
- // Act
- renderWithQueryClient(<ToolPicker {...defaultProps} isShow={true} />)
-
- // Assert - GitHub plugin should not be shown
- expect(screen.queryByText('GitHub Plugin')).not.toBeInTheDocument()
- })
-
- it('should filter by search query', () => {
- // Arrange
-
- // Act
- renderWithQueryClient(<ToolPicker {...defaultProps} isShow={true} />)
-
- // Type in search box
- fireEvent.change(screen.getByTestId('search-input'), { target: { value: 'tool' } })
-
- // Assert - only tool plugin should match
- expect(screen.getByText('Tool Plugin')).toBeInTheDocument()
- expect(screen.queryByText('Model Plugin')).not.toBeInTheDocument()
- })
- })
-
- describe('User Interactions', () => {
- it('should call onShowChange when trigger is clicked', () => {
- // Arrange
- const onShowChange = vi.fn()
-
- // Act
- render(<ToolPicker {...defaultProps} onShowChange={onShowChange} />)
- fireEvent.click(screen.getByRole('button', { name: 'Select Plugins' }))
-
- // Assert
- expect(onShowChange).toHaveBeenCalledWith(true, expect.any(Object))
- })
-
- it('should call onChange when plugin is selected', () => {
- // Arrange
- mockPluginsData.plugins = [
- createMockPluginDetail({
- plugin_id: 'test-plugin',
- source: PluginSource.marketplace,
- declaration: createMockPluginDeclaration({
- label: { 'en-US': 'Test Plugin' } as PluginDeclaration['label'],
- }),
- }),
- ]
- const onChange = vi.fn()
-
- // Act
- renderWithQueryClient(<ToolPicker {...defaultProps} isShow={true} onChange={onChange} />)
- fireEvent.click(screen.getByRole('checkbox'))
-
- // Assert
- expect(onChange).toHaveBeenCalledWith(['test-plugin'])
- })
-
- it('should unselect plugin when already selected', () => {
- // Arrange
- mockPluginsData.plugins = [
- createMockPluginDetail({
- plugin_id: 'test-plugin',
- source: PluginSource.marketplace,
- }),
- ]
- const onChange = vi.fn()
-
- // Act
- renderWithQueryClient(
- <ToolPicker
- {...defaultProps}
- isShow={true}
- value={['test-plugin']}
- onChange={onChange}
- />,
- )
- fireEvent.click(screen.getByRole('checkbox'))
-
- // Assert
- expect(onChange).toHaveBeenCalledWith([])
- })
- })
- })
-
- // ============================================================
- // PluginsPicker Component Tests
- // ============================================================
- describe('PluginsPicker (plugins-picker.tsx)', () => {
- const defaultProps = {
- updateMode: AUTO_UPDATE_MODE.partial,
- value: [] as string[],
- onChange: vi.fn(),
- }
-
- describe('Rendering', () => {
- it('should render NoPluginSelected when no plugins selected', () => {
- // Act
- render(<PluginsPicker {...defaultProps} />)
-
- // Assert
- expect(
- screen.getByText('plugin.autoUpdate.upgradeModePlaceholder.partial'),
- ).toBeInTheDocument()
- })
-
- it('should render selected plugins count and clear button when plugins selected', () => {
- // Act
- render(<PluginsPicker {...defaultProps} value={['plugin-1', 'plugin-2']} />)
-
- // Assert
- expect(
- screen.getByText('plugin.autoUpdate.partialUPdate:{"count":2,"num":2}'),
- ).toBeInTheDocument()
- expect(
- screen.getByRole('button', { name: 'plugin.autoUpdate.operation.clearAll' }),
- ).toBeInTheDocument()
- })
-
- it('should render select button', () => {
- // Act
- render(<PluginsPicker {...defaultProps} />)
-
- // Assert
- expect(screen.getByText('plugin.autoUpdate.operation.select')).toBeInTheDocument()
- })
-
- it('should show exclude mode text when in exclude mode', () => {
- // Act
- render(
- <PluginsPicker
- {...defaultProps}
- updateMode={AUTO_UPDATE_MODE.exclude}
- value={['plugin-1']}
- />,
- )
-
- // Assert
- expect(
- screen.getByText('plugin.autoUpdate.excludeUpdate:{"count":1,"num":1}'),
- ).toBeInTheDocument()
- })
- })
-
- describe('User Interactions', () => {
- it('should call onChange with empty array when clear is clicked', () => {
- // Arrange
- const onChange = vi.fn()
-
- // Act
- render(
- <PluginsPicker {...defaultProps} value={['plugin-1', 'plugin-2']} onChange={onChange} />,
- )
- fireEvent.click(
- screen.getByRole('button', { name: 'plugin.autoUpdate.operation.clearAll' }),
- )
-
- // Assert
- expect(onChange).toHaveBeenCalledWith([])
- })
- })
- })
-
- // ============================================================
- // AutoUpdateSetting Main Component Tests
- // ============================================================
- describe('AutoUpdateSetting (index.tsx)', () => {
- const defaultProps = {
- payload: createMockAutoUpdateConfig(),
- onChange: vi.fn(),
- }
-
- describe('Rendering', () => {
- it('should render update settings header', () => {
- // Act
- render(<AutoUpdateSetting {...defaultProps} />)
-
- // Assert
- expect(screen.getByText('plugin.autoUpdate.updateSettings')).toBeInTheDocument()
- })
-
- it('should render automatic updates label', () => {
- // Act
- render(<AutoUpdateSetting {...defaultProps} />)
-
- // Assert
- expect(screen.getByText('plugin.autoUpdate.automaticUpdates')).toBeInTheDocument()
- })
-
- it('should render strategy picker', () => {
- // Act
- render(<AutoUpdateSetting {...defaultProps} />)
-
- // Assert
- expect(
- screen.getByRole('button', { name: /plugin\.autoUpdate\.strategy\.fixOnly\.name/i }),
- ).toBeInTheDocument()
- })
-
- it('should show time picker when strategy is not disabled', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(screen.getByText('plugin.autoUpdate.updateTime')).toBeInTheDocument()
- })
-
- it('should hide time picker and plugins selection when strategy is disabled', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.disabled,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(screen.queryByText('plugin.autoUpdate.updateTime')).not.toBeInTheDocument()
- })
-
- it('should show plugins picker when mode is not update_all', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.partial,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(screen.getByText('plugin.autoUpdate.operation.select')).toBeInTheDocument()
- })
-
- it('should hide plugins picker when mode is update_all', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.update_all,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(screen.queryByText('plugin.autoUpdate.operation.select')).not.toBeInTheDocument()
- })
- })
-
- describe('Strategy Description', () => {
- it('should show fixOnly description when strategy is fixOnly', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(
- screen.getByText('plugin.autoUpdate.strategy.fixOnly.selectedDescription'),
- ).toBeInTheDocument()
- })
-
- it('should show latest description when strategy is latest', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.latest,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(
- screen.getByText('plugin.autoUpdate.strategy.latest.selectedDescription'),
- ).toBeInTheDocument()
- })
-
- it('should show no description when strategy is disabled', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.disabled,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(
- screen.queryByText('plugin.autoUpdate.strategy.fixOnly.selectedDescription'),
- ).not.toBeInTheDocument()
- expect(
- screen.queryByText('plugin.autoUpdate.strategy.latest.selectedDescription'),
- ).not.toBeInTheDocument()
- })
- })
-
- describe('Plugins Selection', () => {
- it('should show include_plugins when mode is partial', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.partial,
- include_plugins: ['plugin-1', 'plugin-2'],
- exclude_plugins: [],
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(
- screen.getByText('plugin.autoUpdate.partialUPdate:{"count":2,"num":2}'),
- ).toBeInTheDocument()
- })
-
- it('should show exclude_plugins when mode is exclude', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.exclude,
- include_plugins: [],
- exclude_plugins: ['plugin-1', 'plugin-2', 'plugin-3'],
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(
- screen.getByText('plugin.autoUpdate.excludeUpdate:{"count":3,"num":3}'),
- ).toBeInTheDocument()
- })
- })
-
- describe('User Interactions', () => {
- it('should call onChange with updated strategy when strategy changes', async () => {
- // Arrange
- const user = userEvent.setup()
- const onChange = vi.fn()
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- })
-
- // Act
- render(<AutoUpdateSetting payload={payload} onChange={onChange} />)
-
- await user.click(
- screen.getByRole('button', { name: /plugin\.autoUpdate\.strategy\.latest\.name/i }),
- )
-
- // Assert
- expect(onChange).toHaveBeenCalledWith(
- expect.objectContaining({ strategy_setting: AUTO_UPDATE_STRATEGY.latest }),
- )
- })
-
- it('should call onChange with include_plugins when in partial mode', () => {
- // Arrange
- const onChange = vi.fn()
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.partial,
- include_plugins: ['existing-plugin'],
- })
-
- // Act
- render(<AutoUpdateSetting payload={payload} onChange={onChange} />)
-
- // Click clear all
- fireEvent.click(
- screen.getByRole('button', { name: 'plugin.autoUpdate.operation.clearAll' }),
- )
-
- // Assert
- expect(onChange).toHaveBeenCalledWith(
- expect.objectContaining({
- include_plugins: [],
- }),
- )
- })
-
- it('should call onChange with exclude_plugins when in exclude mode', () => {
- // Arrange
- const onChange = vi.fn()
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.exclude,
- exclude_plugins: ['existing-plugin'],
- })
-
- // Act
- render(<AutoUpdateSetting payload={payload} onChange={onChange} />)
-
- // Click clear all
- fireEvent.click(
- screen.getByRole('button', { name: 'plugin.autoUpdate.operation.clearAll' }),
- )
-
- // Assert
- expect(onChange).toHaveBeenCalledWith(
- expect.objectContaining({
- exclude_plugins: [],
- }),
- )
- })
-
- it('should open account settings when timezone link is clicked', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
- fireEvent.click(screen.getByText('autoUpdate.changeTimezone'))
-
- // Assert
- expect(mockSetSettingsDestination).toHaveBeenCalledWith('preferences')
- })
- })
-
- describe('Callback Memoization', () => {
- it('handleChange should preserve other config values', () => {
- // Arrange
- const onChange = vi.fn()
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_time_of_day: 36000,
- upgrade_mode: AUTO_UPDATE_MODE.partial,
- include_plugins: ['plugin-1'],
- exclude_plugins: [],
- })
-
- // Act
- render(<AutoUpdateSetting payload={payload} onChange={onChange} />)
-
- // Trigger a change (clear plugins)
- fireEvent.click(
- screen.getByRole('button', { name: 'plugin.autoUpdate.operation.clearAll' }),
- )
-
- // Assert - other values should be preserved
- expect(onChange).toHaveBeenCalledWith(
- expect.objectContaining({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_time_of_day: 36000,
- upgrade_mode: AUTO_UPDATE_MODE.partial,
- }),
- )
- })
-
- it('handlePluginsChange should not update when mode is update_all', () => {
- // Arrange
- const onChange = vi.fn()
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.update_all,
- })
-
- // Act
- render(<AutoUpdateSetting payload={payload} onChange={onChange} />)
-
- // Plugin picker should not be visible in update_all mode
- expect(screen.queryByText('plugin.autoUpdate.operation.clearAll')).not.toBeInTheDocument()
- })
- })
-
- describe('Memoization Logic', () => {
- it('strategyDescription should update when strategy_setting changes', () => {
- // Arrange
- const payload1 = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- })
- const { rerender } = render(<AutoUpdateSetting {...defaultProps} payload={payload1} />)
-
- // Assert initial
- expect(
- screen.getByText('plugin.autoUpdate.strategy.fixOnly.selectedDescription'),
- ).toBeInTheDocument()
-
- // Act - change strategy
- const payload2 = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.latest,
- })
- rerender(<AutoUpdateSetting {...defaultProps} payload={payload2} />)
-
- // Assert updated
- expect(
- screen.getByText('plugin.autoUpdate.strategy.latest.selectedDescription'),
- ).toBeInTheDocument()
- })
-
- it('plugins should reflect correct list based on upgrade_mode', () => {
- // Arrange
- const partialPayload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.partial,
- include_plugins: ['include-1', 'include-2'],
- exclude_plugins: ['exclude-1'],
- })
- const { rerender } = render(
- <AutoUpdateSetting {...defaultProps} payload={partialPayload} />,
- )
-
- // Assert - partial mode shows include_plugins count
- expect(
- screen.getByText('plugin.autoUpdate.partialUPdate:{"count":2,"num":2}'),
- ).toBeInTheDocument()
-
- // Act - change to exclude mode
- const excludePayload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.exclude,
- include_plugins: ['include-1', 'include-2'],
- exclude_plugins: ['exclude-1'],
- })
- rerender(<AutoUpdateSetting {...defaultProps} payload={excludePayload} />)
-
- // Assert - exclude mode shows exclude_plugins count
- expect(
- screen.getByText('plugin.autoUpdate.excludeUpdate:{"count":1,"num":1}'),
- ).toBeInTheDocument()
- })
- })
-
- describe('Edge Cases', () => {
- it('should handle empty payload values gracefully', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- include_plugins: [],
- exclude_plugins: [],
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(screen.getByText('plugin.autoUpdate.updateSettings')).toBeInTheDocument()
- })
-
- it('should render timezone offset correctly', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert - should show timezone offset
- expect(screen.getByText('GMT-5')).toBeInTheDocument()
- })
- })
-
- describe('Upgrade Mode Options', () => {
- it('should render all three upgrade mode options', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(screen.getByText('plugin.autoUpdate.upgradeMode.all')).toBeInTheDocument()
- expect(screen.getByText('plugin.autoUpdate.upgradeMode.exclude')).toBeInTheDocument()
- expect(screen.getByText('plugin.autoUpdate.upgradeMode.partial')).toBeInTheDocument()
- })
-
- it('should highlight selected upgrade mode', () => {
- // Arrange
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.partial,
- })
-
- // Act
- render(<AutoUpdateSetting {...defaultProps} payload={payload} />)
-
- // Assert
- expect(
- screen.getByRole('button', { name: 'plugin.autoUpdate.upgradeMode.all' }),
- ).toHaveAttribute('aria-pressed', 'false')
- expect(
- screen.getByRole('button', { name: 'plugin.autoUpdate.upgradeMode.exclude' }),
- ).toHaveAttribute('aria-pressed', 'false')
- expect(
- screen.getByRole('button', { name: 'plugin.autoUpdate.upgradeMode.partial' }),
- ).toHaveAttribute('aria-pressed', 'true')
- })
-
- it('should call onChange when upgrade mode is changed', () => {
- // Arrange
- const onChange = vi.fn()
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.update_all,
- })
-
- // Act
- render(<AutoUpdateSetting payload={payload} onChange={onChange} />)
-
- // Click on partial mode
- const partialOption = screen.getByText('plugin.autoUpdate.upgradeMode.partial')
- fireEvent.click(partialOption)
-
- // Assert
- expect(onChange).toHaveBeenCalledWith(
- expect.objectContaining({
- upgrade_mode: AUTO_UPDATE_MODE.partial,
- }),
- )
- })
- })
- })
-
- // ============================================================
- // Integration Tests
- // ============================================================
- describe('Integration', () => {
- it('should handle full workflow: enable updates, set time, select plugins', () => {
- // Arrange
- const onChange = vi.fn()
- let currentPayload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.disabled,
- })
-
- const { rerender } = render(
- <AutoUpdateSetting payload={currentPayload} onChange={onChange} />,
- )
-
- // Assert - initially disabled
- expect(screen.queryByText('plugin.autoUpdate.updateTime')).not.toBeInTheDocument()
-
- // Simulate enabling updates
- currentPayload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.partial,
- include_plugins: [],
- })
- rerender(<AutoUpdateSetting payload={currentPayload} onChange={onChange} />)
-
- // Assert - time picker and plugins visible
- expect(screen.getByText('plugin.autoUpdate.updateTime')).toBeInTheDocument()
- expect(screen.getByText('plugin.autoUpdate.operation.select')).toBeInTheDocument()
- })
-
- it('should maintain state consistency when switching modes', () => {
- // Arrange
- const onChange = vi.fn()
- const payload = createMockAutoUpdateConfig({
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_mode: AUTO_UPDATE_MODE.partial,
- include_plugins: ['plugin-1'],
- exclude_plugins: ['plugin-2'],
- })
-
- // Act
- render(<AutoUpdateSetting payload={payload} onChange={onChange} />)
-
- // Assert - partial mode shows include_plugins
- expect(
- screen.getByText('plugin.autoUpdate.partialUPdate:{"count":1,"num":1}'),
- ).toBeInTheDocument()
- })
- })
-})
diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/strategy-picker.spec.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/strategy-picker.spec.tsx
deleted file mode 100644
index 034cc3d9a7e..00000000000
--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/strategy-picker.spec.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import { describe, expect, it, vi } from 'vitest'
-import StrategyPicker from '../strategy-picker'
-import { AUTO_UPDATE_STRATEGY } from '../types'
-
-const triggerName = (key: string) =>
- new RegExp(`plugin\\.autoUpdate\\.strategy\\.${key}\\.name`, 'i')
-
-describe('StrategyPicker', () => {
- it('renders all strategy toggle options', () => {
- render(<StrategyPicker value={AUTO_UPDATE_STRATEGY.fixOnly} onChange={vi.fn()} />)
-
- expect(
- screen.getByRole('group', { name: 'plugin.autoUpdate.automaticUpdates' }),
- ).toBeInTheDocument()
- expect(screen.getByRole('button', { name: triggerName('disabled') })).toBeInTheDocument()
- expect(screen.getByRole('button', { name: triggerName('fixOnly') })).toBeInTheDocument()
- expect(screen.getByRole('button', { name: triggerName('latest') })).toBeInTheDocument()
- })
-
- it('marks only the currently selected strategy as pressed', () => {
- render(<StrategyPicker value={AUTO_UPDATE_STRATEGY.fixOnly} onChange={vi.fn()} />)
-
- const buttons = screen.getAllByRole('button')
- const pressedOptions = buttons.filter((item) => item.getAttribute('aria-pressed') === 'true')
-
- expect(pressedOptions).toHaveLength(1)
- expect(pressedOptions[0]).toHaveTextContent('plugin.autoUpdate.strategy.fixOnly.name')
- })
-
- it('calls onChange when a new strategy is selected', async () => {
- const onChange = vi.fn()
- render(<StrategyPicker value={AUTO_UPDATE_STRATEGY.disabled} onChange={onChange} />)
-
- fireEvent.click(screen.getByRole('button', { name: triggerName('latest') }))
-
- expect(onChange).toHaveBeenCalledWith(AUTO_UPDATE_STRATEGY.latest)
- })
-})
diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/index.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/index.tsx
deleted file mode 100644
index 00d1110f286..00000000000
--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/index.tsx
+++ /dev/null
@@ -1,268 +0,0 @@
-'use client'
-import type { FC } from 'react'
-import type { AutoUpdateConfig } from './types'
-import type {
- TimePickerProps,
- TriggerParams,
-} from '@/app/components/base/date-and-time-picker/types'
-import { cn } from '@langgenius/dify-ui/cn'
-import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'
-import { RiTimeLine } from '@remixicon/react'
-import { useQuery } from '@tanstack/react-query'
-import { useQueryState } from 'nuqs'
-import * as React from 'react'
-import { useCallback, useMemo } from 'react'
-import { Trans, useTranslation } from 'react-i18next'
-import TimePicker from '@/app/components/base/date-and-time-picker/time-picker'
-import { convertTimezoneToOffsetStr } from '@/app/components/base/date-and-time-picker/utils/dayjs'
-import {
- settingsQueryParamName,
- settingsQueryParser,
-} from '@/app/components/header/account-setting/query-params'
-import { userProfileQueryOptions } from '@/features/account-profile/client'
-import Label from '../label'
-import PluginsPicker from './plugins-picker'
-import StrategyPicker from './strategy-picker'
-import { AUTO_UPDATE_MODE, AUTO_UPDATE_STRATEGY } from './types'
-import {
- convertLocalSecondsToUTCDaySeconds,
- convertUTCDaySecondsToLocalSeconds,
- dayjsToTimeOfDay,
- timeOfDayToDayjs,
-} from './utils'
-
-const i18nPrefix = 'autoUpdate'
-
-type Props = Readonly<{
- payload: AutoUpdateConfig
- onChange: (payload: AutoUpdateConfig) => void
-}>
-
-const SettingTimeZone: FC<{
- children?: React.ReactNode
-}> = ({ children }) => {
- const [, setSettingsDestination] = useQueryState(settingsQueryParamName, settingsQueryParser)
- return (
- <button
- type="button"
- className="cursor-pointer border-none bg-transparent p-0 text-left body-xs-regular text-text-accent focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"
- onClick={() => setSettingsDestination('preferences')}
- >
- {children}
- </button>
- )
-}
-const AutoUpdateSetting: FC<Props> = ({ payload, onChange }) => {
- const { t } = useTranslation()
- const { data: timezone } = useQuery({
- ...userProfileQueryOptions(),
- select: (data) => data.profile.timezone ?? undefined,
- })
-
- const { strategy_setting, upgrade_time_of_day, upgrade_mode, exclude_plugins, include_plugins } =
- payload
-
- const minuteFilter = useCallback((minutes: string[]) => {
- return minutes.filter((m) => {
- const time = Number.parseInt(m, 10)
- return time % 15 === 0
- })
- }, [])
- const strategyDescription = useMemo(() => {
- switch (strategy_setting) {
- case AUTO_UPDATE_STRATEGY.fixOnly:
- return t(($) => $[`${i18nPrefix}.strategy.fixOnly.selectedDescription`], { ns: 'plugin' })
- case AUTO_UPDATE_STRATEGY.latest:
- return t(($) => $[`${i18nPrefix}.strategy.latest.selectedDescription`], { ns: 'plugin' })
- default:
- return ''
- }
- }, [strategy_setting, t])
-
- const plugins = useMemo(() => {
- switch (upgrade_mode) {
- case AUTO_UPDATE_MODE.partial:
- return include_plugins
- case AUTO_UPDATE_MODE.exclude:
- return exclude_plugins
- default:
- return []
- }
- }, [upgrade_mode, exclude_plugins, include_plugins])
- const scopeOptions = useMemo(
- () => [
- {
- value: AUTO_UPDATE_MODE.update_all,
- label: t(($) => $[`${i18nPrefix}.upgradeMode.${AUTO_UPDATE_MODE.update_all}`], {
- ns: 'plugin',
- }),
- },
- {
- value: AUTO_UPDATE_MODE.exclude,
- label: t(($) => $[`${i18nPrefix}.upgradeMode.${AUTO_UPDATE_MODE.exclude}`], {
- ns: 'plugin',
- }),
- },
- {
- value: AUTO_UPDATE_MODE.partial,
- label: t(($) => $[`${i18nPrefix}.upgradeMode.${AUTO_UPDATE_MODE.partial}`], {
- ns: 'plugin',
- }),
- },
- ],
- [t],
- )
-
- const handlePluginsChange = useCallback(
- (newPlugins: string[]) => {
- if (upgrade_mode === AUTO_UPDATE_MODE.partial) {
- onChange({
- ...payload,
- include_plugins: newPlugins,
- })
- } else if (upgrade_mode === AUTO_UPDATE_MODE.exclude) {
- onChange({
- ...payload,
- exclude_plugins: newPlugins,
- })
- }
- },
- [payload, upgrade_mode, onChange],
- )
- const handleChange = useCallback(
- (key: keyof AutoUpdateConfig) => {
- return (value: AutoUpdateConfig[keyof AutoUpdateConfig]) => {
- onChange({
- ...payload,
- [key]: value,
- })
- }
- },
- [payload, onChange],
- )
-
- const renderTimePickerTrigger = useCallback<NonNullable<TimePickerProps['renderTrigger']>>(
- (props, state, { inputElem, onClick }: TriggerParams) => {
- return (
- <button
- {...props}
- type="button"
- className={cn(
- 'group flex h-8 w-40 cursor-pointer items-center justify-between rounded-lg border-none bg-components-input-bg-normal px-2 text-left hover:bg-state-base-hover-alt focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden',
- props.className,
- )}
- onClick={(event) => {
- onClick(event)
- props.onClick?.(event)
- }}
- >
- <div className="flex w-0 grow items-center gap-x-1">
- <RiTimeLine
- className={cn(
- 'size-4 shrink-0 text-text-tertiary',
- state.open ? 'text-text-secondary' : 'group-hover:text-text-secondary',
- )}
- />
- {inputElem}
- </div>
- <div className="system-sm-regular text-text-tertiary">
- {convertTimezoneToOffsetStr(timezone)}
- </div>
- </button>
- )
- },
- [timezone],
- )
-
- return (
- <div className="self-stretch px-6">
- <div className="my-3 flex items-center">
- <div className="system-xs-medium-uppercase text-text-tertiary">
- {t(($) => $[`${i18nPrefix}.updateSettings`], { ns: 'plugin' })}
- </div>
- <div className="ml-2 h-px grow bg-divider-subtle"></div>
- </div>
-
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <Label
- label={t(($) => $[`${i18nPrefix}.automaticUpdates`], { ns: 'plugin' })}
- description={strategyDescription}
- />
- <StrategyPicker value={strategy_setting} onChange={handleChange('strategy_setting')} />
- </div>
- {strategy_setting !== AUTO_UPDATE_STRATEGY.disabled && (
- <>
- <div className="flex items-center justify-between">
- <Label label={t(($) => $[`${i18nPrefix}.updateTime`], { ns: 'plugin' })} />
- <div className="flex flex-col items-end">
- <TimePicker
- value={timeOfDayToDayjs(
- convertUTCDaySecondsToLocalSeconds(upgrade_time_of_day, timezone!),
- )}
- timezone={timezone}
- onChange={(v) =>
- handleChange('upgrade_time_of_day')(
- convertLocalSecondsToUTCDaySeconds(dayjsToTimeOfDay(v), timezone!),
- )
- }
- onClear={() =>
- handleChange('upgrade_time_of_day')(
- convertLocalSecondsToUTCDaySeconds(0, timezone!),
- )
- }
- title={t(($) => $[`${i18nPrefix}.updateTime`], { ns: 'plugin' })}
- minuteFilter={minuteFilter}
- renderTrigger={renderTimePickerTrigger}
- placement="bottom-end"
- />
- <div className="mt-1 text-right body-xs-regular text-text-tertiary">
- <Trans
- i18nKey={($) => $[`${i18nPrefix}.changeTimezone`]}
- ns="plugin"
- components={{
- setTimezone: <SettingTimeZone />,
- }}
- />
- </div>
- </div>
- </div>
- <div>
- <Label
- label={t(($) => $[`${i18nPrefix}.specifyPluginsToUpdate`], { ns: 'plugin' })}
- />
- <SegmentedControl<AUTO_UPDATE_MODE>
- aria-label={t(($) => $[`${i18nPrefix}.specifyPluginsToUpdate`], { ns: 'plugin' })}
- className="mt-1 flex w-full"
- value={[upgrade_mode]}
- onValueChange={(nextValue) => {
- const selectedValue = nextValue[0]
- if (selectedValue) handleChange('upgrade_mode')(selectedValue)
- }}
- >
- {scopeOptions.map((option) => (
- <SegmentedControlItem<AUTO_UPDATE_MODE>
- key={option.value}
- value={option.value}
- className="flex-1 hover:bg-state-base-hover-alt data-pressed:text-text-accent-light-mode-only data-pressed:hover:bg-components-segmented-control-item-active-bg"
- >
- <span className="p-0.5 whitespace-nowrap">{option.label}</span>
- </SegmentedControlItem>
- ))}
- </SegmentedControl>
-
- {upgrade_mode !== AUTO_UPDATE_MODE.update_all && (
- <PluginsPicker
- value={plugins}
- onChange={handlePluginsChange}
- updateMode={upgrade_mode}
- />
- )}
- </div>
- </>
- )}
- </div>
- </div>
- )
-}
-export default React.memo(AutoUpdateSetting)
diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/strategy-picker.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/strategy-picker.tsx
deleted file mode 100644
index acb29a472db..00000000000
--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/strategy-picker.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'
-import { useTranslation } from 'react-i18next'
-import { AUTO_UPDATE_STRATEGY } from './types'
-
-const i18nPrefix = 'autoUpdate.strategy'
-
-type Props = Readonly<{
- value: AUTO_UPDATE_STRATEGY
- onChange: (value: AUTO_UPDATE_STRATEGY) => void
-}>
-const StrategyPicker = ({ value, onChange }: Props) => {
- const { t } = useTranslation()
- const options = [
- {
- value: AUTO_UPDATE_STRATEGY.disabled,
- label: t(($) => $[`${i18nPrefix}.disabled.name`], { ns: 'plugin' }),
- },
- {
- value: AUTO_UPDATE_STRATEGY.fixOnly,
- label: t(($) => $[`${i18nPrefix}.fixOnly.name`], { ns: 'plugin' }),
- },
- {
- value: AUTO_UPDATE_STRATEGY.latest,
- label: t(($) => $[`${i18nPrefix}.latest.name`], { ns: 'plugin' }),
- },
- ]
-
- return (
- <SegmentedControl<AUTO_UPDATE_STRATEGY>
- aria-label={t(($) => $['autoUpdate.automaticUpdates'], { ns: 'plugin' })}
- className="w-81.5"
- value={[value]}
- onValueChange={(nextValue) => {
- const selectedValue = nextValue[0]
- if (selectedValue) onChange(selectedValue)
- }}
- >
- {options.map((option) => (
- <SegmentedControlItem<AUTO_UPDATE_STRATEGY>
- key={option.value}
- value={option.value}
- className="flex-1 hover:bg-state-base-hover-alt data-pressed:text-text-accent-light-mode-only data-pressed:hover:bg-components-segmented-control-item-active-bg"
- >
- <span className="p-0.5 whitespace-nowrap">{option.label}</span>
- </SegmentedControlItem>
- ))}
- </SegmentedControl>
- )
-}
-
-export default StrategyPicker
diff --git a/web/app/components/plugins/reference-setting-modal/index.tsx b/web/app/components/plugins/reference-setting-modal/index.tsx
deleted file mode 100644
index a49e0118624..00000000000
--- a/web/app/components/plugins/reference-setting-modal/index.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-'use client'
-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 { Dialog, DialogCloseButton, DialogContent } from '@langgenius/dify-ui/dialog'
-import { useSuspenseQuery } from '@tanstack/react-query'
-import * as React from 'react'
-import { useCallback, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { PermissionType } from '@/app/components/plugins/types'
-import OptionCard from '@/app/components/workflow/nodes/_base/components/option-card'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
-import AutoUpdateSetting from './auto-update-setting'
-import { AUTO_UPDATE_MODE, AUTO_UPDATE_STRATEGY } from './auto-update-setting/types'
-import Label from './label'
-
-const i18nPrefix = 'privilege'
-const autoUpdateDefaultValue: AutoUpdateConfig = {
- strategy_setting: AUTO_UPDATE_STRATEGY.fixOnly,
- upgrade_time_of_day: 36000,
- upgrade_mode: AUTO_UPDATE_MODE.update_all,
- exclude_plugins: [],
- include_plugins: [],
-}
-
-type Props = Readonly<{
- payload: ReferenceSetting
- canSetPermissions?: boolean
- canSetAutoUpdate?: boolean
- onHide: () => void
- onSave: (payload: ReferenceSetting) => void
-}>
-
-const PluginSettingModal: FC<Props> = ({
- payload,
- canSetPermissions = false,
- canSetAutoUpdate = false,
- onHide,
- onSave,
-}) => {
- const { t } = useTranslation()
- const { auto_upgrade: autoUpdateConfig, permission: privilege } = payload || {}
- const [tempPrivilege, setTempPrivilege] = useState<Permissions>(privilege)
- const [tempAutoUpdateConfig, setTempAutoUpdateConfig] = useState<AutoUpdateConfig>(
- autoUpdateConfig || autoUpdateDefaultValue,
- )
- const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
- const isPermissionDisabledByRBAC = systemFeatures.rbac_enabled
- const permissionDisabledTip = t(($) => $[`${i18nPrefix}.configurePermissionsInSettings`], {
- ns: 'plugin',
- })
- const handlePrivilegeChange = useCallback(
- (key: string) => {
- return (value: PermissionType) => {
- if (isPermissionDisabledByRBAC) return
- setTempPrivilege({
- ...tempPrivilege,
- [key]: value,
- })
- }
- },
- [isPermissionDisabledByRBAC, tempPrivilege],
- )
-
- const handleSave = useCallback(async () => {
- await onSave({
- permission: canSetPermissions ? tempPrivilege : privilege || tempPrivilege,
- auto_upgrade: canSetAutoUpdate
- ? tempAutoUpdateConfig
- : autoUpdateConfig || tempAutoUpdateConfig,
- })
- onHide()
- }, [
- autoUpdateConfig,
- canSetAutoUpdate,
- canSetPermissions,
- onHide,
- onSave,
- privilege,
- tempAutoUpdateConfig,
- tempPrivilege,
- ])
-
- return (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) onHide()
- }}
- >
- <DialogContent className="w-155 max-w-155 overflow-hidden! border-none p-0! text-left align-middle">
- <DialogCloseButton />
-
- <div className="shadows-shadow-xl flex w-full flex-col items-start rounded-2xl border border-components-panel-border bg-components-panel-bg">
- <div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
- <span className="self-stretch title-2xl-semi-bold text-text-primary">
- {t(($) => $[`${i18nPrefix}.title`], { ns: 'plugin' })}
- </span>
- </div>
- {canSetPermissions && (
- <div className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3">
- {[
- {
- title: t(($) => $[`${i18nPrefix}.whoCanInstall`], { ns: 'plugin' }),
- key: 'install_permission',
- value: tempPrivilege?.install_permission || PermissionType.noOne,
- },
- {
- title: t(($) => $[`${i18nPrefix}.whoCanDebug`], { ns: 'plugin' }),
- key: 'debug_permission',
- value: tempPrivilege?.debug_permission || PermissionType.noOne,
- },
- ].map(({ title, key, value }) => (
- <div key={key} className="flex flex-col items-start gap-1 self-stretch">
- <Label
- label={title}
- tooltip={isPermissionDisabledByRBAC ? permissionDisabledTip : undefined}
- />
- <div className="flex w-full items-start justify-between gap-2">
- {[PermissionType.everyone, PermissionType.admin, PermissionType.noOne].map(
- (option) => (
- <OptionCard
- key={option}
- title={t(($) => $[`${i18nPrefix}.${option}`], { ns: 'plugin' })}
- onSelect={() => handlePrivilegeChange(key)(option)}
- selected={value === option}
- disabled={isPermissionDisabledByRBAC}
- className="flex-1"
- />
- ),
- )}
- </div>
- </div>
- ))}
- </div>
- )}
- {systemFeatures.enable_marketplace && canSetAutoUpdate && (
- <AutoUpdateSetting payload={tempAutoUpdateConfig} onChange={setTempAutoUpdateConfig} />
- )}
- <div className="flex h-19 items-center justify-end gap-2 self-stretch p-6 pt-5">
- <Button className="min-w-18" onClick={onHide}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- <Button className="min-w-18" variant="primary" onClick={handleSave}>
- {t(($) => $['operation.save'], { ns: 'common' })}
- </Button>
- </div>
- </div>
- </DialogContent>
- </Dialog>
- )
-}
-
-export default React.memo(PluginSettingModal)
diff --git a/web/app/components/plugins/reference-setting-modal/label.tsx b/web/app/components/plugins/reference-setting-modal/label.tsx
deleted file mode 100644
index efa80ca2aa4..00000000000
--- a/web/app/components/plugins/reference-setting-modal/label.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-'use client'
-import type { FC } from 'react'
-import { cn } from '@langgenius/dify-ui/cn'
-import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import * as React from 'react'
-
-type Props = Readonly<{
- label: string
- description?: string
- tooltip?: string
-}>
-
-const Label: FC<Props> = ({ label, description, tooltip }) => {
- const tooltipIcon = (
- <span
- aria-label={tooltip}
- className="ml-1 flex size-4 shrink-0 cursor-pointer items-center justify-center"
- >
- <span aria-hidden className="i-ri-question-line size-3.5 text-text-quaternary" />
- </span>
- )
-
- return (
- <div>
- <div className={cn('flex h-6 items-center', description && 'h-4')}>
- <span className="system-sm-semibold text-text-secondary">{label}</span>
- {tooltip && (
- <Tooltip>
- <TooltipTrigger render={tooltipIcon} />
- <TooltipContent>{tooltip}</TooltipContent>
- </Tooltip>
- )}
- </div>
- {description && <div className="mt-1 body-xs-regular text-text-tertiary">{description}</div>}
- </div>
- )
-}
-export default React.memo(Label)