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.

test(web): exercise real tool configuration and plugin entry owners (#44726)

Stephen Zhou8eb1c94ef77d
diff --git a/web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx
index a1512238b1c..e6359a6dc31 100644
--- a/web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/index.spec.tsx
@@ -1,437 +1,267 @@
-import type { PropsWithChildren } from 'react'
-import type { Mock } from 'vite-plus/test'
-import type SettingBuiltInToolType from '../setting-built-in-tool'
-import type { Tool, ToolParameter } from '@/app/components/tools/types'
-import type ToolPickerType from '@/app/components/workflow/block-selector/tool-picker'
-import type { ToolDefaultValue } from '@/app/components/workflow/block-selector/types'
-import type { ToolWithProvider } from '@/app/components/workflow/types'
import type { ModelConfig } from '@/models/debug'
import type { AgentTool } from '@/types/app'
-import { zToolProviderApiEntityResponse } from '@dify/contracts/api/console/workspaces/zod.gen'
-import { screen, waitFor } from '@testing-library/react'
+import { zToolApiEntity } from '@dify/contracts/api/console/workspaces/zod.gen'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import * as React from 'react'
import { useEffect, useMemo, useState } from 'react'
import { CollectionType } from '@/app/components/tools/types'
-import {
- DEFAULT_AGENT_SETTING,
- DEFAULT_CHAT_PROMPT_CONFIG,
- DEFAULT_COMPLETION_PROMPT_CONFIG,
-} from '@/config'
import ConfigContext from '@/context/debug-configuration'
+import { EventEmitterContextProvider } from '@/context/event-emitter-provider'
import { consoleQuery } from '@/service/console'
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
-import { createDebugConfigurationFixture } from '@/test/fixtures/debug-configuration'
-import { ModelModeType } from '@/types/app'
+import { createToolProviderFixture } from '@/test/console/tool-provider-fixture'
+import {
+ createDebugConfigurationFixture,
+ createModelConfigFixture,
+} from '@/test/fixtures/debug-configuration'
+import { createNuqsTestWrapper } from '@/test/nuqs-testing'
import { writeTextToClipboard } from '@/utils/clipboard'
import AgentTools from '../index'
-const formattingDispatcherMock = vi.fn()
-vi.mock('@/app/components/app/configuration/debug/hooks', () => ({
- useFormattingChangedDispatcher: () => formattingDispatcherMock,
-}))
-
-let builtInTools: ToolWithProvider[] = []
-let customTools: ToolWithProvider[] = []
-let workflowTools: ToolWithProvider[] = []
-let mcpTools: ToolWithProvider[] = []
-type ToolPickerProps = React.ComponentProps<typeof ToolPickerType>
-let singleToolSelection: ToolDefaultValue | null = null
-let multipleToolSelection: ToolDefaultValue[] = []
-const ToolPickerMock = (props: ToolPickerProps) => (
- <div data-testid="tool-picker">
- <div>{props.trigger}</div>
- <button
- type="button"
- onClick={() => singleToolSelection && props.onSelect(singleToolSelection)}
- >
- pick-single
- </button>
- <button type="button" onClick={() => props.onSelectMultiple(multipleToolSelection)}>
- pick-multiple
- </button>
- </div>
-)
-vi.mock('@/app/components/workflow/block-selector/tool-picker', () => ({
- default: (props: ToolPickerProps) => <ToolPickerMock {...props} />,
-}))
-
-type SettingBuiltInToolProps = React.ComponentProps<typeof SettingBuiltInToolType>
-let settingPanelSavePayload: Record<string, unknown> = {}
-let settingPanelCredentialId = 'credential-from-panel'
-const SettingBuiltInToolMock = (props: SettingBuiltInToolProps) => {
- return (
- <div data-testid="setting-built-in-tool">
- <span>{props.toolName}</span>
- <button type="button" onClick={() => props.onSave?.(settingPanelSavePayload)}>
- save-from-panel
- </button>
- <button
- type="button"
- onClick={() => props.onAuthorizationItemClick?.(settingPanelCredentialId)}
- >
- auth-from-panel
- </button>
- <button type="button" onClick={props.onHide}>
- close-panel
- </button>
- </div>
- )
-}
-vi.mock('../setting-built-in-tool', () => ({
- default: (props: SettingBuiltInToolProps) => <SettingBuiltInToolMock {...props} />,
+// Credential loading and clipboard writes are external boundaries. The picker,
+// settings drawer, authorization menu and configuration caller remain live.
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ get: async (url: string) => {
+ if (
+ !url.startsWith('/workspaces/current/tool-provider/builtin/vendor/provider-1/credential/info')
+ )
+ throw new Error(`Unexpected request: ${url}`)
+ return {
+ supported_credential_types: ['api-key'],
+ is_oauth_custom_client_enabled: false,
+ credentials: [
+ {
+ id: 'credential-search',
+ name: 'Search credential',
+ provider: 'vendor/provider-1',
+ credential_type: 'api-key',
+ is_default: true,
+ },
+ {
+ id: 'credential-translate',
+ name: 'Translate credential',
+ provider: 'vendor/provider-1',
+ credential_type: 'api-key',
+ is_default: false,
+ },
+ {
+ id: 'credential-updated',
+ name: 'Replacement credential',
+ provider: 'vendor/provider-1',
+ credential_type: 'api-key',
+ is_default: false,
+ },
+ ],
+ }
+ },
}))
vi.mock('@/utils/clipboard', () => ({
writeTextToClipboard: vi.fn().mockResolvedValue(undefined),
}))
-const writeTextToClipboardMock = writeTextToClipboard as Mock
-
-const createToolParameter = (overrides?: Partial<ToolParameter>): ToolParameter => ({
- name: 'api_key',
- label: {
- en_US: 'API Key',
- zh_Hans: 'API Key',
- },
- human_description: {
- en_US: 'desc',
- zh_Hans: 'desc',
- },
- type: 'string',
- form: 'form',
- llm_description: '',
- required: true,
- multiple: false,
- default: 'default',
- ...overrides,
-})
-
-const createToolDefinition = (overrides?: Partial<Tool>): Tool => ({
- name: 'search',
- author: 'tester',
- label: {
- en_US: 'Search',
- zh_Hans: 'Search',
- },
- description: {
- en_US: 'desc',
- zh_Hans: 'desc',
- },
- parameters: [createToolParameter()],
- labels: [],
- output_schema: {},
- ...overrides,
-})
-
-const createCollection = (overrides?: Partial<ToolWithProvider>): ToolWithProvider => ({
- id: overrides?.id || 'provider-1',
- name: overrides?.name || 'vendor/provider-1',
- author: 'tester',
- description: {
- en_US: 'desc',
- zh_Hans: 'desc',
- },
- icon: 'https://example.com/icon.png',
- label: {
- en_US: 'Provider Label',
- zh_Hans: 'Provider Label',
- },
- type: overrides?.type || CollectionType.builtIn,
- team_credentials: {},
- is_team_authorization: true,
- allow_delete: true,
- labels: [],
- tools: overrides?.tools || [createToolDefinition()],
- meta: {
- version: '1.0.0',
- },
- ...overrides,
-})
+const createTool = (name: string, label: string) =>
+ zToolApiEntity.parse({
+ name,
+ author: 'tester',
+ label: { en_US: label },
+ description: { en_US: `${label} documents` },
+ parameters: [
+ {
+ name: 'api_key',
+ label: { en_US: 'API Key' },
+ human_description: { en_US: 'API key for requests' },
+ type: 'string',
+ form: 'form',
+ required: true,
+ default: 'default-key',
+ },
+ ],
+ })
-const createAgentTool = (overrides?: Partial<AgentTool>): AgentTool => ({
- provider_id: overrides?.provider_id || 'provider-1',
- provider_type: overrides?.provider_type || CollectionType.builtIn,
- provider_name: overrides?.provider_name || 'vendor/provider-1',
- tool_name: overrides?.tool_name || 'search',
- tool_label: overrides?.tool_label || 'Search Tool',
- tool_parameters: overrides?.tool_parameters || { api_key: 'key' },
- enabled: overrides?.enabled ?? true,
+const createAgentTool = (overrides: Partial<AgentTool> = {}): AgentTool => ({
+ provider_id: 'provider-1',
+ provider_type: CollectionType.builtIn,
+ provider_name: 'vendor/provider-1',
+ tool_name: 'search',
+ tool_label: 'Search Tool',
+ tool_parameters: { api_key: 'original-key' },
+ enabled: true,
...overrides,
})
-const createModelConfig = (tools: AgentTool[]): ModelConfig => ({
- provider: 'OPENAI',
- model_id: 'gpt-3.5-turbo',
- mode: ModelModeType.chat,
- configs: {
- prompt_template: '',
- prompt_variables: [],
- },
- chat_prompt_config: DEFAULT_CHAT_PROMPT_CONFIG,
- completion_prompt_config: DEFAULT_COMPLETION_PROMPT_CONFIG,
- opening_statement: '',
- more_like_this: null,
- suggested_questions: [],
- suggested_questions_after_answer: null,
- speech_to_text: null,
- text_to_speech: null,
- file_upload: null,
- retriever_resource: null,
- sensitive_word_avoidance: null,
- annotation_reply: null,
- external_data_tools: [],
- dataSets: [],
- agentConfig: {
- ...DEFAULT_AGENT_SETTING,
- tools,
- },
-})
-
-const renderAgentTools = (initialTools?: AgentTool[]) => {
- const tools = initialTools ?? [createAgentTool()]
- const modelConfigRef = { current: createModelConfig(tools) }
- const Wrapper = ({ children }: PropsWithChildren) => {
- const [modelConfig, setModelConfig] = useState<ModelConfig>(modelConfigRef.current)
+const renderAgentTools = (initialTools: AgentTool[] = [createAgentTool()]) => {
+ let savedConfig = createModelConfigFixture()
+ const initialConfig = createModelConfigFixture({
+ agentConfig: { ...savedConfig.agentConfig, tools: initialTools },
+ })
+ savedConfig = initialConfig
+ const Caller = () => {
+ const [modelConfig, setModelConfig] = useState<ModelConfig>(initialConfig)
useEffect(() => {
- modelConfigRef.current = modelConfig
+ savedConfig = modelConfig
}, [modelConfig])
const value = useMemo(
- () =>
- createDebugConfigurationFixture({
- modelConfig,
- setModelConfig,
- }),
+ () => createDebugConfigurationFixture({ modelConfig, setModelConfig }),
[modelConfig],
)
- return <ConfigContext.Provider value={value}>{children}</ConfigContext.Provider>
+ return (
+ <ConfigContext.Provider value={value}>
+ <AgentTools />
+ </ConfigContext.Provider>
+ )
}
const queryClient = createConsoleQueryClient()
- for (const [operation, data] of [
- [consoleQuery.workspaces.current.tools.builtin.get, builtInTools],
- [consoleQuery.workspaces.current.tools.api.get, customTools],
- [consoleQuery.workspaces.current.tools.workflow.get, workflowTools],
- [consoleQuery.workspaces.current.tools.mcp.get, mcpTools],
- ] as const)
- queryClient.setQueryData(
- operation.queryOptions().queryKey,
- data.map((item) => zToolProviderApiEntityResponse.parse(item)),
- )
- const renderResult = renderWithConsoleQuery(
- <Wrapper>
- <AgentTools />
- </Wrapper>,
- { queryClient },
+ const tools = consoleQuery.workspaces.current.tools
+ queryClient.setQueryData(tools.builtin.get.queryKey(), [
+ createToolProviderFixture({
+ id: 'provider-1',
+ name: 'vendor/provider-1',
+ label: { en_US: 'Search and Translate' },
+ allow_delete: true,
+ is_team_authorization: true,
+ tools: [createTool('search', 'Search Tool'), createTool('translate', 'Translate Tool')],
+ }),
+ ])
+ for (const operation of [tools.api.get, tools.workflow.get, tools.mcp.get])
+ queryClient.setQueryData(operation.queryKey(), [])
+ const { wrapper: UrlState } = createNuqsTestWrapper()
+ const view = renderWithConsoleQuery(
+ <UrlState>
+ <EventEmitterContextProvider>
+ <Caller />
+ </EventEmitterContextProvider>
+ </UrlState>,
+ {
+ queryClient,
+ systemFeatures: { enable_marketplace: false },
+ workspacePermissionKeys: ['credential.use'],
+ },
)
- return {
- ...renderResult,
- getModelConfig: () => modelConfigRef.current,
- }
+ return { ...view, queryClient, getTools: () => savedConfig.agentConfig.tools as AgentTool[] }
}
describe('AgentTools', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- builtInTools = [
- createCollection(),
- createCollection({
- id: 'provider-2',
- name: 'vendor/provider-2',
- tools: [
- createToolDefinition({
- name: 'translate',
- label: {
- en_US: 'Translate',
- zh_Hans: 'Translate',
- },
- }),
- ],
- }),
- createCollection({
- id: 'provider-3',
- name: 'vendor/provider-3',
- tools: [
- createToolDefinition({
- name: 'summarize',
- label: {
- en_US: 'Summary',
- zh_Hans: 'Summary',
- },
- }),
- ],
- }),
- ]
- customTools = []
- workflowTools = []
- mcpTools = []
- singleToolSelection = {
- provider_id: 'provider-3',
- provider_type: CollectionType.builtIn,
- provider_name: 'vendor/provider-3',
- tool_name: 'summarize',
- tool_label: 'Summary Tool',
- tool_description: 'desc',
- title: 'Summary Tool',
- is_team_authorization: true,
- params: { api_key: 'picker-value' },
- paramSchemas: [],
- output_schema: {},
- }
- multipleToolSelection = [
- {
- provider_id: 'provider-2',
- provider_type: CollectionType.builtIn,
- provider_name: 'vendor/provider-2',
- tool_name: 'translate',
- tool_label: 'Translate Tool',
- tool_description: 'desc',
- title: 'Translate Tool',
- is_team_authorization: true,
- params: { api_key: 'multi-a' },
- paramSchemas: [],
- output_schema: {},
- },
- {
- provider_id: 'provider-3',
- provider_type: CollectionType.builtIn,
- provider_name: 'vendor/provider-3',
- tool_name: 'summarize',
- tool_label: 'Summary Tool',
- tool_description: 'desc',
- title: 'Summary Tool',
- is_team_authorization: true,
- params: { api_key: 'multi-b' },
- paramSchemas: [],
- output_schema: {},
- },
- ]
- settingPanelSavePayload = {}
- settingPanelCredentialId = 'credential-from-panel'
- })
-
- it('should show enabled count and provider information', () => {
+ it('shows enabled count and provider information', () => {
renderAgentTools([
createAgentTool(),
- createAgentTool({
- provider_id: 'provider-2',
- provider_name: 'vendor/provider-2',
- tool_name: 'translate',
- tool_label: 'Translate Tool',
- enabled: false,
- }),
+ createAgentTool({ tool_name: 'translate', tool_label: 'Translate Tool', enabled: false }),
])
-
- const enabledText = screen.getByText((content) =>
- content.includes('appDebug.agent.tools.enabled'),
- )
- expect(enabledText).toHaveTextContent('1/2')
- expect(screen.getByText('provider-1')).toBeInTheDocument()
+ expect(screen.getByText(/appDebug.agent.tools.enabled/)).toHaveTextContent('1/2')
+ expect(screen.getAllByText('provider-1')).toHaveLength(2)
expect(screen.getByText('Translate Tool')).toBeInTheDocument()
})
- it('should copy tool name from infotip action', async () => {
+ it('copies the tool name from its infotip', async () => {
const user = userEvent.setup()
renderAgentTools()
-
await user.hover(screen.getByRole('button', { name: 'search' }))
- const copyButton = await screen.findByText('tools.copyToolName')
- await user.click(copyButton)
- expect(writeTextToClipboardMock).toHaveBeenCalledWith('search')
+ await user.click(await screen.findByRole('button', { name: 'tools.copyToolName' }))
+ expect(writeTextToClipboard).toHaveBeenCalledWith('search')
})
- it('should toggle tool enabled state via switch', async () => {
+ it('saves the disabled state and updates the enabled count', async () => {
const user = userEvent.setup()
- const { getModelConfig } = renderAgentTools()
-
- const switchButton = screen.getByRole('switch')
- await user.click(switchButton)
-
- await waitFor(() => {
- const tools = getModelConfig().agentConfig.tools
- const toggledTool = tools.find((tool) => tool.tool_name === 'search')
- expect(toggledTool?.enabled).toBe(false)
- })
- expect(formattingDispatcherMock).toHaveBeenCalled()
+ const { getTools } = renderAgentTools()
+ await user.click(screen.getByRole('switch'))
+ expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false')
+ expect(screen.getByText(/appDebug.agent.tools.enabled/)).toHaveTextContent('0/1')
+ expect(getTools()[0]?.enabled).toBe(false)
})
- it('should remove tool when delete action is clicked', async () => {
+ it('removes the tool from the configuration and list', async () => {
const user = userEvent.setup()
- const { getModelConfig } = renderAgentTools()
- const deleteButton = screen.getByRole('button', { name: /operation\.delete/i })
- await user.click(deleteButton)
- await waitFor(() => {
- expect(getModelConfig().agentConfig.tools).toHaveLength(0)
- })
- expect(formattingDispatcherMock).toHaveBeenCalled()
+ const { getTools } = renderAgentTools()
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete Search Tool' }))
+ expect(screen.queryByText('Search Tool')).not.toBeInTheDocument()
+ expect(screen.getByText(/appDebug.agent.tools.enabled/)).toHaveTextContent('0/0')
+ expect(getTools()).toEqual([])
})
- it('should add a tool when ToolPicker selects one', async () => {
+ it('adds the chosen tool with its provider and parameter defaults', async () => {
const user = userEvent.setup()
- const { getModelConfig } = renderAgentTools([])
- const addSingleButton = screen.getByRole('button', { name: 'pick-single' })
- await user.click(addSingleButton)
-
- await waitFor(() => {
- expect(screen.getByText('Summary Tool')).toBeInTheDocument()
+ const { getTools } = renderAgentTools([])
+ await user.click(screen.getByRole('button', { name: 'common.operation.add' }))
+ const picker = await screen.findByRole('dialog', {
+ name: 'plugin.detailPanel.toolSelector.title',
})
- expect(getModelConfig().agentConfig.tools).toHaveLength(1)
+ await user.click(await within(picker).findByRole('button', { name: /Search and Translate/ }))
+ await user.click(await within(picker).findByRole('button', { name: /Translate Tool/ }))
+ expect(getTools()).toMatchObject([
+ {
+ provider_id: 'provider-1',
+ provider_name: 'vendor/provider-1',
+ tool_name: 'translate',
+ tool_parameters: { api_key: 'default-key' },
+ enabled: true,
+ notAuthor: false,
+ },
+ ])
+ expect(screen.getByText(/appDebug.agent.tools.enabled/)).toHaveTextContent('1/1')
})
- it('should append multiple selected tools at once', async () => {
+ it('adds all tools from the chosen provider', async () => {
const user = userEvent.setup()
- const { getModelConfig } = renderAgentTools([])
- await user.click(screen.getByRole('button', { name: 'pick-multiple' }))
-
- await waitFor(() => {
- expect(screen.getByText('Translate Tool')).toBeInTheDocument()
- expect(screen.getAllByText('Summary Tool')).toHaveLength(1)
+ const { getTools } = renderAgentTools([])
+ await user.click(screen.getByRole('button', { name: 'common.operation.add' }))
+ const picker = await screen.findByRole('dialog', {
+ name: 'plugin.detailPanel.toolSelector.title',
})
- expect(getModelConfig().agentConfig.tools).toHaveLength(2)
+ const provider = await within(picker).findByRole('button', { name: /Search and Translate/ })
+ await user.hover(provider)
+ // Focus reveals the real add-all control before clicking it.
+ const addAll = within(picker).getByRole('button', { name: 'workflow.tabs.addAll' })
+ addAll.focus()
+ await user.click(addAll)
+ expect(getTools().map((tool) => tool.tool_name)).toEqual(['search', 'translate'])
+ expect(getTools().map((tool) => tool.tool_parameters)).toEqual([
+ { api_key: 'default-key' },
+ { api_key: 'default-key' },
+ ])
+ expect(screen.getByText(/appDebug.agent.tools.enabled/)).toHaveTextContent('2/2')
})
- it('should persist tool parameters when SettingBuiltInTool saves values', async () => {
+ it('saves settings entered in the real drawer and closes it', async () => {
const user = userEvent.setup()
- const { getModelConfig } = renderAgentTools([
- createAgentTool({
- notAuthor: true,
- }),
- ])
- await user.click(screen.getByRole('button', { name: /tools.notAuthorized/ }))
- settingPanelSavePayload = { api_key: 'updated' }
- await user.click(screen.getByRole('button', { name: 'save-from-panel' }))
-
- await waitFor(() => {
- expect(getModelConfig().agentConfig.tools[0]?.tool_parameters).toEqual({ api_key: 'updated' })
- })
+ const { getTools } = renderAgentTools([createAgentTool({ notAuthor: true })])
+ await user.click(screen.getByRole('button', { name: 'tools.notAuthorized' }))
+ const drawer = await screen.findByRole('dialog', { name: 'Search Tool' })
+ const input = await within(drawer).findByRole('textbox', { name: /API Key/ })
+ await user.clear(input)
+ await user.type(input, 'updated-key')
+ await user.click(within(drawer).getByRole('button', { name: 'common.operation.save' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(getTools()[0]?.tool_parameters).toEqual({ api_key: 'updated-key' })
})
- it('should update only the selected tool credential when tools share a provider', async () => {
+ it('changes only the selected tool credential when tools share a provider', async () => {
const user = userEvent.setup()
- const { getModelConfig } = renderAgentTools([
- createAgentTool({
- credential_id: 'credential-search',
- notAuthor: true,
- }),
+ const { getTools } = renderAgentTools([
+ createAgentTool({ credential_id: 'credential-search', notAuthor: true }),
createAgentTool({
credential_id: 'credential-translate',
notAuthor: true,
- tool_label: 'Translate Tool',
tool_name: 'translate',
+ tool_label: 'Translate Tool',
}),
])
- const authorizationButtons = screen.getAllByRole('button', { name: /tools.notAuthorized/ })
- const secondAuthorizationButton = authorizationButtons[1]
- if (!secondAuthorizationButton) throw new Error('Second authorization button not found')
- await user.click(secondAuthorizationButton)
- settingPanelCredentialId = 'credential-updated'
- await user.click(screen.getByRole('button', { name: 'auth-from-panel' }))
-
- await waitFor(() => {
- const tools = getModelConfig().agentConfig.tools as AgentTool[]
- expect(tools.map((tool) => tool.credential_id)).toEqual([
- 'credential-search',
- 'credential-updated',
- ])
- })
+ await user.click(screen.getAllByRole('button', { name: 'tools.notAuthorized' })[1]!)
+ const drawer = await screen.findByRole('dialog', { name: 'Translate Tool' })
+ await user.click(await within(drawer).findByRole('button', { name: 'Translate credential' }))
+ const menu = await screen.findByRole('dialog', { name: 'plugin.auth.authorizations' })
+ await user.click(within(menu).getByText('Replacement credential'))
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('dialog', { name: 'plugin.auth.authorizations' }),
+ ).not.toBeInTheDocument(),
+ )
+ expect(
+ within(drawer).getByRole('button', { name: 'Replacement credential' }),
+ ).toBeInTheDocument()
+ expect(getTools().map((tool) => tool.credential_id)).toEqual([
+ 'credential-search',
+ 'credential-updated',
+ ])
})
})
diff --git a/web/app/components/plugins/plugin-page/empty/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-page/empty/__tests__/index.spec.tsx
index a397e06fc45..b6587aba12d 100644
--- a/web/app/components/plugins/plugin-page/empty/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-page/empty/__tests__/index.spec.tsx
@@ -1,237 +1,219 @@
-import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'
-import type { ReactElement } from 'react'
+import type { ComponentProps } from 'react'
+import type { PluginPageTab } from '../../context'
import type { FilterState } from '../../filter-management'
-import { zPluginInstallationScope } from '@dify/contracts/api/console/system-features/zod.gen'
-import { fireEvent, screen } from '@testing-library/react'
+import { fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { renderWithConsoleQuery } from '@/test/console/query-data'
+import { useMemo, useRef, useState } from 'react'
+import { seedModelProviderQueries } from '@/test/console/model-provider'
+import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
+import { createInstalledPluginFixture } from '@/test/fixtures/plugin'
+import { PluginPageContext } from '../../context'
import Empty from '../index'
-const { mockSetActiveTab, mockUseInstalledPluginList, mockState } = vi.hoisted(() => {
- const state = {
- filters: {
- categories: [] as string[],
- tags: [] as string[],
- searchQuery: '',
- } as FilterState,
- systemFeatures: {
- enable_marketplace: true,
- plugin_installation_permission: {
- plugin_installation_scope: 'all' as const,
- restrict_to_marketplace_only: false,
- },
- } as Partial<GetSystemFeaturesResponse>,
- pluginList: { plugins: [] as Array<{ id: string }> } as
- | { plugins: Array<{ id: string }> }
- | undefined,
- }
+const requests = vi.hoisted(() => ({ list: vi.fn(), upload: vi.fn() }))
+vi.mock('@/service/plugins', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/plugins')>()),
+ uploadFile: requests.upload,
+}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses, withConsoleClientResponses } =
+ await import('@/test/console/service-responses')
return {
- mockSetActiveTab: vi.fn(),
- mockUseInstalledPluginList: vi.fn(() => ({ data: state.pluginList })),
- mockState: state,
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.plugin.list.get': requests.list,
+ 'workspaces.current.plugin.list.installations.ids.post': () => ({ plugins: [] }),
+ }),
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.plugin.permission.fetch.get': () => ({
+ install_permission: 'everyone',
+ debug_permission: 'everyone',
+ }),
+ 'workspaces.current.plugin.tasks.get': () => ({ tasks: [] }),
+ }),
}
})
-const render = (ui: ReactElement) =>
- renderWithConsoleQuery(ui, { systemFeatures: mockState.systemFeatures })
-
-vi.mock('../../context', () => ({
- usePluginPageContext: (selector: (value: Record<string, unknown>) => unknown) => {
- const contextValue = {
- filters: mockState.filters,
- setActiveTab: mockSetActiveTab,
- }
- return selector(contextValue)
- },
-}))
-
-vi.mock('@/service/use-plugins', () => ({
- useInstalledPluginList: () => mockUseInstalledPluginList(),
-}))
-
-vi.mock('@/app/components/plugins/install-plugin/install-from-github', () => ({
- default: ({ onClose }: { onClose: () => void }) => (
- <div data-testid="install-from-github-modal">
- <button data-testid="github-modal-close" onClick={onClose}>
- Close
- </button>
- </div>
- ),
-}))
-
-vi.mock('@/app/components/plugins/install-plugin/install-from-local-package', () => ({
- default: ({ file, onClose }: { file: File; onClose: () => void }) => (
- <div data-testid="install-from-local-modal" data-file-name={file.name}>
- <button data-testid="local-modal-close" onClick={onClose}>
- Close
- </button>
- </div>
- ),
-}))
-
-const resetMockState = () => {
- mockState.filters = { categories: [], tags: [], searchQuery: '' }
- mockState.systemFeatures = {
- enable_marketplace: true,
- plugin_installation_permission: {
- plugin_installation_scope: zPluginInstallationScope.enum.all,
- restrict_to_marketplace_only: false,
- },
+function renderEmpty({
+ filters = {},
+ marketplace = true,
+ restricted = false,
+ customNavigation = false,
+ ...props
+}: Partial<ComponentProps<typeof Empty>> & {
+ filters?: Partial<FilterState>
+ marketplace?: boolean
+ restricted?: boolean
+ customNavigation?: boolean
+} = {}) {
+ const initialFilters: FilterState = { categories: [], tags: [], searchQuery: '', ...filters }
+ function Caller() {
+ const containerRef = useRef<HTMLDivElement>(null)
+ const [activeTab, setActiveTab] = useState<PluginPageTab>('plugins')
+ const [customOpen, setCustomOpen] = useState(false)
+ const value = useMemo(
+ () => ({
+ containerRef,
+ selectedItem: undefined,
+ setSelectedItem: () => {},
+ filters: initialFilters,
+ setFilters: () => {},
+ activeTab,
+ setActiveTab,
+ options: [],
+ }),
+ [activeTab],
+ )
+ return (
+ <PluginPageContext.Provider value={value}>
+ {activeTab === 'discover' && <section aria-label="Discover marketplace" />}
+ {customOpen && <section aria-label="Caller marketplace" />}
+ <Empty
+ {...props}
+ onSwitchToMarketplace={
+ customNavigation ? () => setCustomOpen(true) : props.onSwitchToMarketplace
+ }
+ />
+ </PluginPageContext.Provider>
+ )
}
- mockState.pluginList = { plugins: [] }
- mockUseInstalledPluginList.mockReturnValue({ data: mockState.pluginList })
-}
-
-const setMockFilters = (filters: Partial<FilterState>) => {
- mockState.filters = { ...mockState.filters, ...filters }
-}
-
-const setMockSystemFeatures = (features: Partial<GetSystemFeaturesResponse>) => {
- mockState.systemFeatures = { ...mockState.systemFeatures, ...features }
+ const queryClient = createConsoleQueryClient()
+ seedModelProviderQueries(queryClient)
+ return renderWithConsoleQuery(<Caller />, {
+ queryClient,
+ workspacePermissionKeys: ['plugin.install'],
+ systemFeatures: {
+ rbac_enabled: true,
+ enable_marketplace: marketplace,
+ plugin_installation_permission: {
+ plugin_installation_scope: 'all',
+ restrict_to_marketplace_only: restricted,
+ },
+ },
+ })
}
-const setMockPluginList = (list: { plugins: Array<{ id: string }> } | undefined) => {
- mockState.pluginList = list
- mockUseInstalledPluginList.mockReturnValue({ data: list })
-}
+const getFileInput = () => document.querySelector<HTMLInputElement>('input[type="file"]')!
+const createFile = (name: string) =>
+ new File(['package'], name, { type: 'application/octet-stream' })
+
+beforeEach(() => {
+ requests.list.mockReset().mockResolvedValue({ plugins: [], total: 0 })
+ // These existing scenarios cancel before uploading finishes. Keep the transport
+ // pending so the real upload view and its close action own the interaction.
+ requests.upload.mockReset().mockReturnValue(new Promise(() => {}))
+})
-const createMockFile = (name: string, type = 'application/octet-stream'): File => {
- return new File(['test'], name, { type })
-}
+it('shows the no-installed message even when filters are active', async () => {
+ renderEmpty({ filters: { categories: ['model'], searchQuery: 'test' } })
+ expect(await screen.findByText('plugin.list.noInstalled')).toBeInTheDocument()
+ expect(screen.queryByText('plugin.list.notFound')).not.toBeInTheDocument()
+})
-const getFileInput = () => document.querySelector<HTMLInputElement>('input[type="file"]')!
+it.each([{ categories: ['model'] }, { tags: ['tag1'] }, { searchQuery: 'test query' }])(
+ 'shows no results for an installed list filtered by %o',
+ async (filters) => {
+ requests.list.mockResolvedValue({ plugins: [createInstalledPluginFixture()], total: 1 })
+ renderEmpty({ filters })
+ expect(await screen.findByText('plugin.list.notFound')).toBeInTheDocument()
+ expect(screen.queryByText('plugin.list.noInstalled')).not.toBeInTheDocument()
+ },
+)
+
+it.each([
+ { marketplace: true, restricted: false, methods: ['marketplace', 'github', 'local'] },
+ { marketplace: true, restricted: true, methods: ['marketplace'] },
+ { marketplace: false, restricted: false, methods: ['github', 'local'] },
+ { marketplace: false, restricted: true, methods: [] },
+])(
+ 'offers $methods with marketplace=$marketplace and restricted=$restricted',
+ ({ marketplace, restricted, methods }) => {
+ renderEmpty({ marketplace, restricted })
+ for (const method of ['marketplace', 'github', 'local']) {
+ const button = screen.queryByRole('button', { name: `plugin.source.${method}` })
+ if (methods.includes(method)) expect(button).toBeInTheDocument()
+ else expect(button).not.toBeInTheDocument()
+ }
+ },
+)
+
+it('hides installation actions and ignores file changes without install permission', () => {
+ renderEmpty({ canInstall: false })
+ expect(screen.queryAllByRole('button')).toHaveLength(0)
+ fireEvent.change(getFileInput(), { target: { files: [createFile('blocked.difypkg')] } })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ expect(requests.upload).not.toHaveBeenCalled()
+})
-describe('Plugin list empty state', () => {
- beforeEach(() => {
- resetMockState()
- })
+it('opens the discovery tab from the marketplace action', async () => {
+ const user = userEvent.setup()
+ renderEmpty()
+ await user.click(screen.getByRole('button', { name: 'plugin.source.marketplace' }))
+ expect(screen.getByRole('region', { name: 'Discover marketplace' })).toBeInTheDocument()
+})
- it('shows the no-installed message even when filters are active', () => {
- setMockFilters({ categories: ['model'], searchQuery: 'test' })
- render(<Empty />)
+it('uses the supplied marketplace navigation instead of switching tabs', async () => {
+ const user = userEvent.setup()
+ renderEmpty({ customNavigation: true })
+ await user.click(screen.getByRole('button', { name: 'plugin.source.marketplace' }))
+ expect(screen.getByRole('region', { name: 'Caller marketplace' })).toBeInTheDocument()
+ expect(screen.queryByRole('region', { name: 'Discover marketplace' })).not.toBeInTheDocument()
+})
- expect(screen.getByText('plugin.list.noInstalled')).toBeInTheDocument()
- expect(screen.queryByText('plugin.list.notFound')).not.toBeInTheDocument()
+it('opens, closes, and reopens the real GitHub installer', async () => {
+ const user = userEvent.setup()
+ renderEmpty()
+ await user.click(screen.getByRole('button', { name: 'plugin.source.github' }))
+ const dialog = await screen.findByRole('dialog', {
+ name: 'plugin.installFromGitHub.installPlugin',
})
+ expect(within(dialog).getByRole('textbox')).toHaveValue('')
+ await user.click(within(dialog).getByRole('button', { name: 'plugin.installModal.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(screen.getByRole('button', { name: 'plugin.source.github' }))
+ expect(
+ await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installPlugin' }),
+ ).toBeInTheDocument()
+})
- it.each([{ categories: ['model'] }, { tags: ['tag1'] }, { searchQuery: 'test query' }])(
- 'shows no results for an installed list filtered by %o',
- (filters) => {
- setMockPluginList({ plugins: [{ id: 'plugin-1' }] })
- setMockFilters(filters)
- render(<Empty />)
+it('opens the file picker for supported plugin and bundle files', async () => {
+ const user = userEvent.setup()
+ renderEmpty()
+ const input = getFileInput()
+ const clickSpy = vi.spyOn(input, 'click')
+ await user.click(screen.getByRole('button', { name: 'plugin.source.local' }))
+ expect(clickSpy).toHaveBeenCalledOnce()
+ expect(input).toHaveAttribute('accept', '.difypkg,.difybndl')
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ clickSpy.mockRestore()
+})
- expect(screen.getByText('plugin.list.notFound')).toBeInTheDocument()
- },
+it('uploads the selected package and accepts a new bundle after closing', async () => {
+ const user = userEvent.setup()
+ renderEmpty()
+ const file = createFile('my-plugin.difypkg')
+ await user.upload(getFileInput(), file)
+ const dialog = await screen.findByRole('dialog', { name: 'plugin.installModal.installPlugin' })
+ expect(within(dialog).getByText(/plugin.installModal.uploadingPackage/)).toHaveTextContent(
+ file.name,
)
-
- it.each([
- { marketplace: true, restricted: false, methods: ['marketplace', 'github', 'local'] },
- { marketplace: true, restricted: true, methods: ['marketplace'] },
- { marketplace: false, restricted: false, methods: ['github', 'local'] },
- { marketplace: false, restricted: true, methods: [] },
- ])(
- 'offers $methods with marketplace=$marketplace and restricted=$restricted',
- ({ marketplace, restricted, methods }) => {
- setMockSystemFeatures({
- enable_marketplace: marketplace,
- plugin_installation_permission: {
- plugin_installation_scope: zPluginInstallationScope.enum.all,
- restrict_to_marketplace_only: restricted,
- },
- })
- render(<Empty />)
-
- for (const method of ['marketplace', 'github', 'local']) {
- const button = screen.queryByRole('button', { name: `plugin.source.${method}` })
- if (methods.includes(method)) expect(button).toBeInTheDocument()
- else expect(button).not.toBeInTheDocument()
- }
- },
+ expect(requests.upload).toHaveBeenCalledWith(file, false)
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+
+ const bundle = createFile('my-bundle.difybndl')
+ await user.upload(getFileInput(), bundle)
+ const reopened = await screen.findByRole('dialog', { name: 'plugin.installModal.installPlugin' })
+ expect(within(reopened).getByText(/plugin.installModal.uploadingPackage/)).toHaveTextContent(
+ bundle.name,
)
+ expect(requests.upload).toHaveBeenLastCalledWith(bundle, true)
+})
- it('hides installation actions and ignores file changes without install permission', () => {
- render(<Empty canInstall={false} />)
- expect(screen.queryAllByRole('button')).toHaveLength(0)
-
- // Exercise the permission guard even if a file change reaches the hidden input.
- fireEvent.change(getFileInput(), { target: { files: [createMockFile('blocked.difypkg')] } })
- expect(screen.queryByTestId('install-from-local-modal')).not.toBeInTheDocument()
- })
-
- it('opens the discovery tab from the marketplace action', async () => {
- const user = userEvent.setup()
- render(<Empty />)
-
- await user.click(screen.getByRole('button', { name: 'plugin.source.marketplace' }))
-
- expect(mockSetActiveTab).toHaveBeenCalledWith('discover')
- })
-
- it('uses the supplied marketplace navigation instead of switching tabs', async () => {
- const user = userEvent.setup()
- const onSwitchToMarketplace = vi.fn()
- render(<Empty onSwitchToMarketplace={onSwitchToMarketplace} />)
-
- await user.click(screen.getByRole('button', { name: 'plugin.source.marketplace' }))
-
- expect(onSwitchToMarketplace).toHaveBeenCalledTimes(1)
- expect(mockSetActiveTab).not.toHaveBeenCalled()
- })
-
- it('opens, closes, and reopens the GitHub installer', async () => {
- const user = userEvent.setup()
- render(<Empty />)
- expect(screen.queryByTestId('install-from-github-modal')).not.toBeInTheDocument()
-
- await user.click(screen.getByRole('button', { name: 'plugin.source.github' }))
- expect(screen.getByTestId('install-from-github-modal')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'Close' }))
- expect(screen.queryByTestId('install-from-github-modal')).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'plugin.source.github' }))
- expect(screen.getByTestId('install-from-github-modal')).toBeInTheDocument()
- })
-
- it('opens the file picker for supported plugin and bundle files', async () => {
- const user = userEvent.setup()
- render(<Empty />)
- const input = getFileInput()
- const clickSpy = vi.spyOn(input, 'click')
-
- await user.click(screen.getByRole('button', { name: 'plugin.source.local' }))
-
- expect(clickSpy).toHaveBeenCalledOnce()
- expect(input).toHaveAttribute('accept', '.difypkg,.difybndl')
- expect(screen.queryByTestId('install-from-local-modal')).not.toBeInTheDocument()
- clickSpy.mockRestore()
- })
-
- it('passes the selected package to the installer and accepts a new bundle after closing', async () => {
- const user = userEvent.setup()
- render(<Empty />)
- const input = getFileInput()
-
- await user.upload(input, createMockFile('my-plugin.difypkg'))
- expect(screen.getByTestId('install-from-local-modal')).toHaveAttribute(
- 'data-file-name',
- 'my-plugin.difypkg',
- )
- await user.click(screen.getByRole('button', { name: 'Close' }))
- expect(screen.queryByTestId('install-from-local-modal')).not.toBeInTheDocument()
-
- await user.upload(input, createMockFile('my-bundle.difybndl'))
- expect(screen.getByTestId('install-from-local-modal')).toHaveAttribute(
- 'data-file-name',
- 'my-bundle.difybndl',
- )
- })
-
- it('does not open an installer when file selection is cancelled', () => {
- render(<Empty />)
-
- fireEvent.change(getFileInput(), { target: { files: [] } })
-
- expect(screen.queryByTestId('install-from-local-modal')).not.toBeInTheDocument()
- })
+it('does not open an installer when file selection is cancelled', () => {
+ renderEmpty()
+ fireEvent.change(getFileInput(), { target: { files: [] } })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ expect(requests.upload).not.toHaveBeenCalled()
})
diff --git a/web/app/components/tools/marketplace/__tests__/builtin-marketplace-panel.spec.tsx b/web/app/components/tools/marketplace/__tests__/builtin-marketplace-panel.spec.tsx
index 460e6ae19d0..f4fb4309a35 100644
--- a/web/app/components/tools/marketplace/__tests__/builtin-marketplace-panel.spec.tsx
+++ b/web/app/components/tools/marketplace/__tests__/builtin-marketplace-panel.spec.tsx
@@ -1,97 +1,153 @@
-import { act, render, screen } from '@testing-library/react'
+import type { MarketplaceCollection } from '@dify/contracts/marketplace'
+import { act, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createRef } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
+import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'
+import { createNuqsTestRenderer } from '@/test/nuqs-testing'
import { BuiltinMarketplacePanel } from '../builtin-marketplace-panel'
-const mockUseMarketplace = vi.fn()
-const intersectionObserverCallbacks: IntersectionObserverCallback[] = []
-
-vi.mock('@/app/components/tools/marketplace/hooks', () => ({
- useMarketplace: (...args: unknown[]) => mockUseMarketplace(...args),
+const requests = vi.hoisted(() => ({
+ installed: vi.fn(),
+ search: vi.fn(),
+ collections: vi.fn(),
+ collectionPlugins: vi.fn(),
}))
-
-vi.mock('@/app/components/tools/marketplace', () => ({
- default: ({ showMarketplacePanel }: { showMarketplacePanel: () => void }) => (
- <button type="button" onClick={showMarketplacePanel}>
- Marketplace
- </button>
- ),
+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses, withConsoleClientResponses } =
+ await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.plugin.permission.fetch.get': () => ({
+ install_permission: 'everyone',
+ debug_permission: 'everyone',
+ }),
+ }),
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.plugin.installedIds.get': requests.installed,
+ 'workspaces.current.plugin.list.installations.ids.post': () => ({ plugins: [] }),
+ }),
+ }
+})
+vi.mock('@/service/marketplace', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/marketplace')>()
+ return {
+ ...actual,
+ marketplaceClient: {
+ ...actual.marketplaceClient,
+ collections: requests.collections,
+ collectionPlugins: requests.collectionPlugins,
+ },
+ }
+})
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ postMarketplace: requests.search,
}))
-describe('BuiltinMarketplacePanel', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- intersectionObserverCallbacks.length = 0
- mockUseMarketplace.mockReturnValue({ handleScroll: vi.fn() })
- vi.stubGlobal(
- 'IntersectionObserver',
- class {
- constructor(callback: IntersectionObserverCallback) {
- intersectionObserverCallbacks.push(callback)
- }
-
- observe = vi.fn()
- disconnect = vi.fn()
- },
- )
- })
-
- afterEach(() => {
- vi.unstubAllGlobals()
- })
+const render = createNuqsTestRenderer(renderWithConsoleQuery)
+const plugin = createMarketplacePluginFixture({ label: { en_US: 'Weather Tool' }, tags: [] })
+const collection: MarketplaceCollection = {
+ name: 'featured',
+ label: { en_US: 'Featured tools' },
+ description: { en_US: 'Recommended tools' },
+ rule: '',
+ created_at: '',
+ updated_at: '',
+ searchable: false,
+ search_params: {},
+}
+let enterViewport: () => void
+let observedTarget: Element
+
+beforeEach(() => {
+ requests.installed.mockReset().mockResolvedValue({ plugin_ids: [] })
+ requests.search.mockReset().mockResolvedValue({ data: { plugins: [plugin], total: 1 } })
+ requests.collections.mockReset().mockResolvedValue({ data: { collections: [collection] } })
+ requests.collectionPlugins
+ .mockReset()
+ .mockResolvedValue({ data: { plugins: [plugin], total: 1 } })
+ vi.stubGlobal(
+ 'IntersectionObserver',
+ class {
+ constructor(callback: IntersectionObserverCallback) {
+ enterViewport = () =>
+ callback(
+ [{ isIntersecting: true, target: observedTarget } as IntersectionObserverEntry],
+ this as unknown as IntersectionObserver,
+ )
+ }
+ observe(target: Element) {
+ observedTarget = target
+ }
+ unobserve() {}
+ disconnect() {}
+ },
+ )
+})
+afterEach(() => vi.unstubAllGlobals())
+
+function renderPanel(keywords = '', tagFilterValue: string[] = []) {
+ const containerRef = createRef<HTMLDivElement>()
+ render(
+ <div ref={containerRef}>
+ <BuiltinMarketplacePanel
+ containerRef={containerRef}
+ contentInset="default"
+ keywords={keywords}
+ tagFilterValue={tagFilterValue}
+ />
+ </div>,
+ { workspacePermissionKeys: [], systemFeatures: { rbac_enabled: true } },
+ )
+ return containerRef
+}
+
+it('defers catalog requests until the section enters the viewport, then shows its tools', async () => {
+ renderPanel()
+ expect(requests.installed).not.toHaveBeenCalled()
+ expect(requests.collections).not.toHaveBeenCalled()
+ expect(screen.queryByText('Weather Tool')).not.toBeInTheDocument()
+
+ act(() => enterViewport())
+
+ expect(await screen.findByText('Weather Tool')).toBeInTheDocument()
+ expect(screen.getByText('Featured tools')).toBeInTheDocument()
+})
- const renderPanel = (overrides?: { keywords?: string; tagFilterValue?: string[] }) => {
- const containerRef = createRef<HTMLDivElement>()
- const { container } = render(
- <div ref={containerRef}>
- <BuiltinMarketplacePanel
- containerRef={containerRef}
- contentInset="default"
- keywords={overrides?.keywords ?? ''}
- tagFilterValue={overrides?.tagFilterValue ?? []}
- />
- </div>,
+it.each([
+ { keywords: 'weather', tags: [] },
+ { keywords: '', tags: ['search'] },
+])(
+ 'loads matching tools immediately for search=$keywords and tags=$tags',
+ async ({ keywords, tags }) => {
+ renderPanel(keywords, tags)
+
+ expect(await screen.findByText('Weather Tool')).toBeInTheDocument()
+ expect(requests.search).toHaveBeenCalledWith(
+ '/plugins/search/advanced',
+ expect.objectContaining({
+ body: expect.objectContaining({ query: keywords, tags, category: 'tool' }),
+ }),
)
-
- return { container, containerRef }
- }
-
- it('defers Marketplace queries until the section enters the viewport', () => {
- renderPanel()
-
- expect(mockUseMarketplace).toHaveBeenLastCalledWith('', [], false)
-
- act(() => {
- intersectionObserverCallbacks[0]?.(
- [{ isIntersecting: true }] as IntersectionObserverEntry[],
- {} as IntersectionObserver,
- )
- })
-
- expect(mockUseMarketplace).toHaveBeenLastCalledWith('', [], true)
- })
-
- it('loads Marketplace immediately when the user searches', () => {
- renderPanel({ keywords: 'weather' })
-
- expect(mockUseMarketplace).toHaveBeenLastCalledWith('weather', [], true)
- })
-
- it('loads Marketplace immediately when the user filters by tag', () => {
- renderPanel({ tagFilterValue: ['search'] })
-
- expect(mockUseMarketplace).toHaveBeenLastCalledWith('', ['search'], true)
- })
-
- it('activates Marketplace before scrolling to it from the arrow action', async () => {
- const user = userEvent.setup()
- const { containerRef } = renderPanel()
- containerRef.current!.scrollTo = vi.fn()
-
- await user.click(screen.getByRole('button', { name: 'Marketplace' }))
-
- expect(mockUseMarketplace).toHaveBeenLastCalledWith('', [], true)
- expect(containerRef.current!.scrollTo).toHaveBeenCalledWith({ top: -80, behavior: 'smooth' })
- })
+ expect(requests.collections).not.toHaveBeenCalled()
+ },
+)
+
+it('activates and scrolls to the marketplace from the real arrow action', async () => {
+ const user = userEvent.setup()
+ const containerRef = renderPanel()
+ const scrollTo = vi.fn()
+ containerRef.current!.scrollTo = scrollTo
+ // Supply the browser layout at the observer boundary, rather than relying on
+ // happy-dom's zero-sized layout producing a negative scroll destination.
+ Object.defineProperty(observedTarget, 'offsetTop', { configurable: true, value: 500 })
+
+ await user.click(screen.getByRole('button', { name: 'plugin.marketplace.moreFrom' }))
+
+ expect(await screen.findByText('Weather Tool')).toBeInTheDocument()
+ expect(scrollTo).toHaveBeenCalledWith({ top: 420, behavior: 'smooth' })
})