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

Stephen Zhou910ce5569591
diff --git a/web/app/components/base/chat/chat-with-history/inputs-form/__tests__/index.spec.tsx b/web/app/components/base/chat/chat-with-history/inputs-form/__tests__/index.spec.tsx
index eb85f5caec3..2ff145770d8 100644
--- a/web/app/components/base/chat/chat-with-history/inputs-form/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/inputs-form/__tests__/index.spec.tsx
@@ -1,45 +1,49 @@
-import type { ChatWithHistoryContextValue } from '../../context'
-import { act, render, screen } from '@testing-library/react'
+import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
-import { InputVarType } from '@/app/components/workflow/types'
-import { ChatWithHistoryContext, useChatWithHistoryContext } from '../../context'
+import { fetchChatList, fetchConversations } from '@/service/share'
+import { createChatConfigFixture } from '@/test/fixtures/chat'
+import { CONVERSATION_ID_INFO, TAB_CONVERSATION_ID_INFO } from '../../../constants'
+import { renderChatHistory } from '../../__tests__/chat-history-test-env'
import InputsFormNode from '../index'
-function Conversation({
- overrides = {},
- initiallyCollapsed = true,
-}: {
- overrides?: Partial<ChatWithHistoryContextValue>
- initiallyCollapsed?: boolean
-}) {
- const defaults = useChatWithHistoryContext()
+vi.mock('@/service/share', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/share')>()),
+ fetchChatList: vi.fn(),
+ fetchConversations: vi.fn(),
+}))
+
+function Conversation({ initiallyCollapsed = true }: { initiallyCollapsed?: boolean }) {
const [collapsed, setCollapsed] = useState(initiallyCollapsed)
- return (
- <ChatWithHistoryContext.Provider
- value={{
- ...defaults,
- inputsForms: [{ variable: 'topic', type: InputVarType.textInput, label: 'Topic' }],
- ...overrides,
- }}
- >
- <InputsFormNode collapsed={collapsed} setCollapsed={setCollapsed} />
- </ChatWithHistoryContext.Provider>
- )
+ return <InputsFormNode collapsed={collapsed} setCollapsed={setCollapsed} />
}
+const topic = { label: 'Topic', variable: 'topic', required: true, default: '' }
+const appParams = createChatConfigFixture({ user_input_form: [{ 'text-input': topic }] })
+
+beforeEach(() => {
+ vi.mocked(fetchChatList).mockResolvedValue({ data: [] })
+ vi.mocked(fetchConversations).mockResolvedValue({ data: [], has_more: false, limit: 100 })
+})
+afterEach(() => {
+ localStorage.removeItem(CONVERSATION_ID_INFO)
+ sessionStorage.removeItem(TAB_CONVERSATION_ID_INFO)
+ localStorage.removeItem('webappSidebarCollapse')
+})
describe('InputsFormNode', () => {
- it.each([{ allInputsHidden: true }, { inputsForms: [] }])(
- 'omits settings when no inputs are available: %j',
- (overrides) => {
- const { container } = render(<Conversation overrides={overrides} />)
- expect(container).toBeEmptyDOMElement()
- },
- )
+ it.each([
+ { name: 'hidden inputs', user_input_form: [{ 'text-input': { ...topic, hide: true } }] },
+ { name: 'no inputs', user_input_form: [] },
+ ])('omits settings for $name', ({ user_input_form }) => {
+ const { container } = renderChatHistory(<Conversation />, {
+ appParams: createChatConfigFixture({ user_input_form }),
+ })
+ expect(container).toBeEmptyDOMElement()
+ })
it('opens and closes settings for an existing conversation', async () => {
const user = userEvent.setup()
- render(<Conversation overrides={{ currentConversationId: 'conv-1' }} />)
+ renderChatHistory(<Conversation />, { appParams })
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()
@@ -50,13 +54,15 @@ describe('InputsFormNode', () => {
it('collapses new conversation settings only after starting chat succeeds', async () => {
const user = userEvent.setup()
- const handleStartChat = vi.fn<ChatWithHistoryContextValue['handleStartChat']>()
- render(<Conversation initiallyCollapsed={false} overrides={{ handleStartChat }} />)
+ renderChatHistory(<Conversation initiallyCollapsed={false} />, {
+ currentConversationId: '',
+ appParams,
+ })
+ await user.click(screen.getByRole('button', { name: 'share.chat.startChat' }))
+ expect(screen.getByRole('textbox', { name: 'Topic' })).toBeVisible()
+ await user.type(screen.getByRole('textbox', { name: 'Topic' }), 'Travel')
await user.click(screen.getByRole('button', { name: 'share.chat.startChat' }))
- expect(handleStartChat).toHaveBeenCalledTimes(1)
- expect(screen.getByRole('textbox', { name: 'Topic' })).toBeInTheDocument()
- act(() => handleStartChat.mock.calls[0]![0]?.())
expect(screen.queryByRole('textbox', { name: 'Topic' })).not.toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'common.operation.edit' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'common.operation.edit' })).toBeVisible()
})
})
diff --git a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
index 15ba85491b6..f48a1ddcf40 100644
--- a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
@@ -1,16 +1,42 @@
import type { ChatWithHistoryContextValue } from '../../context'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import {
+ AppSourceType,
+ delConversation,
+ fetchChatList,
+ fetchConversations,
+ pinConversation,
+ renameConversation,
+ unpinConversation,
+} from '@/service/share'
import { renderWithConsoleQuery } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
+import { CONVERSATION_ID_INFO, TAB_CONVERSATION_ID_INFO } from '../../../constants'
+import { renderChatHistory } from '../../__tests__/chat-history-test-env'
import { ChatWithHistoryContext, useChatWithHistoryContext } from '../../context'
import Sidebar from '../index'
+vi.mock('@/service/share', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/share')>()),
+ fetchChatList: vi.fn(),
+ fetchConversations: vi.fn(),
+ pinConversation: vi.fn(),
+ unpinConversation: vi.fn(),
+ renameConversation: vi.fn(),
+ delConversation: vi.fn(),
+}))
vi.mock('@/next/navigation', () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => '/chat/app-1',
}))
const conversation = (id: string, name: string) => ({ id, name, inputs: {}, introduction: '' })
+const conversations = [
+ conversation('1', 'First conversation'),
+ conversation('2', 'Second conversation'),
+]
+const pinnedConversations = [conversation('p1', 'Pinned conversation')]
const appData = {
site: {
title: 'Test App',
@@ -22,59 +48,66 @@ const appData = {
custom_config: {},
} as ChatWithHistoryContextValue['appData']
-function renderSidebar(
- overrides: Partial<ChatWithHistoryContextValue> = {},
- branding = { enabled: false, workspace_logo: '' },
-) {
- const handlers = {
- handleNewConversation: vi.fn(),
- handleChangeConversation: vi.fn(),
- handlePinConversation: vi.fn(),
- handleUnpinConversation: vi.fn(),
- handleDeleteConversation: vi.fn(),
- handleRenameConversation: vi.fn(),
- handleSidebarCollapse: vi.fn(),
+beforeEach(() => {
+ vi.mocked(fetchChatList).mockResolvedValue({ data: [] })
+ vi.mocked(fetchConversations).mockImplementation(async (_source, _app, _last, pinned) => ({
+ data: pinned ? pinnedConversations : conversations,
+ has_more: false,
+ limit: 100,
+ }))
+ vi.mocked(pinConversation).mockResolvedValue(undefined)
+ vi.mocked(unpinConversation).mockResolvedValue(undefined)
+ vi.mocked(renameConversation).mockResolvedValue(undefined)
+ vi.mocked(delConversation).mockResolvedValue(undefined)
+})
+afterEach(() => {
+ localStorage.removeItem(CONVERSATION_ID_INFO)
+ sessionStorage.removeItem(TAB_CONVERSATION_ID_INFO)
+ localStorage.removeItem('webappSidebarCollapse')
+})
+
+function renderSidebar(options: Parameters<typeof renderChatHistory>[1] = {}) {
+ return {
+ ...renderChatHistory(<Sidebar />, {
+ currentConversationId: '1',
+ conversations,
+ pinnedConversations,
+ ...options,
+ }),
+ user: userEvent.setup(),
}
- function Harness({ state }: { state: Partial<ChatWithHistoryContextValue> }) {
+}
+function selectedConversation() {
+ return JSON.parse(sessionStorage.getItem(TAB_CONVERSATION_ID_INFO)!)['app-1']['user-1']
+}
+
+// Branding is a display contract with caller-supplied application metadata.
+function renderBranding(
+ overrides: Partial<ChatWithHistoryContextValue>,
+ branding: { enabled: boolean; workspace_logo: string },
+) {
+ function View() {
const defaults = useChatWithHistoryContext()
return (
- <ChatWithHistoryContext.Provider
- value={{
- ...defaults,
- ...handlers,
- appData,
- conversationList: [
- conversation('1', 'First conversation'),
- conversation('2', 'Second conversation'),
- ],
- pinnedConversationList: [conversation('p1', 'Pinned conversation')],
- ...state,
- }}
- >
+ <ChatWithHistoryContext.Provider value={{ ...defaults, appData, ...overrides }}>
<Sidebar />
</ChatWithHistoryContext.Provider>
)
}
- const result = renderWithConsoleQuery(<Harness state={overrides} />, {
- systemFeatures: { branding },
- })
- return {
- ...result,
- ...handlers,
- user: userEvent.setup(),
- update: (state: Partial<ChatWithHistoryContextValue>) =>
- result.rerender(<Harness state={{ ...overrides, ...state }} />),
- }
+ return renderWithConsoleQuery(<View />, { systemFeatures: { branding } })
}
+async function openOperations(user: ReturnType<typeof userEvent.setup>, name: string) {
+ const row = screen.getByRole('button', { name }).parentElement!
+ await user.hover(row)
+ await user.click(within(row).getByRole('button', { name: 'common.operation.more' }))
+}
async function operate(
user: ReturnType<typeof userEvent.setup>,
name: string,
action: 'pin' | 'unpin' | 'rename' | 'delete',
) {
- const row = screen.getByRole('button', { name }).parentElement!
- await user.hover(row)
- await user.click(within(row).getByRole('button', { name: 'common.operation.more' }))
+ await openOperations(user, name)
await user.click(
await screen.findByRole('menuitem', { name: `explore.sidebar.action.${action}` }),
)
@@ -82,99 +115,162 @@ async function operate(
describe('Conversation sidebar', () => {
it('selects conversations from both lists and keeps operations separate from selection', async () => {
- const { user, handleChangeConversation, handlePinConversation, handleUnpinConversation } =
- renderSidebar()
+ const { user, queryClient, listKey } = renderSidebar()
expect(screen.getByText('share.chat.pinnedTitle')).toBeInTheDocument()
expect(screen.getByText('share.chat.unpinnedTitle')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Second conversation' }))
+ expect(selectedConversation()).toBe('2')
await user.click(screen.getByRole('button', { name: 'Pinned conversation' }))
- expect(handleChangeConversation.mock.calls).toEqual([['2'], ['p1']])
+ expect(selectedConversation()).toBe('p1')
+ vi.mocked(fetchConversations).mockImplementation(async (_source, _app, _last, pinned) => ({
+ data: pinned ? [...pinnedConversations, conversations[0]!] : [conversations[1]!],
+ has_more: false,
+ limit: 100,
+ }))
await operate(user, 'First conversation', 'pin')
+ await waitFor(() =>
+ expect(queryClient.getQueryData(listKey(true))).toMatchObject({
+ data: [...pinnedConversations, conversations[0]!],
+ }),
+ )
+ expect(pinConversation).toHaveBeenCalledExactlyOnceWith(AppSourceType.webApp, 'app-1', '1')
+ await openOperations(user, 'First conversation')
+ expect(
+ await screen.findByRole('menuitem', { name: 'explore.sidebar.action.unpin' }),
+ ).toBeVisible()
+ await user.keyboard('{Escape}')
+ vi.mocked(fetchConversations).mockImplementation(async (_source, _app, _last, pinned) => ({
+ data: pinned ? [conversations[0]!] : [conversations[1]!, ...pinnedConversations],
+ has_more: false,
+ limit: 100,
+ }))
await operate(user, 'Pinned conversation', 'unpin')
- expect(handlePinConversation).toHaveBeenCalledExactlyOnceWith('1')
- expect(handleUnpinConversation).toHaveBeenCalledExactlyOnceWith('p1')
- expect(handleChangeConversation).toHaveBeenCalledTimes(2)
+ await waitFor(() =>
+ expect(queryClient.getQueryData(listKey(false))).toMatchObject({
+ data: [conversations[1]!, ...pinnedConversations],
+ }),
+ )
+ expect(unpinConversation).toHaveBeenCalledExactlyOnceWith(AppSourceType.webApp, 'app-1', 'p1')
+ await openOperations(user, 'Pinned conversation')
+ expect(
+ await screen.findByRole('menuitem', { name: 'explore.sidebar.action.pin' }),
+ ).toBeVisible()
+ await user.keyboard('{Escape}')
+ expect(selectedConversation()).toBe('p1')
})
it('starts a conversation only while no response is being generated', async () => {
- const { user, update, handleNewConversation } = renderSidebar({
- isResponding: true,
- pinnedConversationList: [],
- conversationList: [],
+ const { user, unmount } = renderSidebar({
+ ownerProps: { isResponding: true },
+ conversations: [],
+ pinnedConversations: [],
})
const newChat = screen.getByRole('button', { name: 'share.chat.newChat' })
await user.click(newChat)
expect(newChat).toBeDisabled()
- expect(handleNewConversation).not.toHaveBeenCalled()
+ expect(selectedConversation()).toBe('1')
expect(screen.queryByText('share.chat.pinnedTitle')).not.toBeInTheDocument()
expect(screen.queryByText('share.chat.unpinnedTitle')).not.toBeInTheDocument()
- update({ isResponding: false })
- await user.click(newChat)
- expect(handleNewConversation).toHaveBeenCalledTimes(1)
+ unmount()
+ renderSidebar({ conversations: [], pinnedConversations: [] })
+ await user.click(screen.getByRole('button', { name: 'share.chat.newChat' }))
+ expect(selectedConversation()).toBe('')
})
it.each([false, true])('toggles the desktop sidebar when collapsed=%s', async (collapsed) => {
- const { user, handleSidebarCollapse } = renderSidebar({ sidebarCollapseState: collapsed })
+ const { user } = renderSidebar({ sidebarCollapsed: collapsed })
await user.click(
screen.getByRole('button', {
name: collapsed ? 'layout.sidebar.expandSidebar' : 'layout.sidebar.collapseSidebar',
}),
)
- expect(handleSidebarCollapse).toHaveBeenCalledExactlyOnceWith(!collapsed)
+ expect(
+ screen.getByRole('button', {
+ name: collapsed ? 'layout.sidebar.collapseSidebar' : 'layout.sidebar.expandSidebar',
+ }),
+ ).toBeVisible()
+ expect(localStorage.getItem('webappSidebarCollapse')).toBe(collapsed ? 'expanded' : 'collapsed')
})
it('keeps desktop collapse actions out of the mobile sidebar', () => {
- renderSidebar({ isMobile: true })
+ renderSidebar({ ownerProps: { isMobile: true } })
expect(
screen.queryByRole('button', { name: /layout.sidebar.(expand|collapse)Sidebar/ }),
).not.toBeInTheDocument()
})
it('confirms deletion for the chosen conversation and closes only after success', async () => {
- const { user, handleDeleteConversation } = renderSidebar()
+ const pending = createDeferred<void>()
+ vi.mocked(delConversation).mockReturnValueOnce(pending.promise)
+ const { user } = renderSidebar({ currentConversationId: '2' })
await operate(user, 'Second conversation', 'delete')
const dialog = await screen.findByRole('alertdialog', {
name: 'share.chat.deleteConversation.title',
})
- expect(handleDeleteConversation).not.toHaveBeenCalled()
+ expect(delConversation).not.toHaveBeenCalled()
await user.click(within(dialog).getByRole('button', { name: 'common.operation.confirm' }))
- expect(handleDeleteConversation).toHaveBeenCalledExactlyOnceWith('2', {
- onSuccess: expect.any(Function),
- })
+ expect(delConversation).toHaveBeenCalledExactlyOnceWith(AppSourceType.webApp, 'app-1', '2')
expect(dialog).toBeInTheDocument()
- act(() => handleDeleteConversation.mock.calls[0]![1].onSuccess())
+ expect(selectedConversation()).toBe('2')
+ vi.mocked(fetchConversations).mockImplementation(async (_source, _app, _last, pinned) => ({
+ data: pinned ? pinnedConversations : [conversations[0]!],
+ has_more: false,
+ limit: 100,
+ }))
+ await act(async () => pending.resolve())
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ await waitFor(() =>
+ expect(screen.queryByRole('button', { name: 'Second conversation' })).not.toBeInTheDocument(),
+ )
+ expect(screen.getByRole('button', { name: 'First conversation' })).toBeVisible()
+ expect(selectedConversation()).toBe('')
})
it('cancels deletion without changing the conversation', async () => {
- const { user, handleDeleteConversation } = renderSidebar()
+ const { user } = renderSidebar()
await operate(user, 'First conversation', 'delete')
- const dialog = await screen.findByRole('alertdialog')
- await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))
+ await user.click(
+ within(await screen.findByRole('alertdialog')).getByRole('button', {
+ name: 'common.operation.cancel',
+ }),
+ )
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
- expect(handleDeleteConversation).not.toHaveBeenCalled()
+ expect(delConversation).not.toHaveBeenCalled()
+ expect(screen.getByRole('button', { name: 'First conversation' })).toBeVisible()
+ expect(selectedConversation()).toBe('1')
})
it('saves the edited name for the chosen conversation and blocks resubmission while saving', async () => {
- const { user, update, handleRenameConversation } = renderSidebar()
+ const pending = createDeferred<void>()
+ vi.mocked(renameConversation).mockReturnValueOnce(pending.promise)
+ const { user } = renderSidebar()
await operate(user, 'Second conversation', 'rename')
const input = await screen.findByRole('textbox', { name: 'common.chat.conversationName' })
expect(input).toHaveValue('Second conversation')
await user.clear(input)
await user.type(input, 'New name{Enter}')
- expect(handleRenameConversation).toHaveBeenCalledExactlyOnceWith('2', 'New name', {
- onSuccess: expect.any(Function),
- })
- update({ conversationRenaming: true })
+ expect(renameConversation).toHaveBeenCalledExactlyOnceWith(
+ AppSourceType.webApp,
+ 'app-1',
+ '2',
+ 'New name',
+ )
+ expect(screen.getByRole('button', { name: 'common.operation.save' })).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ )
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await user.type(input, '{Enter}')
- expect(handleRenameConversation).toHaveBeenCalledTimes(1)
- act(() => handleRenameConversation.mock.calls[0]![2].onSuccess())
+ expect(renameConversation).toHaveBeenCalledTimes(1)
+ await act(async () => pending.resolve())
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(await screen.findByRole('button', { name: 'New name' })).toBeVisible()
+ expect(screen.queryByRole('button', { name: 'Second conversation' })).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'First conversation' })).toBeVisible()
})
it('discards a cancelled rename before opening a different conversation', async () => {
- const { user, handleRenameConversation } = renderSidebar()
+ const { user } = renderSidebar()
await operate(user, 'First conversation', 'rename')
await user.type(
await screen.findByRole('textbox', { name: 'common.chat.conversationName' }),
@@ -186,7 +282,7 @@ describe('Conversation sidebar', () => {
expect(
await screen.findByRole('textbox', { name: 'common.chat.conversationName' }),
).toHaveValue('Second conversation')
- expect(handleRenameConversation).not.toHaveBeenCalled()
+ expect(renameConversation).not.toHaveBeenCalled()
})
it.each([
@@ -198,7 +294,7 @@ describe('Conversation sidebar', () => {
},
{ enabled: true, workspace_logo: '', expected: 'https://example.com/custom.png' },
])('chooses the effective branding logo: $expected', ({ expected, ...branding }) => {
- renderSidebar(
+ renderBranding(
{
appData: {
...appData!,
@@ -211,7 +307,7 @@ describe('Conversation sidebar', () => {
})
it('removes branding when the application disables it', () => {
- renderSidebar(
+ renderBranding(
{ appData: { ...appData!, custom_config: { remove_webapp_brand: true } } },
{ enabled: true, workspace_logo: 'https://example.com/workspace.png' },
)
diff --git a/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx b/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx
index cc5c4519011..1ddbf04730a 100644
--- a/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/inputs-form/__tests__/content.spec.tsx
@@ -1,11 +1,14 @@
import type { ReactElement, ReactNode } from 'react'
-import { fireEvent, render as renderComponent, screen, within } from '@testing-library/react'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useRef, useState } from 'react'
+import { fileUpload } from '@/app/components/base/file-uploader/utils'
import { InputVarType } from '@/app/components/workflow/types'
import { PromptMode } from '@/models/debug'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createDatasetConfigsFixture } from '@/test/fixtures/debug-configuration'
import { createEmbeddedChatbotContextFixture } from '@/test/fixtures/embedded-chatbot'
+import { TransferMethod } from '@/types/app'
import { EmbeddedChatbotContext } from '../../context'
import InputsFormContent from '../content'
@@ -16,45 +19,12 @@ vi.mock('@/next/navigation', () => ({
useSearchParams: () => new URLSearchParams(),
}))
-// Mock CodeEditor to trigger onChange easily
-vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
- default: ({
- value,
- onChange,
- placeholder,
- }: {
- value: string
- onChange: (v: string) => void
- placeholder: string | React.ReactNode
- }) => (
- <textarea
- data-testid="mock-code-editor"
- value={value}
- onChange={(e) => onChange(e.target.value)}
- placeholder={typeof placeholder === 'string' ? placeholder : 'json-placeholder'}
- />
- ),
+vi.mock('@/app/components/base/file-uploader/utils', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/app/components/base/file-uploader/utils')>()),
+ fileUpload: vi.fn(),
}))
-// Mock FileUploaderInAttachmentWrapper to trigger onChange easily
-vi.mock('@/app/components/base/file-uploader', () => ({
- FileUploaderInAttachmentWrapper: ({
- value,
- onChange,
- }: {
- value: File[]
- onChange: (v: File[]) => void
- }) => (
- <div data-testid="mock-file-uploader">
- <button onClick={() => onChange([new File([''], 'test.png', { type: 'image/png' })])}>
- Upload
- </button>
- <span>{value.length > 0 ? value[0]!.name : 'no file'}</span>
- </div>
- ),
-}))
-
-const mockContextValue = createEmbeddedChatbotContextFixture({
+const baseContext = createEmbeddedChatbotContextFixture({
appParams: {
opening_statement: '',
pre_prompt: '',
@@ -115,7 +85,7 @@ const mockContextValue = createEmbeddedChatbotContextFixture({
required: true,
allowed_file_types: ['image'],
allowed_file_extensions: ['.png'],
- allowed_file_upload_methods: ['local_upload'],
+ allowed_file_upload_methods: [TransferMethod.local_file],
},
{
variable: 'multi_file_var',
@@ -125,7 +95,7 @@ const mockContextValue = createEmbeddedChatbotContextFixture({
max_length: 5,
allowed_file_types: ['image'],
allowed_file_extensions: ['.png'],
- allowed_file_upload_methods: ['local_upload'],
+ allowed_file_upload_methods: [TransferMethod.local_file],
},
{
variable: 'json_var',
@@ -143,13 +113,11 @@ const mockContextValue = createEmbeddedChatbotContextFixture({
],
currentConversationId: '',
currentConversationInputs: {},
- setCurrentConversationInputs: vi.fn(),
newConversationInputs: {},
newConversationInputsRef: { current: {} },
- handleNewConversationInputsChange: vi.fn(),
})
-let context = mockContextValue
+let context = baseContext
function render(ui: ReactElement) {
function Wrapper({ children }: { children: ReactNode }) {
const [currentInputs, setCurrentInputs] = useState(context.currentConversationInputs)
@@ -163,31 +131,49 @@ function render(ui: ReactElement) {
newConversationInputs: newInputs,
newConversationInputsRef: newInputsRef,
setCurrentConversationInputs: (value) => {
- context.setCurrentConversationInputs(value)
setCurrentInputs(value)
},
handleNewConversationInputsChange: (value) => {
- context.handleNewConversationInputsChange(value)
newInputsRef.current = value
setNewInputs(value)
},
}}
>
{children}
+ <output aria-label="Current conversation inputs">{JSON.stringify(currentInputs)}</output>
+ <output aria-label="New conversation inputs">{JSON.stringify(newInputs)}</output>
</EmbeddedChatbotContext.Provider>
)
}
- return renderComponent(ui, { wrapper: Wrapper })
+ return renderWithConsoleQuery(<Wrapper>{ui}</Wrapper>)
}
+const currentInputs = () =>
+ JSON.parse(screen.getByLabelText('Current conversation inputs').textContent!)
+const newInputs = () => JSON.parse(screen.getByLabelText('New conversation inputs').textContent!)
+
describe('InputsFormContent', () => {
let user: ReturnType<typeof userEvent.setup>
beforeEach(() => {
- vi.clearAllMocks()
+ vi.mocked(fileUpload)
+ .mockReset()
+ .mockImplementation(({ file, onSuccessCallback }) => {
+ onSuccessCallback({
+ id: 'uploaded-file',
+ name: file.name,
+ size: file.size,
+ mime_type: file.type,
+ extension: 'png',
+ created_at: 0,
+ created_by: 'user-1',
+ source_url: '',
+ preview_url: null,
+ })
+ })
user = userEvent.setup()
- context = mockContextValue
+ context = baseContext
})
it('should render visible input forms', () => {
@@ -212,10 +198,10 @@ describe('InputsFormContent', () => {
const input = screen.getByRole('textbox', { name: 'Text Label' })
await user.type(input, 'hello')
- expect(mockContextValue.setCurrentConversationInputs).toHaveBeenLastCalledWith({
+ expect(currentInputs()).toEqual({
text_var: 'hello',
})
- expect(mockContextValue.handleNewConversationInputsChange).toHaveBeenLastCalledWith({
+ expect(newInputs()).toEqual({
text_var: 'hello',
})
})
@@ -225,10 +211,10 @@ describe('InputsFormContent', () => {
const input = screen.getByRole('spinbutton', { name: 'Number Label' })
await user.type(input, '123')
- expect(mockContextValue.setCurrentConversationInputs).toHaveBeenLastCalledWith({
+ expect(currentInputs()).toEqual({
num_var: '123',
})
- expect(mockContextValue.handleNewConversationInputsChange).toHaveBeenLastCalledWith({
+ expect(newInputs()).toEqual({
num_var: '123',
})
})
@@ -238,10 +224,10 @@ describe('InputsFormContent', () => {
const input = screen.getByRole('textbox', { name: 'Paragraph Label' })
await user.type(input, 'long text')
- expect(mockContextValue.setCurrentConversationInputs).toHaveBeenLastCalledWith({
+ expect(currentInputs()).toEqual({
para_var: 'long text',
})
- expect(mockContextValue.handleNewConversationInputsChange).toHaveBeenLastCalledWith({
+ expect(newInputs()).toEqual({
para_var: 'long text',
})
})
@@ -251,10 +237,10 @@ describe('InputsFormContent', () => {
const checkbox = screen.getByRole('checkbox', { name: 'Bool Label' })
await user.click(checkbox)
- expect(mockContextValue.setCurrentConversationInputs).toHaveBeenLastCalledWith({
+ expect(currentInputs()).toEqual({
bool_var: true,
})
- expect(mockContextValue.handleNewConversationInputsChange).toHaveBeenLastCalledWith({
+ expect(newInputs()).toEqual({
bool_var: true,
})
})
@@ -267,55 +253,55 @@ describe('InputsFormContent', () => {
const option = screen.getByText('Option 1')
await user.click(option)
- expect(mockContextValue.setCurrentConversationInputs).toHaveBeenLastCalledWith({
+ expect(currentInputs()).toEqual({
select_var: 'Option 1',
})
- expect(mockContextValue.handleNewConversationInputsChange).toHaveBeenLastCalledWith({
+ expect(newInputs()).toEqual({
select_var: 'Option 1',
})
})
- it('should handle single file upload change', async () => {
- render(<InputsFormContent />)
- await user.click(
- within(screen.getByTestId('inputs-form-item-file_var')).getByRole('button', {
- name: 'Upload',
- }),
- )
-
- expect(mockContextValue.setCurrentConversationInputs).toHaveBeenLastCalledWith({
- file_var: expect.objectContaining({ name: 'test.png' }),
- })
- expect(mockContextValue.handleNewConversationInputsChange).toHaveBeenLastCalledWith({
- file_var: expect.objectContaining({ name: 'test.png' }),
- })
- })
-
- it('should handle multi files upload change', async () => {
- render(<InputsFormContent />)
- await user.click(
- within(screen.getByTestId('inputs-form-item-multi_file_var')).getByRole('button', {
- name: 'Upload',
- }),
- )
-
- expect(mockContextValue.setCurrentConversationInputs).toHaveBeenLastCalledWith({
- multi_file_var: [expect.objectContaining({ name: 'test.png' })],
- })
- expect(mockContextValue.handleNewConversationInputsChange).toHaveBeenLastCalledWith({
- multi_file_var: [expect.objectContaining({ name: 'test.png' })],
- })
- })
+ it.each([
+ { variable: 'file_var', array: false },
+ { variable: 'multi_file_var', array: true },
+ ])(
+ 'uploads $variable and saves the expected scalar or list shape',
+ async ({ variable, array }) => {
+ render(<InputsFormContent />)
+ const input = screen
+ .getByTestId(`inputs-form-item-${variable}`)
+ .querySelector<HTMLInputElement>('input[type="file"]')!
+ const file = new File(['image'], 'test.png', { type: 'image/png' })
+ await user.upload(input, file)
+ const uploaded = expect.objectContaining({
+ name: 'test.png',
+ uploadedId: 'uploaded-file',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ })
+ const value = array ? [uploaded] : uploaded
+ await waitFor(() => expect(currentInputs()).toEqual({ [variable]: value }))
+ expect(newInputs()).toEqual({ [variable]: value })
+ expect(fileUpload).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ file }),
+ true,
+ undefined,
+ )
+ },
+ )
it('should handle JSON object change', async () => {
render(<InputsFormContent />)
- const jsonEditor = screen.getByTestId('mock-code-editor')
- fireEvent.change(jsonEditor, { target: { value: '{ "a": 1 }' } })
+ // Monaco is the external editor boundary provided by vitest.setup.ts.
+ const jsonEditor = screen.getByTestId('monaco-editor')
+ await user.click(jsonEditor)
+ await user.paste('{ "a": 1 }')
+ expect(jsonEditor).toHaveValue('{ "a": 1 }')
- expect(mockContextValue.setCurrentConversationInputs).toHaveBeenLastCalledWith({
+ expect(currentInputs()).toEqual({
json_var: '{ "a": 1 }',
})
- expect(mockContextValue.handleNewConversationInputsChange).toHaveBeenLastCalledWith({
+ expect(newInputs()).toEqual({
json_var: '{ "a": 1 }',
})
})
@@ -327,7 +313,7 @@ describe('InputsFormContent', () => {
it('should set initial values from context', () => {
const contextWithValues = {
- ...mockContextValue,
+ ...baseContext,
newConversationInputs: {
text_var: 'initial value',
},
@@ -341,7 +327,7 @@ describe('InputsFormContent', () => {
it('should use currentConversationInputs when currentConversationId exists', () => {
const contextWithConv = {
- ...mockContextValue,
+ ...baseContext,
currentConversationId: 'conv-id',
currentConversationInputs: {
text_var: 'conv value',
@@ -356,7 +342,7 @@ describe('InputsFormContent', () => {
it('should render numeric zero from context as zero', () => {
const contextWithZero = {
- ...mockContextValue,
+ ...baseContext,
newConversationInputs: {
num_var: 0,
},
diff --git a/web/app/components/base/file-uploader/__tests__/file-input.spec.tsx b/web/app/components/base/file-uploader/__tests__/file-input.spec.tsx
index de1913af3f9..65da98d2f39 100644
--- a/web/app/components/base/file-uploader/__tests__/file-input.spec.tsx
+++ b/web/app/components/base/file-uploader/__tests__/file-input.spec.tsx
@@ -1,46 +1,60 @@
import type { FileEntity } from '../types'
import type { FileUpload } from '@/app/components/base/features/types'
-import { fireEvent, render } from '@testing-library/react'
+import { fireEvent, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
import FileInput from '../file-input'
-import { FileContextProvider } from '../store'
+import { createFileStore, FileContext } from '../store'
+import { fileUpload } from '../utils'
-const mockHandleLocalFileUpload = vi.fn()
-
-vi.mock('../hooks', () => ({
- useFile: () => ({
- handleLocalFileUpload: mockHandleLocalFileUpload,
- }),
+vi.mock('../utils', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../utils')>()),
+ fileUpload: vi.fn(),
}))
+vi.mock('@/next/navigation', () => ({ useParams: () => ({}), usePathname: () => '/chat' }))
+
+const createFileConfig = (overrides: Partial<FileUpload> = {}): FileUpload => ({
+ enabled: true,
+ allowed_file_types: ['image'],
+ allowed_file_extensions: [],
+ number_limits: 5,
+ allowed_file_upload_methods: ['local_file'],
+ ...overrides,
+})
-const createFileConfig = (overrides: Partial<FileUpload> = {}): FileUpload =>
- ({
- enabled: true,
- allowed_file_types: ['image'],
- allowed_file_extensions: [],
- number_limits: 5,
- ...overrides,
- }) as FileUpload
-
-function createStubFile(id: string): FileEntity {
+function createUploadedFile(id: string): FileEntity {
return {
id,
- name: `${id}.txt`,
- size: 0,
- type: '',
+ name: `${id}.jpg`,
+ size: 1,
+ type: 'image/jpeg',
+ uploadedId: `uploaded-${id}`,
progress: 100,
- transferMethod: 'local_file' as FileEntity['transferMethod'],
- supportFileType: 'document',
+ transferMethod: 'local_file',
+ supportFileType: 'image',
}
}
function renderWithProvider(ui: React.ReactElement, fileIds: string[] = []) {
- return render(<FileContextProvider value={fileIds.map(createStubFile)}>{ui}</FileContextProvider>)
+ const store = createFileStore(fileIds.map(createUploadedFile))
+ return { ...renderWithConsoleQuery(<FileContext value={store}>{ui}</FileContext>), store }
}
describe('FileInput', () => {
beforeEach(() => {
- vi.clearAllMocks()
+ vi.mocked(fileUpload).mockImplementation(({ file, onSuccessCallback }) => {
+ onSuccessCallback({
+ id: `uploaded-${file.name}`,
+ name: file.name,
+ size: file.size,
+ mime_type: file.type,
+ extension: 'jpg',
+ created_at: 0,
+ created_by: 'user-1',
+ preview_url: null,
+ source_url: '',
+ })
+ })
})
it('should set accept attribute based on allowed file types', () => {
@@ -56,7 +70,7 @@ describe('FileInput', () => {
renderWithProvider(
<FileInput
fileConfig={createFileConfig({
- allowed_file_types: ['custom'] as unknown as FileUpload['allowed_file_types'],
+ allowed_file_types: ['custom'],
allowed_file_extensions: ['.csv', '.xlsx'],
})}
/>,
@@ -79,10 +93,10 @@ describe('FileInput', () => {
it('should respect number_limits when uploading multiple files', async () => {
const user = userEvent.setup()
- renderWithProvider(<FileInput fileConfig={createFileConfig({ number_limits: 3 })} />, [
- '1',
- '2',
- ])
+ const { store } = renderWithProvider(
+ <FileInput fileConfig={createFileConfig({ number_limits: 3 })} />,
+ ['1', '2'],
+ )
const input = document.querySelector('input[type="file"]') as HTMLInputElement
const file1 = new File(['content'], 'test1.jpg', { type: 'image/jpeg' })
@@ -90,29 +104,56 @@ describe('FileInput', () => {
await user.upload(input, [file1, file2])
- // Only 1 file should be uploaded (2 existing + 1 = 3 = limit)
- expect(mockHandleLocalFileUpload).toHaveBeenCalledTimes(1)
- expect(mockHandleLocalFileUpload).toHaveBeenCalledWith(file1)
+ await waitFor(() => expect(store.getState().files).toHaveLength(3))
+ expect(store.getState().files).toEqual([
+ createUploadedFile('1'),
+ createUploadedFile('2'),
+ expect.objectContaining({
+ name: 'test1.jpg',
+ uploadedId: 'uploaded-test1.jpg',
+ progress: 100,
+ originalFile: file1,
+ }),
+ ])
+ expect(input).toBeDisabled()
+ expect(fileUpload).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ file: file1 }),
+ false,
+ undefined,
+ )
})
it('should upload first file only when number_limits is not set', async () => {
const user = userEvent.setup()
- renderWithProvider(<FileInput fileConfig={createFileConfig({ number_limits: undefined })} />)
+ const { store } = renderWithProvider(
+ <FileInput fileConfig={createFileConfig({ number_limits: undefined })} />,
+ )
const input = document.querySelector('input[type="file"]') as HTMLInputElement
const file = new File(['content'], 'test.jpg', { type: 'image/jpeg' })
await user.upload(input, [file, new File(['other'], 'other.jpg', { type: 'image/jpeg' })])
- expect(mockHandleLocalFileUpload).toHaveBeenCalledWith(file)
+ await waitFor(() =>
+ expect(store.getState().files).toEqual([
+ expect.objectContaining({
+ name: 'test.jpg',
+ uploadedId: 'uploaded-test.jpg',
+ progress: 100,
+ }),
+ ]),
+ )
})
it('should not upload an empty selection without a configured limit', () => {
- renderWithProvider(<FileInput fileConfig={createFileConfig({ number_limits: undefined })} />)
+ const { store } = renderWithProvider(
+ <FileInput fileConfig={createFileConfig({ number_limits: undefined })} />,
+ )
const input = document.querySelector('input[type="file"]') as HTMLInputElement
fireEvent.change(input, { target: { files: [] } })
- expect(mockHandleLocalFileUpload).not.toHaveBeenCalled()
+ expect(fileUpload).not.toHaveBeenCalled()
+ expect(store.getState().files).toEqual([])
})
it('should handle empty allowed_file_types', () => {
@@ -128,7 +169,7 @@ describe('FileInput', () => {
renderWithProvider(
<FileInput
fileConfig={createFileConfig({
- allowed_file_types: ['custom'] as unknown as FileUpload['allowed_file_types'],
+ allowed_file_types: ['custom'],
allowed_file_extensions: undefined,
})}
/>,
@@ -138,13 +179,25 @@ describe('FileInput', () => {
expect(input.accept).toBe('')
})
- it('allows selecting the same file again after canceling or retrying an upload', async () => {
+ it('allows selecting the same file again', async () => {
const user = userEvent.setup()
- const { container } = renderWithProvider(<FileInput fileConfig={createFileConfig()} />)
+ const { container, store } = renderWithProvider(<FileInput fileConfig={createFileConfig()} />)
const input = container.querySelector<HTMLInputElement>('input[type="file"]')!
const file = new File(['content'], 'test.jpg', { type: 'image/jpeg' })
await user.upload(input, file)
await user.upload(input, file)
- expect(mockHandleLocalFileUpload.mock.calls).toEqual([[file], [file]])
+ await waitFor(() => expect(store.getState().files).toHaveLength(2))
+ expect(store.getState().files).toEqual([
+ expect.objectContaining({
+ originalFile: file,
+ uploadedId: 'uploaded-test.jpg',
+ progress: 100,
+ }),
+ expect.objectContaining({
+ originalFile: file,
+ uploadedId: 'uploaded-test.jpg',
+ progress: 100,
+ }),
+ ])
})
})
diff --git a/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsx b/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsx
index 8e494ccdf13..d357d811795 100644
--- a/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/hit-testing/components/query-input/__tests__/index.spec.tsx
@@ -1,45 +1,72 @@
import type { DatasetQueryContentResponse } from '@dify/contracts/api/console/datasets/types.gen'
-import type { FileEntity } from '@/app/components/datasets/common/image-uploader/types'
+import type { ComponentProps, ReactElement } from 'react'
import type { RetrievalConfig } from '@/types/app'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { fileUpload } from '@/app/components/base/file-uploader/utils'
+import DatasetDetailContext from '@/context/dataset-detail'
import { expectLoadingButton } from '@/test/button'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
+import { createDatasetFixture } from '@/test/fixtures/dataset'
+import { mockFixtureImageFetch } from '@/test/image-fetch'
import { RETRIEVE_METHOD } from '@/types/app'
import QueryInput from '../index'
-// Capture onChange callback so tests can trigger handleImageChange
-let capturedOnChange: ((files: FileEntity[]) => void) | null = null
-vi.mock(
- '@/app/components/datasets/common/image-uploader/image-uploader-in-retrieval-testing',
- () => ({
- default: ({
- textArea,
- actionButton,
- onChange,
- }: {
- textArea: React.ReactNode
- actionButton: React.ReactNode
- onChange?: (files: FileEntity[]) => void
- }) => {
- capturedOnChange = onChange ?? null
- return (
- <div data-testid="image-uploader">
- {textArea}
- {actionButton}
- </div>
- )
- },
- }),
-)
-
-vi.mock('@/app/components/datasets/common/retrieval-method-info', () => ({
- getIcon: () => '/test-icon.png',
+vi.mock('@/app/components/base/file-uploader/utils', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/app/components/base/file-uploader/utils')>()),
+ fileUpload: 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, {
+ 'files.upload.get': async () => ({
+ image_file_batch_limit: 10,
+ single_chunk_attachment_limit: 20,
+ attachment_image_file_size_limit: 15,
+ }),
+ }),
+ }
+})
-vi.mock('@/context/dataset-detail', () => ({
- useDatasetDetailContextWithSelector: () => false,
-}))
+const imageUrl = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
+const dataset = createDatasetFixture({ is_multimodal: true })
+function render(ui: ReactElement) {
+ const wrap = (view: ReactElement) => (
+ <DatasetDetailContext.Provider value={{ dataset }}>{view}</DatasetDetailContext.Provider>
+ )
+ const view = renderWithConsoleQuery(wrap(ui))
+ return { ...view, rerender: (next: ReactElement) => view.rerender(wrap(next)) }
+}
+
+function ControlledQuery(props: ComponentProps<typeof QueryInput>) {
+ const [queries, setQueries] = useState(props.queries)
+ return <QueryInput {...props} queries={queries} setQueries={setQueries} />
+}
+function uploadResponse(file: File) {
+ return {
+ id: 'uploaded-1',
+ name: file.name,
+ size: file.size,
+ mime_type: file.type,
+ extension: 'gif',
+ created_at: 0,
+ created_by: 'user-1',
+ preview_url: null,
+ source_url: '',
+ }
+}
+function imageFile() {
+ return new File(
+ [Uint8Array.from(atob(imageUrl.split(',')[1]!), (c) => c.charCodeAt(0))],
+ 'pic.gif',
+ { type: 'image/gif' },
+ )
+}
describe('QueryInput', () => {
// Re-create per test to avoid cross-test mutation (handleTextChange mutates query objects)
@@ -73,7 +100,10 @@ describe('QueryInput', () => {
beforeEach(() => {
vi.clearAllMocks()
defaultProps = makeDefaultProps()
- capturedOnChange = null
+ mockFixtureImageFetch()
+ vi.mocked(fileUpload).mockImplementation(({ file, onSuccessCallback }) =>
+ onSuccessCallback(uploadResponse(file)),
+ )
})
it('labels the query input and focuses it when its visible label is clicked', async () => {
@@ -192,29 +222,25 @@ describe('QueryInput', () => {
})
describe('Text Change Handling', () => {
- it('should update existing text query on text change', () => {
- render(<QueryInput {...defaultProps} />)
-
- const textarea = screen.getByRole('textbox', { name: 'datasetHitTesting.input.title' })
- fireEvent.change(textarea, { target: { value: 'updated text' } })
-
- expect(defaultProps.setQueries).toHaveBeenCalledWith(
- expect.arrayContaining([
- expect.objectContaining({ content: 'updated text', content_type: 'text_query' }),
- ]),
- )
- })
-
- it('should create new text query when none exists', () => {
- render(<QueryInput {...defaultProps} queries={[]} />)
-
+ it.each([
+ {
+ queries: [
+ { content: 'test query', content_type: 'text_query', file_info: null },
+ ] satisfies DatasetQueryContentResponse[],
+ next: 'updated text',
+ },
+ { queries: [], next: 'new text' },
+ ])('saves $next in the live query and submitted request', async ({ queries, next }) => {
+ const user = userEvent.setup()
+ render(<ControlledQuery {...defaultProps} queries={queries} />)
const textarea = screen.getByRole('textbox', { name: 'datasetHitTesting.input.title' })
- fireEvent.change(textarea, { target: { value: 'new text' } })
-
- expect(defaultProps.setQueries).toHaveBeenCalledWith(
- expect.arrayContaining([
- expect.objectContaining({ content: 'new text', content_type: 'text_query' }),
- ]),
+ await user.clear(textarea)
+ await user.type(textarea, next)
+ expect(textarea).toHaveValue(next)
+ await user.click(screen.getByRole('button', { name: /input\.testing/ }))
+ expect(defaultProps.hitTestingMutation).toHaveBeenCalledWith(
+ expect.objectContaining({ query: next }),
+ expect.anything(),
)
})
})
@@ -256,91 +282,52 @@ describe('QueryInput', () => {
)
describe('Image Change Handling', () => {
- it('should update queries when images change', () => {
- render(<QueryInput {...defaultProps} />)
-
- const files: FileEntity[] = [
- {
- id: 'f-1',
- name: 'pic.jpg',
- size: 2048,
- mimeType: 'image/jpeg',
- extension: 'jpg',
- sourceUrl: 'https://img.example.com/pic.jpg',
- uploadedId: 'uploaded-1',
- progress: 100,
- },
- ]
-
- capturedOnChange!(files)
-
- expect(defaultProps.setQueries).toHaveBeenCalledWith(
- expect.arrayContaining([
- expect.objectContaining({ content_type: 'text_query' }),
- expect.objectContaining({
- content: 'https://img.example.com/pic.jpg',
- content_type: 'image_query',
- file_info: expect.objectContaining({ id: 'uploaded-1', name: 'pic.jpg' }),
- }),
- ]),
+ it('uploads an image and submits its saved identifier alongside the existing text', async () => {
+ const user = userEvent.setup()
+ const { container } = render(<ControlledQuery {...defaultProps} />)
+ const file = imageFile()
+ await user.upload(container.querySelector<HTMLInputElement>('input[type="file"]')!, file)
+ expect(await screen.findByRole('img', { name: 'Preview' })).toBeVisible()
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /input\.testing/ })).toBeEnabled(),
)
- })
-
- it('should handle files with missing sourceUrl and uploadedId', () => {
- render(<QueryInput {...defaultProps} />)
-
- const files: FileEntity[] = [
- {
- id: 'f-2',
- name: 'no-url.jpg',
- size: 512,
- mimeType: 'image/jpeg',
- extension: 'jpg',
- progress: 100,
- // sourceUrl and uploadedId are undefined
- },
- ]
-
- capturedOnChange!(files)
-
- expect(defaultProps.setQueries).toHaveBeenCalledWith(
- expect.arrayContaining([
- expect.objectContaining({
- content: '',
- content_type: 'image_query',
- file_info: expect.objectContaining({ id: '', source_url: '' }),
- }),
- ]),
+ await user.click(screen.getByRole('button', { name: /input\.testing/ }))
+ expect(fileUpload).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ file }))
+ expect(defaultProps.hitTestingMutation).toHaveBeenCalledWith(
+ expect.objectContaining({ query: 'test query', attachment_ids: ['uploaded-1'] }),
+ expect.anything(),
)
})
- it('should replace all existing image queries with new ones', () => {
+ it('removes an existing image without losing the text query', async () => {
+ const user = userEvent.setup()
const queries: DatasetQueryContentResponse[] = [
{ content: 'text', content_type: 'text_query', file_info: null },
{
- content: 'old-img',
+ content: imageUrl,
content_type: 'image_query',
file_info: {
id: 'old',
- name: 'old.png',
+ name: 'old.gif',
size: 100,
- mime_type: 'image/png',
- extension: 'png',
- source_url: '',
+ mime_type: 'image/gif',
+ extension: 'gif',
+ source_url: imageUrl,
},
},
]
- render(<QueryInput {...defaultProps} queries={queries} />)
-
- capturedOnChange!([])
-
- // Should keep text query but remove all image queries
- expect(defaultProps.setQueries).toHaveBeenCalledWith(
- expect.arrayContaining([expect.objectContaining({ content_type: 'text_query' })]),
+ render(<ControlledQuery {...defaultProps} queries={queries} />)
+ expect(await screen.findByRole('img', { name: 'Preview' })).toBeVisible()
+ await user.click(screen.getByRole('button', { name: 'common.operation.remove' }))
+ expect(screen.queryByRole('img', { name: 'Preview' })).not.toBeInTheDocument()
+ expect(screen.getByRole('textbox', { name: 'datasetHitTesting.input.title' })).toHaveValue(
+ 'text',
+ )
+ await user.click(screen.getByRole('button', { name: /input\.testing/ }))
+ expect(defaultProps.hitTestingMutation).toHaveBeenCalledWith(
+ expect.objectContaining({ query: 'text', attachment_ids: [] }),
+ expect.anything(),
)
- // Should not contain image_query
- const calledWith = defaultProps.setQueries.mock.calls[0]![0] as DatasetQueryContentResponse[]
- expect(calledWith.filter((q) => q.content_type === 'image_query')).toHaveLength(0)
})
})
@@ -440,7 +427,7 @@ describe('QueryInput', () => {
const queries: DatasetQueryContentResponse[] = [
{ content: 'test', content_type: 'text_query', file_info: null },
{
- content: 'img-url',
+ content: imageUrl,
content_type: 'image_query',
file_info: {
id: 'img-id',
@@ -448,7 +435,7 @@ describe('QueryInput', () => {
size: 100,
mime_type: 'image/png',
extension: 'png',
- source_url: 'img-url',
+ source_url: imageUrl,
},
},
]
diff --git a/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx b/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx
index b85cc07c65c..18c687488cb 100644
--- a/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx
+++ b/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx
@@ -3,20 +3,24 @@ import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { expectLoadingButton } from '@/test/button'
-import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { renderWithConfigurationModals as render } from '@/test/configuration-modals'
import { createDeferred } from '@/test/deferred'
+import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'
import Action from '../action'
const requests = vi.hoisted(() => ({
uninstall: vi.fn(),
releases: vi.fn(),
- updateModal: vi.fn(),
+ uploadGitHub: vi.fn(),
+ updateFromGitHub: vi.fn(),
invalidate: vi.fn(),
notify: vi.fn(),
}))
vi.mock('@/service/plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/plugins')>()),
uninstallPlugin: requests.uninstall,
+ uploadGitHub: requests.uploadGitHub,
+ updateFromGitHub: requests.updateFromGitHub,
}))
vi.mock('../../install-plugin/hooks', async (importOriginal) => ({
...(await importOriginal<typeof import('../../install-plugin/hooks')>()),
@@ -26,10 +30,20 @@ vi.mock('@/app/notifications', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/app/notifications')>()
return { ...actual, toast: Object.assign(requests.notify, actual.toast) }
})
-// The shared modal host and catalog invalidation are separate owners.
-vi.mock('@/context/modal-context', () => ({
- useModalContext: () => ({ setShowUpdatePluginModal: requests.updateModal }),
+// Catalog refresh is an independent installer contract; the real host, release picker and installer stay mounted.
+vi.mock('../../install-plugin/hooks/use-refresh-plugin-list', () => ({
+ default: () => ({ refreshPluginList: 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, {
+ 'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
+ }),
+ }
+})
vi.mock('@/service/use-plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/use-plugins')>()),
useInvalidateInstalledPluginList: () => requests.invalidate,
@@ -158,32 +172,61 @@ describe('installed plugin actions', () => {
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
- it('opens the update host with the existing identifier and fetched releases, then refreshes on save', async () => {
+ it('updates the chosen release through the real modal and refreshes after saving', async () => {
const user = userEvent.setup()
- const releases = [{ tag_name: '2.0.0', assets: [] }]
- requests.releases.mockResolvedValue(releases)
- render(<Action {...createActionProps({ isShowFetchNewVersion: true })} />)
- await user.click(updateButton())
- await waitFor(() => expect(requests.updateModal).toHaveBeenCalledOnce())
- expect(requests.releases).toHaveBeenCalledExactlyOnceWith('test-author', 'test-plugin')
- expect(requests.updateModal).toHaveBeenCalledWith({
- onSaveCallback: expect.any(Function),
- payload: {
- category: 'tool',
- github: {
- originalPackageInfo: {
- id: 'test-author/[email protected]',
- repo: 'test-author/test-plugin',
- version: '1.0.0',
- package: 'test-plugin.difypkg',
- releases,
+ requests.releases.mockResolvedValue([
+ {
+ tag_name: '2.0.0',
+ assets: [
+ {
+ id: 2,
+ name: 'test-plugin.difypkg',
+ browser_download_url:
+ 'https://github.com/test-author/test-plugin/releases/download/2.0.0/test-plugin.difypkg',
},
- },
+ ],
},
+ { tag_name: '1.0.0', assets: [] },
+ ])
+ requests.uploadGitHub.mockResolvedValue({
+ unique_identifier: 'test-author/[email protected]',
+ manifest: createPluginDeclarationFixture({ version: '2.0.0' }),
})
+ const pending = createDeferred<{ all_installed: boolean; task_id: string }>()
+ requests.updateFromGitHub.mockReturnValueOnce(pending.promise)
+ render(<Action {...createActionProps({ isShowFetchNewVersion: true })} />)
+ await user.click(updateButton())
+ expect(
+ await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.updatePlugin' }),
+ ).toBeVisible()
+ expect(requests.releases).toHaveBeenCalledExactlyOnceWith('test-author', 'test-plugin')
expect(requests.notify).toHaveBeenCalledWith('New version available: 2.0.0', { type: 'info' })
+ await user.click(
+ screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' }),
+ )
+ expect(await screen.findByRole('option', { name: /1\.0\.0.*INSTALLED/ })).toBeVisible()
+ await user.click(screen.getByRole('option', { name: '2.0.0' }))
+ await user.click(
+ screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectPackage' }),
+ )
+ await user.click(await screen.findByRole('option', { name: 'test-plugin.difypkg' }))
+ await user.click(screen.getByRole('button', { name: 'plugin.installModal.next' }))
+ await user.click(await screen.findByRole('button', { name: 'plugin.installModal.install' }))
+ expect(requests.uploadGitHub).toHaveBeenCalledExactlyOnceWith(
+ 'test-author/test-plugin',
+ '2.0.0',
+ 'test-plugin.difypkg',
+ )
+ expect(requests.updateFromGitHub).toHaveBeenCalledExactlyOnceWith(
+ 'test-author/test-plugin',
+ '2.0.0',
+ 'test-plugin.difypkg',
+ 'test-author/[email protected]',
+ 'test-author/[email protected]',
+ )
expect(requests.invalidate).not.toHaveBeenCalled()
- requests.updateModal.mock.calls[0]![0].onSaveCallback()
+ pending.resolve({ all_installed: true, task_id: '' })
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(requests.invalidate).toHaveBeenCalledExactlyOnceWith('tool')
})
@@ -203,7 +246,7 @@ describe('installed plugin actions', () => {
expect(requests.notify).toHaveBeenCalledWith('No new version available', { type: 'info' }),
)
expect(requests.releases).toHaveBeenCalledExactlyOnceWith('test-author', 'test-plugin')
- expect(requests.updateModal).not.toHaveBeenCalled()
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
it('does not open an update when the repository has no releases', async () => {
@@ -212,6 +255,6 @@ describe('installed plugin actions', () => {
await user.click(updateButton())
await waitFor(() => expect(requests.releases).toHaveBeenCalledOnce())
expect(requests.notify).not.toHaveBeenCalled()
- expect(requests.updateModal).not.toHaveBeenCalled()
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
})