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 chat, plugin and upload behavior owners (#44732)

Stephen Zhou0580e1f65b91
diff --git a/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/index.spec.tsx b/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/index.spec.tsx
index 360d491698f..361c323027b 100644
--- a/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/index.spec.tsx
@@ -1,64 +1,161 @@
+import type { ReactNode } from 'react'
import type { EmbeddedChatbotContextValue } from '../../context'
-import { act, render, screen } from '@testing-library/react'
+import type { AppConversationData, AppData } from '@/models/share'
+import { gzipSync } from 'node:zlib'
+import { QueryClientProvider } from '@tanstack/react-query'
+import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
-import { InputVarType } from '@/app/components/workflow/types'
-import { createEmbeddedChatbotContextFixture } from '@/test/fixtures/embedded-chatbot'
-import { useEmbeddedChatbotContext } from '../../context'
+import { AppToaster } from '@/app/notifications/app-toaster'
+import { useWebAppStore } from '@/context/web-app-context'
+import { AppSourceType, fetchChatList, fetchConversations } from '@/service/share'
+import { createChatConfigFixture } from '@/test/fixtures/chat'
+import { createTestQueryClient } from '@/test/query-client'
+import { EmbeddedChatbotContext } from '../../context'
+import { useEmbeddedChatbot } from '../../hooks'
import InputsFormNode from '../index'
-vi.mock('../../context', () => ({ useEmbeddedChatbotContext: vi.fn() }))
+vi.mock('@/i18n/client', () => ({ changeLanguage: vi.fn().mockResolvedValue(undefined) }))
-const inputsForms = [
- { variable: 'topic', label: 'Topic', type: InputVarType.textInput, required: true },
-]
-const setContext = (overrides: Partial<EmbeddedChatbotContextValue> = {}) => {
- vi.mocked(useEmbeddedChatbotContext).mockReturnValue(
- createEmbeddedChatbotContextFixture({ inputsForms, ...overrides }),
- )
+vi.mock('@/service/share', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/share')>()
+ return {
+ ...actual,
+ fetchChatList: vi.fn<typeof actual.fetchChatList>(),
+ fetchConversations: vi.fn<typeof actual.fetchConversations>(),
+ }
+})
+
+const requiredInput = {
+ 'text-input': { variable: 'topic', label: 'Topic', required: true },
}
-function Form({ initiallyCollapsed = false }) {
+const EmbeddedChatbotContextProvider = EmbeddedChatbotContext.Provider
+
+function FormOwner({ initiallyCollapsed = false }: { initiallyCollapsed?: boolean }) {
+ const owner = useEmbeddedChatbot(AppSourceType.webApp)
const [collapsed, setCollapsed] = useState(initiallyCollapsed)
- return <InputsFormNode collapsed={collapsed} setCollapsed={setCollapsed} />
+ const contextValue: EmbeddedChatbotContextValue = {
+ ...owner,
+ appData: (owner.appData as AppData | undefined) ?? null,
+ isMobile: false,
+ }
+
+ return (
+ <EmbeddedChatbotContextProvider value={contextValue}>
+ <InputsFormNode collapsed={collapsed} setCollapsed={setCollapsed} />
+ </EmbeddedChatbotContextProvider>
+ )
}
-it.each([{ allInputsHidden: true }, { inputsForms: [] }])(
- 'omits settings when no input can be edited: %j',
- (overrides) => {
- setContext(overrides)
- render(<Form />)
- expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
- expect(screen.queryByRole('button')).not.toBeInTheDocument()
- },
-)
+function renderOwner({
+ children,
+ appParams = createChatConfigFixture({ user_input_form: [requiredInput] }),
+ conversationId = null,
+}: {
+ children?: ReactNode
+ appParams?: ReturnType<typeof createChatConfigFixture>
+ conversationId?: string | null
+} = {}) {
+ useWebAppStore.setState({
+ appInfo: {
+ app_id: 'app-1',
+ end_user_id: 'user-1',
+ custom_config: null,
+ site: { title: 'Test App', default_language: 'en-US' },
+ },
+ appMeta: { tool_icons: {} },
+ appParams,
+ embeddedConversationId: conversationId,
+ embeddedUserId: 'embedded-user-1',
+ })
+ const queryClient = createTestQueryClient()
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <AppToaster timeout={0} />
+ {children ?? <FormOwner />}
+ </QueryClientProvider>,
+ )
+}
-it('collapses a new conversation only after starting chat succeeds', async () => {
- const user = userEvent.setup()
- const start = vi.fn<EmbeddedChatbotContextValue['handleStartChat']>()
- setContext({ handleStartChat: start })
- render(<Form />)
- await user.click(screen.getByRole('button', { name: 'share.chat.startChat' }))
- expect(start).toHaveBeenCalledTimes(1)
- expect(screen.getByRole('textbox', { name: 'Topic' })).toBeInTheDocument()
- act(() => start.mock.calls[0]![0]!())
- expect(screen.queryByRole('textbox', { name: 'Topic' })).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
- expect(screen.getByRole('textbox', { name: 'Topic' })).toBeInTheDocument()
-})
+describe('InputsFormNode', () => {
+ beforeEach(() => {
+ window.history.replaceState({}, '', '/')
+ localStorage.clear()
+ sessionStorage.clear()
+ vi.mocked(fetchConversations).mockReset().mockResolvedValue({
+ data: [],
+ has_more: false,
+ limit: 100,
+ })
+ vi.mocked(fetchChatList).mockReset().mockResolvedValue({ data: [] })
+ })
+
+ it.each([
+ createChatConfigFixture({
+ user_input_form: [{ 'text-input': { ...requiredInput['text-input'], hide: true } }],
+ }),
+ createChatConfigFixture({ user_input_form: [] }),
+ ])('omits settings when no input can be edited', (appParams) => {
+ renderOwner({ appParams })
+ expect(screen.queryByRole('textbox', { name: 'Topic' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'share.chat.startChat' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.edit' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.close' })).not.toBeInTheDocument()
+ })
+
+ it('keeps invalid settings open, then collapses after a valid start and retains the input', async () => {
+ const user = userEvent.setup()
+ renderOwner()
+
+ const topic = await screen.findByRole('textbox', { name: 'Topic' })
+ await user.click(screen.getByRole('button', { name: 'share.chat.startChat' }))
+ expect(topic).toBeInTheDocument()
+
+ await user.type(topic, 'Persistent topic')
+ await user.click(screen.getByRole('button', { name: 'share.chat.startChat' }))
+ await waitFor(() =>
+ expect(screen.queryByRole('textbox', { name: 'Topic' })).not.toBeInTheDocument(),
+ )
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ expect(screen.getByRole('textbox', { name: 'Topic' })).toHaveValue('Persistent topic')
+ })
+
+ it('lets an existing conversation reopen and close its settings without starting a new chat', async () => {
+ const user = userEvent.setup()
+ const params = new URLSearchParams({
+ 'sys.conversation_id': gzipSync('conv-123').toString('base64'),
+ })
+ window.history.replaceState({}, '', `/?${params}`)
+ const conversations: AppConversationData = {
+ data: [{ id: 'conv-123', name: 'Existing conversation', inputs: null, introduction: '' }],
+ has_more: false,
+ limit: 100,
+ }
+ vi.mocked(fetchConversations).mockResolvedValue(conversations)
+ vi.mocked(fetchChatList).mockResolvedValue({
+ data: [
+ {
+ id: 'message-1',
+ query: 'Question',
+ answer: 'Answer',
+ inputs: { topic: 'Existing topic' },
+ message_files: [],
+ },
+ ],
+ })
+
+ renderOwner({
+ conversationId: 'conv-123',
+ children: <FormOwner initiallyCollapsed />,
+ })
-it('lets an existing conversation reopen and close its settings without starting a new chat', async () => {
- const user = userEvent.setup()
- const start = vi.fn()
- setContext({
- currentConversationId: 'conv-123',
- currentConversationInputs: { topic: 'Existing topic' },
- handleStartChat: start,
+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
+ await waitFor(() =>
+ expect(screen.getByRole('textbox', { name: 'Topic' })).toHaveValue('Existing topic'),
+ )
+ expect(screen.queryByRole('button', { name: 'share.chat.startChat' })).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
+ expect(screen.queryByRole('textbox', { name: 'Topic' })).not.toBeInTheDocument()
})
- render(<Form initiallyCollapsed />)
- await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))
- expect(screen.getByRole('textbox', { name: 'Topic' })).toHaveValue('Existing topic')
- expect(screen.queryByRole('button', { name: 'share.chat.startChat' })).not.toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
- expect(screen.queryByRole('textbox', { name: 'Topic' })).not.toBeInTheDocument()
- expect(start).not.toHaveBeenCalled()
})
diff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsx b/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsx
index 9307ce90f74..76e29a3fcca 100644
--- a/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsx
+++ b/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsx
@@ -1,28 +1,25 @@
import type { ReactElement } from 'react'
-import { screen, waitFor } from '@testing-library/react'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { ModalContextProvider } from '@/context/modal-context-provider'
import { renderWithConsoleQuery } from '@/test/console/query-data'
+import { createNuqsTestWrapper } from '@/test/nuqs-testing'
import AnnotationCtrlButton from '../annotation-ctrl-button'
-const mockSetShowAnnotationFullModal = vi.fn()
-vi.mock('@/context/modal-context', () => ({
- useModalContext: () => ({
- setShowAnnotationFullModal: mockSetShowAnnotationFullModal,
- }),
-}))
-
let mockAnnotatedResponseUsage = 5
-const mockAddAnnotation = vi.fn().mockResolvedValue({ id: 'annotation-1' })
-
-vi.mock('@/service/console', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/console')>()),
- consoleClient: {
- apps: {
- byAppId: { annotations: { post: (...args: unknown[]) => mockAddAnnotation(...args) } },
- },
- },
-}))
+const api = vi.hoisted(() => ({ addAnnotation: vi.fn() }))
+
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleClientResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'apps.byAppId.annotations.post': api.addAnnotation,
+ }),
+ }
+})
vi.mock('@/app/notifications', () => ({
default: { notify: vi.fn() },
@@ -35,16 +32,23 @@ vi.mock('@/app/notifications', () => ({
}))
function render(ui: ReactElement) {
- return renderWithConsoleQuery(ui, {
- systemFeatures: { deployment_edition: 'CLOUD' },
- features: { annotation_quota_limit: { size: mockAnnotatedResponseUsage, limit: 100 } },
- })
+ const { wrapper: NuqsWrapper } = createNuqsTestWrapper()
+ return renderWithConsoleQuery(
+ <NuqsWrapper>
+ <ModalContextProvider>{ui}</ModalContextProvider>
+ </NuqsWrapper>,
+ {
+ systemFeatures: { deployment_edition: 'CLOUD' },
+ features: { annotation_quota_limit: { size: mockAnnotatedResponseUsage, limit: 100 } },
+ },
+ )
}
describe('AnnotationCtrlButton', () => {
beforeEach(() => {
vi.clearAllMocks()
mockAnnotatedResponseUsage = 5
+ api.addAnnotation.mockResolvedValue({ id: 'annotation-1' })
})
it('should call onEdit when edit button is clicked', async () => {
@@ -99,7 +103,7 @@ describe('AnnotationCtrlButton', () => {
await user.click(screen.getByRole('button', { name: 'appDebug.feature.annotation.add' }))
await waitFor(() => {
- expect(mockAddAnnotation).toHaveBeenCalledWith({
+ expect(api.addAnnotation).toHaveBeenCalledWith({
params: { app_id: 'test-app' },
body: { message_id: 'msg-1', question: 'test query', answer: 'test answer' },
})
@@ -124,7 +128,10 @@ describe('AnnotationCtrlButton', () => {
await user.click(screen.getByRole('button', { name: 'appDebug.feature.annotation.add' }))
- expect(mockSetShowAnnotationFullModal).toHaveBeenCalled()
- expect(mockAddAnnotation).not.toHaveBeenCalled()
+ const dialog = await screen.findByRole('dialog')
+ expect(within(dialog).getByText('billing.annotatedResponse.fullTipLine1')).toBeInTheDocument()
+ expect(api.addAnnotation).not.toHaveBeenCalled()
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
})
diff --git a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx
index 6b277c9bcd1..7671326966a 100644
--- a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx
@@ -1,15 +1,14 @@
import type { ComponentProps, ReactNode } from 'react'
-import type { FileUploaderInAttachmentWrapperProps } from '@/app/components/base/file-uploader/file-uploader-in-attachment'
+import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { fileUpload } from '@/app/components/base/file-uploader/utils'
import { zAppAgentModePayload } from '@dify/contracts/api/console/apps/zod.gen'
-import { fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
+import { render as rtlRender, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useRef, useState } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { useFile } from '@/app/components/base/file-uploader/hooks'
-import { FileContextProvider, useStore } from '@/app/components/base/file-uploader/store'
import { InputVarType } from '@/app/components/workflow/types'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { TransferMethod } from '@/types/app'
import AppInputsForm from '../app-inputs-form'
const render = (ui: ReactNode) => rtlRender(ui, { wrapper: createConsoleQueryWrapper().wrapper })
@@ -28,44 +27,6 @@ vi.mock('@/app/components/base/file-uploader/utils', async (importOriginal) => (
vi.mock('uuid', () => ({ v4: () => 'file-1' }))
-function UploadControls({ fileConfig }: Pick<FileUploaderInAttachmentWrapperProps, 'fileConfig'>) {
- const files = useStore((state) => state.files)
- const { handleLocalFileUpload, handleClearFiles, handleReUploadFile } = useFile(fileConfig)
- return (
- <div>
- <span data-testid="file-uploader-value">{JSON.stringify(files)}</span>
- <button
- data-testid="file-uploader"
- onClick={() => handleLocalFileUpload(new File(['png'], 'demo.png', { type: 'image/png' }))}
- >
- Upload
- </button>
- <button data-testid="file-uploader-empty" onClick={handleClearFiles}>
- Upload Empty
- </button>
- {files
- .filter((file) => file.progress === -1)
- .map((file) => (
- <button key={file.id} onClick={() => handleReUploadFile(file.id)}>
- Retry {file.name}
- </button>
- ))}
- </div>
- )
-}
-
-vi.mock('@/app/components/base/file-uploader', () => ({
- FileUploaderInAttachmentWrapper: ({
- onChange,
- value,
- fileConfig,
- }: FileUploaderInAttachmentWrapperProps) => (
- <FileContextProvider value={value} onChange={onChange}>
- <UploadControls fileConfig={fileConfig} />
- </FileContextProvider>
- ),
-}))
-
type AppInputsFormProps = ComponentProps<typeof AppInputsForm>
const parseAgentToolInputs = (inputs: Record<string, unknown> | undefined) =>
@@ -91,6 +52,22 @@ const parseAgentToolInputs = (inputs: Record<string, unknown> | undefined) =>
],
})
+const createUploadedFile = (overrides: Partial<FileEntity> = {}): FileEntity => ({
+ id: 'existing-file',
+ name: 'existing.png',
+ size: 3,
+ type: 'image/png',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'image',
+ uploadedId: 'uploaded-existing-file',
+ base64Url: 'data:image/png;base64,cG5n',
+ ...overrides,
+})
+
+const getFileInput = () => document.querySelector<HTMLInputElement>('input[type="file"]')!
+const createLocalFile = () => new File(['png'], 'demo.png', { type: 'image/png' })
+
const renderControlledForm = ({
inputsForms,
initialInputs,
@@ -114,6 +91,11 @@ const renderControlledForm = ({
return (
<>
<button onClick={() => setOpen(!open)}>{open ? 'Close inputs' : 'Open inputs'}</button>
+ <output aria-label="form values">
+ {JSON.stringify(inputs, (key, value) =>
+ key === 'originalFile' && value instanceof File ? value.name : value,
+ )}
+ </output>
{open && (
<AppInputsForm
inputsForms={inputsForms}
@@ -226,13 +208,9 @@ describe('AppInputsForm', () => {
onFormChange,
})
- await user.click(screen.getByRole('button', { name: 'Upload' }))
- await waitFor(() =>
- expect(screen.getByTestId('file-uploader-value')).toHaveTextContent('uploaded-file-1'),
- )
+ await user.upload(getFileInput(), createLocalFile())
+ expect(await screen.findByText('demo.png')).toBeInTheDocument()
- const selectedInputs = onFormChange.mock.lastCall?.[0]
- expect(() => parseAgentToolInputs(selectedInputs)).not.toThrow()
const persistedFile = {
id: 'file-1',
name: 'demo.png',
@@ -244,9 +222,20 @@ describe('AppInputsForm', () => {
uploadedId: 'uploaded-file-1',
base64Url: 'data:image/png;base64,cG5n',
}
- expect(selectedInputs).toEqual({
+ const expectedInputs = {
attachment: type === InputVarType.singleFile ? persistedFile : [persistedFile],
- })
+ }
+ await waitFor(() => expect(onFormChange).toHaveBeenLastCalledWith(expectedInputs))
+
+ const selectedInputs = onFormChange.mock.lastCall![0]
+ expect(() => parseAgentToolInputs(selectedInputs)).not.toThrow()
+ expect(selectedInputs).toEqual(expectedInputs)
+ expect(screen.getByRole('status', { name: 'form values' })).toHaveTextContent(
+ 'uploaded-file-1',
+ )
+ await user.click(screen.getByRole('button', { name: 'Close inputs' }))
+ await user.click(screen.getByRole('button', { name: 'Open inputs' }))
+ expect(screen.getByText('demo.png')).toBeInTheDocument()
},
)
@@ -271,56 +260,79 @@ describe('AppInputsForm', () => {
onFormChange,
})
- await user.click(screen.getByRole('button', { name: 'Upload' }))
- await screen.findByRole('button', { name: 'Retry demo.png' })
+ await user.upload(getFileInput(), createLocalFile())
+ await screen.findByRole('button', { name: 'common.operation.retry demo.png' })
const originalFile = mockFileUpload.mock.calls[0]?.[0].file
expect(() => parseAgentToolInputs(onFormChange.mock.lastCall?.[0])).toThrow()
await user.click(screen.getByRole('button', { name: 'Close inputs' }))
- expect(screen.queryByRole('button', { name: 'Retry demo.png' })).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.retry demo.png' }),
+ ).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Open inputs' }))
- await user.click(screen.getByRole('button', { name: 'Retry demo.png' }))
+ expect(screen.getByText('demo.png')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'common.operation.retry demo.png' }))
expect(mockFileUpload.mock.lastCall?.[0].file).toBe(originalFile)
- expect(screen.queryByRole('button', { name: 'Retry demo.png' })).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: 'common.operation.retry demo.png' }),
+ ).not.toBeInTheDocument()
expect(() => parseAgentToolInputs(onFormChange.mock.lastCall?.[0])).not.toThrow()
+ expect(screen.getByRole('status', { name: 'form values' })).toHaveTextContent('uploaded-file-1')
})
- it('should keep multi-file values and forward empty multi-file uploads', () => {
+ it('should remove every multi-file value and publish an empty list', async () => {
+ const user = userEvent.setup()
const onFormChange = vi.fn()
- const existingFiles = [{ id: 'existing-file', name: 'existing.png' }]
+ const existingFiles = [
+ createUploadedFile(),
+ createUploadedFile({
+ id: 'remaining-file',
+ name: 'remaining.png',
+ uploadedId: 'uploaded-remaining-file',
+ }),
+ ]
- render(
- <AppInputsForm
- inputsForms={[
- {
- variable: 'files',
- label: 'Files',
- type: InputVarType.multiFiles,
- required: true,
- max_length: 3,
- allowed_file_types: ['image'],
- allowed_file_extensions: ['.png'],
- allowed_file_upload_methods: ['local_file'],
- },
- ]}
- inputs={{ files: existingFiles }}
- inputsRef={{ current: { files: existingFiles } }}
- onFormChange={onFormChange}
- />,
- )
+ renderControlledForm({
+ inputsForms: [
+ {
+ variable: 'files',
+ label: 'Files',
+ type: InputVarType.multiFiles,
+ required: true,
+ max_length: 3,
+ allowed_file_types: ['image'],
+ allowed_file_extensions: ['.png'],
+ allowed_file_upload_methods: ['local_file'],
+ },
+ ],
+ initialInputs: { files: existingFiles },
+ onFormChange,
+ })
- expect(screen.getByTestId('file-uploader-value')).toHaveTextContent('"existing-file"')
+ expect(screen.getByText('existing.png')).toBeInTheDocument()
+ expect(screen.getByText('remaining.png')).toBeInTheDocument()
expect(screen.queryByText('workflow.panel.optional')).not.toBeInTheDocument()
- fireEvent.click(screen.getByTestId('file-uploader-empty'))
- expect(onFormChange).toHaveBeenCalledWith({ files: [] })
+ await user.click(screen.getByRole('button', { name: 'common.operation.remove existing.png' }))
+ expect(onFormChange).toHaveBeenLastCalledWith({ files: [existingFiles[1]] })
+ expect(screen.queryByText('existing.png')).not.toBeInTheDocument()
+ expect(screen.getByText('remaining.png')).toBeInTheDocument()
+ expect(screen.getByRole('status', { name: 'form values' })).toHaveTextContent(
+ 'uploaded-remaining-file',
+ )
+
+ await user.click(screen.getByRole('button', { name: 'common.operation.remove remaining.png' }))
+ expect(onFormChange).toHaveBeenLastCalledWith({ files: [] })
+ expect(screen.queryByText('existing.png')).not.toBeInTheDocument()
+ expect(screen.queryByText('remaining.png')).not.toBeInTheDocument()
+ expect(screen.getByRole('status', { name: 'form values' }).textContent).toBe('{"files":[]}')
})
it('should remove cleared single-file inputs while keeping agent tool parameters publishable', async () => {
const user = userEvent.setup()
const onFormChange = vi.fn<(value: Record<string, unknown>) => void>()
- const existingFile = { id: 'existing-file', name: 'existing.png' }
+ const existingFile = createUploadedFile()
const siblingInputs = { enabled: false, count: 0, note: '', nullable: null }
renderControlledForm({
@@ -339,13 +351,14 @@ describe('AppInputsForm', () => {
onFormChange,
})
- expect(screen.getByTestId('file-uploader-value')).toHaveTextContent('"existing-file"')
+ expect(screen.getByText('existing.png')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'Upload Empty' }))
+ await user.click(screen.getByRole('button', { name: 'common.operation.remove existing.png' }))
expect(() => parseAgentToolInputs(onFormChange.mock.lastCall?.[0])).not.toThrow()
expect(onFormChange).toHaveBeenLastCalledWith(siblingInputs)
expect(onFormChange.mock.lastCall?.[0]).not.toHaveProperty('attachment')
- expect(screen.getByTestId('file-uploader-value')).toHaveTextContent('[]')
+ expect(screen.queryByText('existing.png')).not.toBeInTheDocument()
+ expect(screen.getByRole('status', { name: 'form values' })).not.toHaveTextContent('attachment')
})
})
diff --git a/web/app/components/plugins/plugin-item/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-item/__tests__/index.spec.tsx
index 281857b4793..fdd60d792c3 100644
--- a/web/app/components/plugins/plugin-item/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-item/__tests__/index.spec.tsx
@@ -1,9 +1,18 @@
-import type { ReactElement } from 'react'
+import type { ReactElement, ReactNode } from 'react'
import type { PluginDeclaration, PluginDetail } from '../../types'
-import { screen, waitFor } from '@testing-library/react'
+import { useQuery } from '@tanstack/react-query'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import { ModalContextProvider } from '@/context/modal-context-provider'
+import { consoleQuery } from '@/service/console'
+import { useInstalledPluginList } from '@/service/use-plugins'
+import { createCatalogModelFixture, createModelCatalogFixture } from '@/test/console/model-provider'
import { renderWithConsoleQuery } from '@/test/console/query-data'
+import { createPluginEntity } from '@/test/fixtures/plugin'
+import { PluginPageContext } from '../../plugin-page/context'
import { PluginCategoryEnum, PluginSource } from '../../types'
import PluginItem from '../index'
@@ -13,23 +22,7 @@ const mockTheme = vi.fn(() => 'light')
vi.mock('@/hooks/use-theme', () => ({
default: () => ({ theme: mockTheme() }),
}))
-
-const mockSelectedItem = vi.fn((): { type: 'plugin'; id: string } | undefined => undefined)
-const mockSetSelectedItem = vi.fn()
-vi.mock('../../plugin-page/context', () => ({
- usePluginPageContext: (selector: (v: Record<string, unknown>) => unknown) => {
- const context = {
- selectedItem: mockSelectedItem(),
- setSelectedItem: mockSetSelectedItem,
- }
- return selector(context)
- },
-}))
-
-const mockRefreshPluginList = vi.fn()
-vi.mock('@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list', () => ({
- default: () => ({ refreshPluginList: mockRefreshPluginList }),
-}))
+const PluginPageContextProvider = PluginPageContext.Provider
const mockLangGeniusVersionInfo = vi.fn(() => ({
current_env: '',
@@ -47,24 +40,67 @@ const createLangGeniusVersionInfo = (currentVersion: string) => ({
version: '',
})
-const render = (ui: ReactElement) =>
- renderWithConsoleQuery(ui, {
+function PluginPageBoundary({ children }: { children: ReactNode }) {
+ const [selectedItem, setSelectedItem] = useState<
+ { type: 'plugin'; id: string } | { type: 'builtinTool'; id: string }
+ >()
+ return (
+ <PluginPageContextProvider
+ value={{
+ containerRef: { current: null },
+ selectedItem,
+ setSelectedItem,
+ filters: { categories: [], tags: [], searchQuery: '' },
+ setFilters: () => {},
+ activeTab: 'plugins',
+ setActiveTab: () => {},
+ options: [],
+ }}
+ >
+ <output aria-label="selected plugin">
+ {selectedItem ? `${selectedItem.type}:${selectedItem.id}` : 'none'}
+ </output>
+ {children}
+ </PluginPageContextProvider>
+ )
+}
+
+const render = (ui: ReactElement) => {
+ const wrap = (element: ReactElement) => (
+ <PluginPageBoundary>
+ <ModalContextProvider>{element}</ModalContextProvider>
+ </PluginPageBoundary>
+ )
+ const rendered = renderWithConsoleQuery(wrap(ui), {
accountProfileMeta: {
currentVersion: mockLangGeniusVersionInfo().current_version,
},
systemFeatures: { enable_marketplace: mockEnableMarketplace() },
})
+ return { ...rendered, rerender: (element: ReactElement) => rendered.rerender(wrap(element)) }
+}
-const requests = vi.hoisted(() => ({ uninstall: vi.fn() }))
+const requests = vi.hoisted(() => ({
+ categoryList: vi.fn(),
+ models: vi.fn(),
+ uninstall: vi.fn(),
+}))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'workspaces.current.plugin.byCategory.list.get': requests.categoryList,
+ 'workspaces.current.models.modelTypes.byModelType.get': requests.models,
+ }),
+ }
+})
vi.mock('@/service/plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/plugins')>()),
uninstallPlugin: requests.uninstall,
}))
-vi.mock('@/context/modal-context', () => ({
- useModalContext: () => ({ setShowUpdatePluginModal: vi.fn() }),
-}))
-
const createPluginDeclaration = (
overrides: Partial<PluginDeclaration> = {},
): PluginDeclaration => ({
@@ -120,11 +156,44 @@ const createPluginDetail = (overrides: Partial<PluginDetail> = {}): PluginDetail
...overrides,
})
+let installedPlugins: ReturnType<typeof createPluginEntity>[] = []
+let modelCatalog: ReturnType<typeof createModelCatalogFixture>[] = []
+
+function InstalledPluginList({ category }: { category: PluginCategoryEnum }) {
+ const { data } = useInstalledPluginList({ category, staleTime: 0 })
+ const plugins = data?.plugins ?? []
+
+ return (
+ <output aria-label="installed plugin ids">
+ {plugins.map((plugin) => plugin.plugin_id).join(',') || 'none'}
+ </output>
+ )
+}
+
+function ModelCatalog() {
+ const { data = [] } = useQuery(
+ consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
+ input: { params: { model_type: ModelTypeEnum.textGeneration } },
+ select: (response) =>
+ response.data.flatMap((provider) => provider.models.map((model) => model.model)),
+ }),
+ )
+
+ return <output aria-label="model ids">{data.join(',') || 'none'}</output>
+}
+
beforeEach(() => {
vi.clearAllMocks()
+ installedPlugins = []
+ modelCatalog = []
+ requests.categoryList.mockImplementation(async () => ({
+ plugins: installedPlugins,
+ builtin_tools: [],
+ has_more: false,
+ }))
+ requests.models.mockImplementation(async () => ({ data: modelCatalog }))
requests.uninstall.mockResolvedValue({ success: true })
mockTheme.mockReturnValue('light')
- mockSelectedItem.mockReturnValue(undefined)
mockEnableMarketplace.mockReturnValue(true)
mockLangGeniusVersionInfo.mockReturnValue(createLangGeniusVersionInfo('1.0.0'))
})
@@ -222,41 +291,110 @@ describe('Installed plugin card', () => {
it('selects the plugin from the card and keeps its actions separate', async () => {
const user = userEvent.setup()
- render(<PluginItem plugin={createPluginDetail()} />)
- const card = screen.getByRole('button', { name: 'Test Plugin' })
+ render(
+ <>
+ <section aria-label="Other plugin card">
+ <PluginItem
+ plugin={createPluginDetail({
+ id: 'plugin-2',
+ plugin_id: 'plugin-2',
+ declaration: createPluginDeclaration({
+ name: 'other-plugin',
+ label: { en_US: 'Other Plugin' } as PluginDeclaration['label'],
+ }),
+ })}
+ />
+ </section>
+ <section aria-label="Test plugin card">
+ <PluginItem plugin={createPluginDetail()} />
+ </section>
+ </>,
+ )
+ const otherPlugin = within(screen.getByRole('region', { name: 'Other plugin card' }))
+ const testPlugin = within(screen.getByRole('region', { name: 'Test plugin card' }))
+ const otherCard = otherPlugin.getByRole('button', { name: 'Other Plugin' })
await user.tab()
- expect(card).toHaveFocus()
+ expect(otherCard).toHaveFocus()
await user.keyboard('{Enter}')
- expect(mockSetSelectedItem).toHaveBeenCalledExactlyOnceWith({ type: 'plugin', id: 'plugin-1' })
- mockSetSelectedItem.mockClear()
- const action = screen.getByRole('button', { name: 'plugin.action.delete' })
+ expect(screen.getByRole('status', { name: 'selected plugin' })).toHaveTextContent(
+ 'plugin:plugin-2',
+ )
+ const card = testPlugin.getByRole('button', { name: 'Test Plugin' })
+ const action = testPlugin.getByRole('button', { name: 'plugin.action.delete' })
expect(card).not.toContainElement(action)
- expect(card).not.toContainElement(screen.getByRole('link', { name: /marketplace/ }))
+ expect(card).not.toContainElement(testPlugin.getByRole('link', { name: /marketplace/ }))
await user.click(action)
expect(screen.getByRole('alertdialog', { name: 'plugin.action.delete' })).toHaveTextContent(
'test-plugin',
)
- expect(mockSetSelectedItem).not.toHaveBeenCalled()
+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
+ expect(screen.getByRole('status', { name: 'selected plugin' })).toHaveTextContent(
+ 'plugin:plugin-2',
+ )
})
- it('refreshes the current plugin category after a real uninstall succeeds', async () => {
+ it('refreshes the visible plugin category after a real uninstall succeeds', async () => {
const user = userEvent.setup()
- const { rerender } = render(<PluginItem plugin={createPluginDetail()} />)
+ const installedModelPlugin = createPluginEntity({
+ id: 'new-installation',
+ installation_id: 'new-installation',
+ plugin_id: 'plugin-1',
+ })
+ installedModelPlugin.declaration.author = 'test-author'
+ installedModelPlugin.declaration.name = 'test-plugin'
+ installedModelPlugin.declaration.category = PluginCategoryEnum.model
+ installedModelPlugin.declaration.label = { en_US: 'Test Plugin' }
+ installedModelPlugin.declaration.description = { en_US: 'Test plugin description' }
+ installedPlugins = [installedModelPlugin]
+ modelCatalog = [
+ createModelCatalogFixture({
+ models: [createCatalogModelFixture({ model: 'catalog-model' })],
+ }),
+ ]
+ requests.uninstall.mockImplementation(async () => {
+ installedPlugins = []
+ modelCatalog = []
+ return { success: true }
+ })
+
+ const renderCard = (plugin: PluginDetail) => (
+ <>
+ <PluginItem plugin={plugin} />
+ <InstalledPluginList category={PluginCategoryEnum.model} />
+ <ModelCatalog />
+ </>
+ )
+
+ const { rerender } = render(renderCard(createPluginDetail()))
+ await waitFor(() =>
+ expect(screen.getByRole('status', { name: 'installed plugin ids' })).toHaveTextContent(
+ 'plugin-1',
+ ),
+ )
+ await waitFor(() =>
+ expect(screen.getByRole('status', { name: 'model ids' })).toHaveTextContent('catalog-model'),
+ )
rerender(
- <PluginItem
- plugin={createPluginDetail({
+ renderCard(
+ createPluginDetail({
installation_id: 'new-installation',
declaration: createPluginDeclaration({ category: PluginCategoryEnum.model }),
- })}
- />,
+ }),
+ ),
)
+
await user.click(screen.getByRole('button', { name: 'plugin.action.delete' }))
await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(requests.uninstall).toHaveBeenCalledExactlyOnceWith('new-installation')
- expect(mockRefreshPluginList).toHaveBeenCalledExactlyOnceWith({
- category: PluginCategoryEnum.model,
- })
+ await waitFor(() =>
+ expect(screen.getByRole('status', { name: 'installed plugin ids' })).toHaveTextContent(
+ 'none',
+ ),
+ )
+ await waitFor(() =>
+ expect(screen.getByRole('status', { name: 'model ids' })).toHaveTextContent('none'),
+ )
})
it.each([