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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
test(web): exercise avatar marketplace and agent tools owners (#44835)
Stephen Zhou6a90e6310ade
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsxindex 2d6216034ff..6c1500f3215 100644--- a/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx+++ b/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx@@ -1,21 +1,13 @@-import type { ImageIconInputProps } from '@/app/components/base/icon-picker/image-input'-import type { ImageFile } from '@/types/app'import { QueryClientProvider } from '@tanstack/react-query'-import { act, render, screen, waitFor } from '@testing-library/react'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { imageUpload } from '@/app/components/base/image-uploader/utils'import { createTestQueryClient } from '@/test/query-client'-import { TransferMethod } from '@/types/app'import { createCroppedAvatarImage } from '../avatar-image'import AvatarWithEdit from '../AvatarWithEdit'-type LocalFileUploaderOptions = {- onUpload: (imageFile: ImageFile) => void-}-const mocks = vi.hoisted(() => ({- animatedFile: new File(['animated'], 'avatar.gif', { type: 'image/gif' }),- handleLocalFileUpload: vi.fn<(file: File) => void>(),- onUpload: null as ((imageFile: ImageFile) => void) | null,+ imageUpload: vi.fn(),request: vi.fn(),}))@@ -24,58 +16,31 @@ vi.mock('@/config', () => ({DISABLE_UPLOAD_IMAGE_AS_ICON: false,}))-vi.mock('@/service/base', () => ({- request: mocks.request,+vi.mock('@/next/navigation', () => ({+ useParams: () => ({}),}))-vi.mock('@/app/components/base/icon-picker/image-input', () => ({- ImageIconInput: ({ onChange }: ImageIconInputProps) => (- <div>- <button- type="button"- onClick={() =>- onChange?.({- type: 'crop',- url: 'blob:static-avatar',- area: { x: 10, y: 20, width: 1000, height: 1000 },- fileName: 'avatar.png',- })- }- >- Select static avatar- </button>- <button type="button" onClick={() => onChange?.({ type: 'file', file: mocks.animatedFile })}>- Select animated avatar- </button>- </div>- ),+vi.mock('@/service/base', () => ({+ request: mocks.request,}))-vi.mock('@/app/components/base/image-uploader/hooks', () => ({- useLocalFileUploader: (options: LocalFileUploaderOptions) => {- mocks.onUpload = options.onUpload- return { handleLocalFileUpload: mocks.handleLocalFileUpload }- },+vi.mock('@/app/components/base/image-uploader/utils', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/app/components/base/image-uploader/utils')>()),+ imageUpload: mocks.imageUpload,}))vi.mock('../avatar-image', async (importOriginal) => {const actual = await importOriginal<typeof import('../avatar-image')>()return {...actual,+ // avatar-image.spec.ts independently verifies bitmap cropping and output size bounds.createCroppedAvatarImage: vi.fn(),}})+const mockedImageUpload = vi.mocked(imageUpload)const mockedCreateCroppedAvatarImage = vi.mocked(createCroppedAvatarImage)-const createImageFile = (fileId = 'uploaded-avatar-id'): ImageFile => ({- type: TransferMethod.local_file,- _id: 'test-image-id',- fileId,- progress: 100,- url: 'https://example.com/avatar.png',-})-const createAccountResponse = (avatar = '') => ({id: 'user-id',name: 'Alice',@@ -94,67 +59,107 @@ const renderAvatar = (avatar: string | null = null) => {)}+const expectProfilePatch = async (avatar: string) => {+ await waitFor(() => expect(mocks.request).toHaveBeenCalled())+ expect(mocks.request.mock.calls[0]?.[0]).toEqual(expect.stringContaining('/account/profile'))+ const request = mocks.request.mock.calls[0]?.[2]?.request as Request+ expect(request.method).toBe('PATCH')+ await expect(request.json()).resolves.toEqual({ avatar })+}+describe('AvatarWithEdit', () => {beforeEach(() => {- vi.clearAllMocks()- mocks.onUpload = null- mocks.handleLocalFileUpload.mockReset()- mockedCreateCroppedAvatarImage.mockReset()- mocks.request.mockImplementation(+ mocks.imageUpload.mockReset()+ mocks.request.mockReset().mockImplementation(async () =>new Response(JSON.stringify(createAccountResponse('uploaded-avatar-id')), {headers: { 'content-type': 'application/json' },}),)+ mockedCreateCroppedAvatarImage.mockReset()+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:avatar-preview')+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})})+ afterEach(() => vi.restoreAllMocks())+it('uploads the bounded crop for a static avatar', async () => {const user = userEvent.setup()- const blob = new Blob(['bounded-avatar'], { type: 'image/png' })- mockedCreateCroppedAvatarImage.mockResolvedValue(blob)+ const croppedBlob = new Blob(['bounded-avatar'], { type: 'image/png' })+ const selectedFile = new File(['static-avatar'], 'avatar.png', { type: 'image/png' })+ mockedCreateCroppedAvatarImage.mockResolvedValue(croppedBlob)renderAvatar()await user.click(screen.getByRole('button', { name: /avatar\.editAction/i }))- await user.click(screen.getByRole('button', { name: 'Select static avatar' }))+ const dialog = screen.getByRole('dialog', { name: /avatar\.editAction/i })+ const originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (+ this: HTMLElement,+ ) {+ return dialog.contains(this)+ ? new DOMRect(0, 0, 320, 320)+ : originalGetBoundingClientRect.call(this)+ })+ await user.upload(screen.getByTestId('image-input'), selectedFile)+ await screen.findByRole('group', { name: /iconPicker\.crop/i })+ // The library image has no accessible name; select it only to supply native load/geometry.+ const cropperImage = dialog.querySelector('img')+ if (!cropperImage) throw new Error('Expected the real cropper image')+ Object.defineProperties(cropperImage, {+ naturalWidth: { value: 1200, configurable: true },+ naturalHeight: { value: 600, configurable: true },+ width: { value: 320, configurable: true },+ height: { value: 160, configurable: true },+ offsetWidth: { value: 320, configurable: true },+ offsetHeight: { value: 160, configurable: true },+ })+ vi.spyOn(cropperImage, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 80, 320, 160))+ fireEvent.load(cropperImage)await user.click(screen.getByRole('button', { name: /iconPicker\.ok/i }))- await waitFor(() => {- expect(mockedCreateCroppedAvatarImage).toHaveBeenCalledWith(- 'blob:static-avatar',- { x: 10, y: 20, width: 1000, height: 1000 },- 'avatar.png',- )- expect(mocks.handleLocalFileUpload).toHaveBeenCalledWith(- expect.objectContaining({ name: 'avatar.png', type: 'image/png' }),- )- })+ await waitFor(() => expect(mockedCreateCroppedAvatarImage).toHaveBeenCalled())+ expect(mockedCreateCroppedAvatarImage).toHaveBeenCalledWith(+ 'blob:avatar-preview',+ { x: 300, y: 0, width: 600, height: 600 },+ 'avatar.png',+ )+ await waitFor(() => expect(mockedImageUpload).toHaveBeenCalledOnce())+ expect(mockedImageUpload.mock.calls[0]![0].file).toEqual(+ expect.objectContaining({ name: 'avatar.png', type: 'image/png' }),+ )+ expect(+ Array.from(new Uint8Array(await mockedImageUpload.mock.calls[0]![0].file.arrayBuffer())),+ ).toEqual(Array.from(new Uint8Array(await croppedBlob.arrayBuffer())))+ act(() => mockedImageUpload.mock.calls[0]![0].onSuccessCallback({ id: 'cropped-avatar-id' }))++ await expectProfilePatch('cropped-avatar-id')+ await waitFor(() => expect(dialog).not.toBeInTheDocument())})it('updates an animated avatar through the account profile endpoint', async () => {const user = userEvent.setup()- const uploadedAvatar = createImageFile()- mocks.handleLocalFileUpload.mockImplementation(() => mocks.onUpload?.(uploadedAvatar))+ const animatedFile = new File(['GIF89a'], 'avatar.gif', { type: 'image/gif' })renderAvatar()await user.click(screen.getByRole('button', { name: /avatar\.editAction/i }))- await user.click(screen.getByRole('button', { name: 'Select animated avatar' }))+ const dialog = screen.getByRole('dialog', { name: /avatar\.editAction/i })+ await user.upload(screen.getByTestId('image-input'), animatedFile)+ expect(await screen.findByRole('img', { name: /iconPicker\.image/i })).toBeInTheDocument()await user.click(screen.getByRole('button', { name: /iconPicker\.ok/i }))expect(mockedCreateCroppedAvatarImage).not.toHaveBeenCalled()- expect(mocks.handleLocalFileUpload).toHaveBeenCalledWith(mocks.animatedFile)- await waitFor(() => {- expect(mocks.request).toHaveBeenCalled()- })- expect(mocks.request.mock.calls[0]?.[0]).toEqual(expect.stringContaining('/account/profile'))- const request = mocks.request.mock.calls[0]?.[2]?.request as Request- expect(request.method).toBe('PATCH')- await expect(request.json()).resolves.toEqual({ avatar: uploadedAvatar.fileId })+ await waitFor(() => expect(mockedImageUpload).toHaveBeenCalledOnce())+ expect(mockedImageUpload.mock.calls[0]![0].file).toBe(animatedFile)+ act(() => mockedImageUpload.mock.calls[0]![0].onSuccessCallback({ id: 'animated-avatar-id' }))++ await expectProfilePatch('animated-avatar-id')+ await waitFor(() => expect(dialog).not.toBeInTheDocument())})it('clears a saved avatar even after its image fails to load', async () => {const images: HTMLImageElement[] = []const NativeImage = window.Image- const imageLoader = vi.spyOn(window, 'Image').mockImplementation(+ vi.spyOn(window, 'Image').mockImplementation(class extends NativeImage {constructor() {super()@@ -165,21 +170,16 @@ describe('AvatarWithEdit', () => {const user = userEvent.setup()renderAvatar('https://example.com/broken.png')await waitFor(() => expect(images.length).toBeGreaterThan(0))- await act(async () => {+ act(() => {for (const image of images) image.dispatchEvent(new Event('error'))})- imageLoader.mockRestore()await user.click(screen.getByRole('button', { name: /avatar\.editAction/i }))await user.click(screen.getByRole('button', { name: /operation\.delete/i }))- await user.click(await screen.findByRole('button', { name: /operation\.delete/i }))+ const confirmDialog = await screen.findByRole('dialog', { name: /avatar\.deleteTitle/i })+ await user.click(screen.getByRole('button', { name: /operation\.delete/i }))- await waitFor(() => {- expect(mocks.request).toHaveBeenCalled()- })- expect(mocks.request.mock.calls[0]?.[0]).toEqual(expect.stringContaining('/account/profile'))- const request = mocks.request.mock.calls[0]?.[2]?.request as Request- expect(request.method).toBe('PATCH')- await expect(request.json()).resolves.toEqual({ avatar: '' })+ await expectProfilePatch('')+ await waitFor(() => expect(confirmDialog).not.toBeInTheDocument())})})diff --git a/web/app/components/plugins/marketplace/list/__tests__/list-wrapper.spec.tsx b/web/app/components/plugins/marketplace/list/__tests__/list-wrapper.spec.tsxindex 389e80ba765..74b668a7d5b 100644--- a/web/app/components/plugins/marketplace/list/__tests__/list-wrapper.spec.tsx+++ b/web/app/components/plugins/marketplace/list/__tests__/list-wrapper.spec.tsx@@ -1,162 +1,251 @@-import type { MarketplaceCollection } from '@dify/contracts/marketplace'import type { ReactNode } from 'react'-import type { Plugin } from '@/app/components/plugins/types'-import { render, screen } from '@testing-library/react'+import type { marketplaceClient } from '@/service/marketplace'+import { QueryClientProvider } from '@tanstack/react-query'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { Provider as JotaiProvider } from 'jotai'+import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'import { createNuqsTestWrapper } from '@/test/nuqs-testing'+import { createTestQueryClient } from '@/test/query-client'+import { useSearchPluginText } from '../../atoms'import ListWrapper from '../list-wrapper'-const mockMarketplaceData = vi.hoisted(() => ({- plugins: undefined as Plugin[] | undefined,- pluginsTotal: 0,- marketplaceCollections: [] as MarketplaceCollection[],- marketplaceCollectionPluginsMap: {} as Record<string, Plugin[]>,- isLoading: false,- isRefreshing: false,- isError: false,- refetch: vi.fn(),- isFetchingNextPage: false,- page: 1,+const transport = vi.hoisted(() => ({+ collections: vi.fn<typeof marketplaceClient.collections>(),+ collectionPlugins: vi.fn<typeof marketplaceClient.collectionPlugins>(),+ searchAdvanced: vi.fn<typeof marketplaceClient.searchAdvanced>(),}))-vi.mock('#i18n', async () => {+vi.mock('@/service/marketplace', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/marketplace')>()+ return {+ ...actual,+ marketplaceClient: {+ ...actual.marketplaceClient,+ collections: transport.collections,+ collectionPlugins: transport.collectionPlugins,+ searchAdvanced: transport.searchAdvanced,+ },+ }+})++vi.mock('#i18n', async (importOriginal) => {+ const actual = await importOriginal<typeof import('#i18n')>()const { withSelectorKey } = await import('@/test/i18n-mock')return {+ ...actual,useTranslation: () => ({t: withSelectorKey((key: string, options?: Record<string, unknown>) => {+ const translations: Record<string, string> = {+ 'marketplace.loadError': 'Could not load plugins',+ 'marketplace.sortBy': 'Sort by',+ 'marketplace.sortOption.mostPopular': 'Most Popular',+ 'marketplace.sortOption.recentlyUpdated': 'Recently Updated',+ 'marketplace.sortOption.newlyReleased': 'Newly Released',+ 'marketplace.sortOption.firstReleased': 'First Released',+ }if (key === 'marketplace.pluginsResult') return `${options?.num} plugins found`- return key+ return translations[key] || key}),}),}})-vi.mock('../../sort-menu', () => ({- default: () => <div data-testid="sort-menu">sort</div>,-}))+const plugin = (name: string, label: string) =>+ createMarketplacePluginFixture({+ name,+ plugin_id: `dify/${name}`,+ label: { en_US: label },+ brief: { en_US: `${label} description` },+ })-vi.mock('../index', () => ({- default: ({ plugins }: { plugins?: Plugin[] }) => (- <div data-testid="list">{plugins?.length ?? 'collections'}</div>- ),-}))+const searchResponse = (plugins: ReturnType<typeof plugin>[], total = plugins.length) => ({+ data: { plugins, total },+})-vi.mock('../../state', () => ({- useMarketplaceData: () => mockMarketplaceData,-}))+const deferred = <T,>() => {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise+ })+ return { promise, resolve }+}-// ListWrapper reads the raw `q` through nuqs for its analytics flush, so the-// tree needs an adapter even though the data hook itself is mocked.-const renderListWrapper = (ui: ReactNode) => {- const { wrapper: NuqsWrapper } = createNuqsTestWrapper({ searchParams: '' })- return render(ui, { wrapper: NuqsWrapper })+function SearchControl() {+ const [query, setQuery] = useSearchPluginText()+ return (+ <input+ aria-label="Marketplace query"+ value={query}+ onChange={(event) => void setQuery(event.target.value)}+ />+ )+}++const renderListWrapper = ({+ children,+ searchParams = '?category=model',+}: { children?: ReactNode; searchParams?: string } = {}) => {+ const queryClient = createTestQueryClient()+ const { wrapper: NuqsWrapper, onUrlUpdate } = createNuqsTestWrapper({+ searchParams,+ hasMemory: true,+ })+ const rendered = render(+ <JotaiProvider>+ <QueryClientProvider client={queryClient}>+ <NuqsWrapper>+ {children}+ <div id="marketplace-container">+ <ListWrapper linkToMarketplaceDetail />+ </div>+ </NuqsWrapper>+ </QueryClientProvider>+ </JotaiProvider>,+ )+ return { ...rendered, onUrlUpdate }}describe('ListWrapper', () => {beforeEach(() => {- vi.clearAllMocks()- mockMarketplaceData.plugins = undefined- mockMarketplaceData.pluginsTotal = 0- mockMarketplaceData.marketplaceCollections = []- mockMarketplaceData.marketplaceCollectionPluginsMap = {}- mockMarketplaceData.isLoading = false- mockMarketplaceData.isRefreshing = false- mockMarketplaceData.isError = false- mockMarketplaceData.isFetchingNextPage = false- mockMarketplaceData.page = 1+ transport.collections.mockReset().mockResolvedValue({ data: { collections: [] } })+ transport.collectionPlugins.mockReset().mockResolvedValue({ data: { plugins: [] } })+ transport.searchAdvanced.mockReset()+ })++ afterEach(() => {+ vi.useRealTimers()+ vi.unstubAllGlobals()})- it('shows result header and sort dropdown when plugins are loaded', () => {- mockMarketplaceData.plugins = [{ plugin_id: 'p1', name: 'Plugin One' } as Plugin]- mockMarketplaceData.pluginsTotal = 1+ it('shows real result cards and the sort dropdown when plugins are loaded', async () => {+ transport.searchAdvanced.mockResolvedValue(searchResponse([plugin('plugin-one', 'Plugin One')]))- renderListWrapper(<ListWrapper />)+ renderListWrapper()+ expect(await screen.findByRole('link', { name: /Plugin One/ })).toBeInTheDocument()expect(screen.getByRole('status')).toHaveTextContent('1 plugins found')- expect(screen.getByTestId('sort-menu')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Sort by Most Popular' })).toBeInTheDocument()})- it('keeps the status owner mounted through pagination and reports the total result count', () => {- mockMarketplaceData.plugins = [{ plugin_id: 'p1', name: 'Plugin One' } as Plugin]- mockMarketplaceData.pluginsTotal = 20- const view = renderListWrapper(<ListWrapper />)+ it('keeps the status and loaded cards visible while fetching the next page', async () => {+ const nextPage = deferred<ReturnType<typeof searchResponse>>()+ const firstPage = Array.from({ length: 40 }, (_, index) =>+ plugin(`plugin-${index}`, `Plugin ${index}`),+ )+ transport.searchAdvanced.mockImplementation(({ body }) =>+ body.page === 1 ? Promise.resolve(searchResponse(firstPage, 41)) : nextPage.promise,+ )+ renderListWrapper()+ const firstCard = await screen.findByRole('link', { name: /Plugin 0/ })const status = screen.getByRole('status')- expect(status).toHaveTextContent('20 plugins found')-- mockMarketplaceData.isFetchingNextPage = true- view.rerender(<ListWrapper />)+ expect(status).toHaveTextContent('41 plugins found')++ const container = document.getElementById('marketplace-container')!+ Object.defineProperties(container, {+ scrollTop: { value: 800, configurable: true },+ scrollHeight: { value: 1000, configurable: true },+ clientHeight: { value: 200, configurable: true },+ })+ fireEvent.scroll(container)++ await waitFor(() => {+ expect(screen.getByRole('progressbar')).toBeVisible()+ expect(status.textContent).toMatch(/loading/i)+ })+ expect(firstCard).toBeInTheDocument()expect(screen.getByRole('status')).toBe(status)- expect(status).toHaveTextContent('loading')- expect(screen.getByRole('progressbar')).toBeInTheDocument()- mockMarketplaceData.isFetchingNextPage = false- mockMarketplaceData.plugins = [- ...mockMarketplaceData.plugins,- { plugin_id: 'p2', name: 'Plugin Two' } as Plugin,- ]- view.rerender(<ListWrapper />)+ await act(async () => {+ nextPage.resolve(searchResponse([plugin('plugin-40', 'Plugin 40')], 41))+ })++ expect(await screen.findByRole('link', { name: /Plugin 40/ })).toBeInTheDocument()+ expect(screen.getByRole('link', { name: /Plugin 0/ })).toBeInTheDocument()expect(screen.getByRole('status')).toBe(status)- expect(status).toHaveTextContent('20 plugins found')+ expect(status).toHaveTextContent('41 plugins found')expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()-- mockMarketplaceData.isRefreshing = true- view.rerender(<ListWrapper />)- expect(status).toHaveTextContent('loading')- mockMarketplaceData.isRefreshing = false- mockMarketplaceData.isError = true- view.rerender(<ListWrapper />)- expect(status).toHaveTextContent('marketplace.loadError')})it('shows centered loading on a cold start', () => {- mockMarketplaceData.isLoading = true- mockMarketplaceData.page = 1+ transport.searchAdvanced.mockReturnValue(new Promise(() => {}))- renderListWrapper(<ListWrapper />)+ renderListWrapper()expect(screen.getByRole('progressbar')).toBeInTheDocument()+ expect(screen.queryByRole('link')).not.toBeInTheDocument()+ expect(screen.getByRole('status').textContent).toMatch(/loading/i)})- // The reported "jitter": every debounced keystroke used to unmount the grid- // behind a centre-absolute spinner, collapsing the container height and- // jumping the scroll position.- it('keeps the result grid mounted while a superseded query is in flight', () => {- mockMarketplaceData.plugins = [{ plugin_id: 'p1', name: 'Plugin One' } as Plugin]- mockMarketplaceData.pluginsTotal = 1- mockMarketplaceData.isRefreshing = true-- renderListWrapper(<ListWrapper />)-- const list = screen.getByTestId('list')- expect(list).toBeInTheDocument()- expect(list.parentElement).toHaveAttribute('aria-busy', 'true')- expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()- })-- it('renders list when loading additional pages', () => {- mockMarketplaceData.isLoading = true- mockMarketplaceData.page = 2- mockMarketplaceData.plugins = [{ plugin_id: 'p1', name: 'Plugin One' } as Plugin]-- renderListWrapper(<ListWrapper showInstallButton />)-- expect(screen.getByTestId('list')).toBeInTheDocument()+ it('keeps stale results visible while a debounced replacement query is pending', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })+ // RTL recognizes this bridge when draining userEvent's zero-delay async wrapper.+ vi.stubGlobal('jest', { advanceTimersByTime: vi.advanceTimersByTime })+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })+ const replacement = deferred<ReturnType<typeof searchResponse>>()+ transport.searchAdvanced.mockImplementation(({ body }) => {+ if (body.query === 'first')+ return Promise.resolve(searchResponse([plugin('first-plugin', 'First Plugin')]))+ return replacement.promise+ })++ const { onUrlUpdate } = renderListWrapper({+ children: <SearchControl />,+ searchParams: '?category=all&q=first',+ })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0)+ })+ expect(screen.getByRole('link', { name: /First Plugin/ })).toBeInTheDocument()++ const input = screen.getByRole('textbox', { name: 'Marketplace query' })+ await user.clear(input)+ await user.type(input, 'second')+ // Flush Nuqs' zero-delay URL update before starting the production debounce clock.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(0)+ })+ expect(onUrlUpdate).toHaveBeenLastCalledWith(+ expect.objectContaining({ searchParams: new URLSearchParams('category=all&q=second') }),+ )++ expect(screen.getByRole('link', { name: /First Plugin/ })).toBeInTheDocument()+ expect(screen.getByRole('status').textContent).toMatch(/loading/i)+ expect(+ transport.searchAdvanced.mock.calls.some(([request]) => request.body.query === 'second'),+ ).toBe(false)++ await act(async () => {+ await vi.advanceTimersByTimeAsync(500)+ })+ expect(+ transport.searchAdvanced.mock.calls.some(([request]) => request.body.query === 'second'),+ ).toBe(true)+ expect(screen.getByRole('link', { name: /First Plugin/ })).toBeInTheDocument()++ await act(async () => {+ replacement.resolve(searchResponse([plugin('second-plugin', 'Second Plugin')]))+ await vi.advanceTimersByTimeAsync(0)+ })+ expect(screen.getByRole('link', { name: /Second Plugin/ })).toBeInTheDocument()+ expect(screen.queryByRole('link', { name: /First Plugin/ })).not.toBeInTheDocument()+ expect(screen.getByRole('status')).toHaveTextContent('1 plugins found')})- // A failed search used to arrive as a successful empty page and render as- // "no plugins found", with nothing to retry.- it('offers a retry when the search failed with nothing to show', async () => {+ it('offers a retry and renders the recovered result after a failed search', async () => {const user = userEvent.setup()- mockMarketplaceData.isError = true- mockMarketplaceData.plugins = []+ transport.searchAdvanced+ .mockRejectedValueOnce(new Error('Marketplace unavailable'))+ .mockResolvedValueOnce(searchResponse([plugin('recovered-plugin', 'Recovered Plugin')]))- renderListWrapper(<ListWrapper />)+ renderListWrapper()- expect(screen.queryByTestId('list')).not.toBeInTheDocument()- expect(screen.getByRole('status')).toHaveTextContent('marketplace.loadError')+ const status = screen.getByRole('status')+ await waitFor(() => expect(status).toHaveTextContent('Could not load plugins'))+ expect(screen.queryByRole('link')).not.toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: /operation\.retry/i }))- await user.click(screen.getByRole('button', { name: 'operation.retry' }))- expect(mockMarketplaceData.refetch).toHaveBeenCalledTimes(1)+ expect(await screen.findByRole('link', { name: /Recovered Plugin/ })).toBeInTheDocument()+ expect(screen.getByRole('status')).toHaveTextContent('1 plugins found')})})diff --git a/web/app/components/plugins/marketplace/sort-menu/__tests__/index.spec.tsx b/web/app/components/plugins/marketplace/sort-menu/__tests__/index.spec.tsxindex adef922325f..7fa099ac260 100644--- a/web/app/components/plugins/marketplace/sort-menu/__tests__/index.spec.tsx+++ b/web/app/components/plugins/marketplace/sort-menu/__tests__/index.spec.tsx@@ -1,5 +1,7 @@import { render, screen, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { Provider as JotaiProvider } from 'jotai'+import { useMarketplaceSort } from '../../atoms'import SortMenu from '../index'const mockTranslation = vi.hoisted(() =>@@ -25,49 +27,47 @@ vi.mock('#i18n', async () => {}})-let mockSort: { sortBy: string; sortOrder: string } = { sortBy: 'install_count', sortOrder: 'DESC' }-const mockHandleSortChange = vi.fn()--vi.mock('../../atoms', () => ({- useMarketplaceSort: () => [mockSort, mockHandleSortChange],-}))+function SortStateSubscriber() {+ const [sort] = useMarketplaceSort()+ return (+ <output aria-label="Selected marketplace sort">{`${sort.sortBy}-${sort.sortOrder}`}</output>+ )+}describe('SortMenu', () => {- beforeEach(() => {- vi.clearAllMocks()- mockSort = { sortBy: 'install_count', sortOrder: 'DESC' }- })-- it('falls back to the default option when the current sort is invalid', () => {- mockSort = { sortBy: 'unknown', sortOrder: 'ASC' }-- render(<SortMenu />)-- expect(screen.getByText('Most Popular')).toBeInTheDocument()- })-- it('updates the sort and closes the menu when an option is selected', async () => {+ it('updates the shared sort state and preserves the selection when reopened', async () => {const user = userEvent.setup()- render(<SortMenu />)+ render(+ <JotaiProvider>+ <SortMenu />+ <SortStateSubscriber />+ </JotaiProvider>,+ )- await user.click(screen.getByRole('button', { name: 'Sort by Most Popular' }))+ const trigger = screen.getByRole('button', { name: 'Sort by Most Popular' })+ await user.click(trigger)const menu = within(await screen.findByRole('menu'))expect(menu.getByRole('menuitemradio', { name: 'Most Popular' })).toHaveAttribute('aria-checked','true',)- expect(menu.getByRole('menuitemradio', { name: 'Recently Updated' })).toHaveAttribute(- 'aria-checked',- 'false',- )- expect(menu.getByRole('menuitemradio', { name: 'Newly Released' })).toBeInTheDocument()- expect(menu.getByRole('menuitemradio', { name: 'First Released' })).toBeInTheDocument()await user.click(menu.getByRole('menuitemradio', { name: 'Recently Updated' }))- expect(mockHandleSortChange).toHaveBeenCalledWith({- sortBy: 'version_updated_at',- sortOrder: 'DESC',- })expect(screen.queryByRole('menu')).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Sort by Recently Updated' })).toBeInTheDocument()+ expect(screen.getByRole('status', { name: 'Selected marketplace sort' })).toHaveTextContent(+ 'version_updated_at-DESC',+ )++ await user.click(screen.getByRole('button', { name: 'Sort by Recently Updated' }))+ const reopenedMenu = within(await screen.findByRole('menu'))+ expect(reopenedMenu.getByRole('menuitemradio', { name: 'Recently Updated' })).toHaveAttribute(+ 'aria-checked',+ 'true',+ )+ expect(reopenedMenu.getByRole('menuitemradio', { name: 'Most Popular' })).toHaveAttribute(+ 'aria-checked',+ 'false',+ )})})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsxindex a94e7759415..a5e8d2ab0fa 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx@@ -1,153 +1,48 @@import type { ToolProviderApiEntityResponse } from '@dify/contracts/api/console/workspaces/types.gen'-import type { AddOAuthButtonProps, Credential } from '@/app/components/plugins/plugin-auth/types'+import type { Credential } from '@/app/components/plugins/plugin-auth/types'import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'import { QueryClient } from '@tanstack/react-query'-import { act, render, screen, waitFor } from '@testing-library/react'+import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { createStore, Provider as JotaiProvider } from 'jotai'-import { queryClientAtom } from 'jotai-tanstack-query'-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { useAtomValue } from 'jotai'import { CredentialTypeEnum } from '@/app/components/plugins/plugin-auth/types'import { CollectionType } from '@/app/components/tools/types'import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'import {agentComposerDraftAtom,- agentComposerSavedDraftAtom,isAgentComposerDirtyAtom,} from '@/features/agent-v2/agent-composer/store'import { consoleQuery } from '@/service/console'import { seedAccountProfileQuery } from '@/test/console/account-profile'+import { seedSystemFeatures } from '@/test/console/query-data'import { QueryClientTestProvider } from '@/test/console/query-provider'import { seedToolProviders } from '@/test/console/tool-providers'import { seedWorkspacePermissionsQuery } from '@/test/console/workspace-permissions'+import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'import {AgentOrchestrateReadOnlyContext,AgentOrchestrateViewingVersionContext,} from '../../read-only-context'-import { AgentTemplateTools, AgentTools } from '../index'+import { AgentTools } from '../index'const toolProviderState = vi.hoisted(() => ({builtInTools: [] as ToolProviderApiEntityResponse[] | undefined,customTools: [] as ToolProviderApiEntityResponse[] | undefined,}))-const pluginAuthState = vi.hoisted(() => ({- canOAuth: true as boolean | undefined,- canApiKey: false as boolean | undefined,- credentials: [] as Credential[],- notAllowCustomCredential: false,- invalidPluginCredentialInfo: vi.fn(),-}))-const pluginInstallState = vi.hoisted(() => ({- manifest: undefined as- | {- label: Record<string, string>- latest_package_identifier: string- }- | undefined,- fallbackManifest: undefined as- | {- latest_package_identifier: string- }- | undefined,- invalidateInstalledPluginList: vi.fn(),- installPackage: vi.fn(),-}))--vi.mock('@/app/components/workflow/block-selector/tool-picker', () => ({- ToolPickerContent: () => <div>Mock tool picker</div>,-}))--vi.mock('@/app/components/workflow/block-icon', () => ({- default: ({ toolIcon }: { toolIcon?: string | { content: string; background: string } }) => (- <span aria-hidden data-testid="tool-icon">- {typeof toolIcon === 'string' ? toolIcon : toolIcon?.content}- </span>- ),-}))--vi.mock('@/service/use-plugins', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/service/use-plugins')>()),- useInvalidateInstalledPluginList: () => pluginInstallState.invalidateInstalledPluginList,- useFetchPluginsInMarketPlaceByInfo: (infos: Array<{ organization: string; plugin: string }>) => ({- data:- infos.length > 0 && pluginInstallState.manifest- ? {- data: {- list: infos.map(({ organization, plugin }) => ({- plugin: {- ...pluginInstallState.manifest,- name: plugin,- plugin_id: `${organization}/${plugin}`,- },- })),- },- }- : undefined,- }),- usePluginManifestInfo: (pluginId: string) => ({- data:- pluginId && pluginInstallState.fallbackManifest- ? {- data: {- plugin: pluginInstallState.fallbackManifest,- },- }- : undefined,- }),-}))--vi.mock('@/utils/get-icon', () => ({- getIconFromMarketPlace: (pluginId: string) => `https://marketplace.example.com/${pluginId}/icon`,-}))-vi.mock('@/app/components/plugins/plugin-auth/authorize/add-oauth-button', () => ({- default: ({ buttonText, onUpdate, renderTrigger }: AddOAuthButtonProps) => {- const trigger = (- <button type="button" onClick={onUpdate}>- {buttonText}- </button>- )-- if (renderTrigger) {- return renderTrigger({- isConfigured: false,- onClick: () => onUpdate?.(),- trigger,- })- }-- return trigger- },-}))--vi.mock('@/app/components/plugins/plugin-auth/hooks/use-plugin-auth', () => ({- usePluginAuth: () => ({- ...pluginAuthState,- isAuthorized: pluginAuthState.credentials.length > 0,- }),-}))--vi.mock('@/hooks/use-credential-permissions', () => ({- useCredentialPermissions: () => ({- canUseCredential: true,- canCreateCredential: true,- canManageCredential: true,- }),+const service = vi.hoisted(() => ({+ credentialInfo: vi.fn(),+ getMarketplace: vi.fn(),+ installPackage: vi.fn(),+ postMarketplace: vi.fn(),}))-vi.mock('@/app/components/header/account-setting/model-provider-page/model-modal/Form', () => ({- default: ({- formSchemas,- }: {- formSchemas: Array<{ label?: Record<string, string>; variable?: string }>- }) => (- <form aria-label="tool settings">- {formSchemas.map((schema) => (- <div key={schema.variable}>{schema.label?.en_US}</div>- ))}- </form>- ),+vi.mock('@/service/base', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/service/base')>()),+ get: service.credentialInfo,+ getMarketplace: service.getMarketplace,+ postMarketplace: service.postMarketplace,}))vi.mock('@/service/console', async (importOriginal) => {@@ -157,12 +52,21 @@ vi.mock('@/service/console', async (importOriginal) => {return {...actual,consoleClient: withConsoleClientResponses(actual.consoleClient, {- 'workspaces.current.plugin.install.marketplace.post': pluginInstallState.installPackage,+ 'workspaces.current.plugin.install.marketplace.post': service.installPackage,}),consoleQuery: withConsoleResponses(actual.consoleQuery, {'workspaces.current.plugin.list.installations.ids.post': async () => ({ plugins: [] }),- 'workspaces.current.tools.builtin.get': async () => toolProviderState.builtInTools,- 'workspaces.current.tools.api.get': async () => toolProviderState.customTools,+ 'workspaces.current.toolProvider.builtin.byProvider.oauth.clientSchema.get': async () => ({+ schema: [],+ is_oauth_custom_client_enabled: false,+ is_system_oauth_params_exists: true,+ client_params: {},+ redirect_uri: '',+ }),+ 'workspaces.current.tools.builtin.get': async () =>+ toolProviderState.builtInTools ?? new Promise<ToolProviderApiEntityResponse[]>(() => {}),+ 'workspaces.current.tools.api.get': async () =>+ toolProviderState.customTools ?? new Promise<ToolProviderApiEntityResponse[]>(() => {}),'workspaces.current.tools.workflow.get': async () => [],'workspaces.current.tools.mcp.get': async () => [],}),@@ -441,32 +345,39 @@ const authorizedSwaggerProvider = {],} satisfies ToolProviderApiEntityResponse-function renderAgentTools(initialDraft: AgentSoulConfigFormState = agentToolsDraft) {- const queryClient = new QueryClient({- defaultOptions: {- queries: {- retry: false,- },- },- })- seedAccountProfileQuery(queryClient, { id: 'user-1' })- seedWorkspacePermissionsQuery(queryClient, ['plugin.install'])- queryClient.setQueryDefaults(consoleQuery.workspaces.current.rbac.myPermissions.get.queryKey(), {- staleTime: Infinity,+const marketplaceGooglePlugin = (identifier: string) =>+ createMarketplacePluginFixture({+ org: 'langgenius',+ name: 'google',+ plugin_id: 'langgenius/google',+ label: { en_US: 'Google Tools' },+ latest_package_identifier: identifier,})- seedToolProviders(queryClient, toolProviderState)- const view = render(- <QueryClientTestProvider queryClient={queryClient}>- <AgentComposerProvider initialDraft={initialDraft}>- <AgentTools />- </AgentComposerProvider>- </QueryClientTestProvider>,+const credentialInfo = (credentials: Credential[] = []) => ({+ credentials,+ supported_credential_types: [CredentialTypeEnum.OAUTH2],+ allow_custom_token: true,+ is_oauth_custom_client_enabled: false,+})++type ComposerState = {+ dirty: boolean+ tools: AgentSoulConfigFormState['tools']+}++function ComposerStateSubscriber() {+ const draft = useAtomValue(agentComposerDraftAtom)+ const dirty = useAtomValue(isAgentComposerDirtyAtom)+ return (+ <output aria-label="Composer state">{JSON.stringify({ dirty, tools: draft.tools })}</output>)- return { ...view, queryClient }}-function renderAgentToolsWithStore(initialDraft: AgentSoulConfigFormState = agentToolsDraft) {+const readComposerState = (): ComposerState =>+ JSON.parse(screen.getByRole('status', { name: 'Composer state' }).textContent || '{}')++const createAgentToolsQueryClient = () => {const queryClient = new QueryClient({defaultOptions: {queries: {@@ -475,59 +386,47 @@ function renderAgentToolsWithStore(initialDraft: AgentSoulConfigFormState = agen},})seedAccountProfileQuery(queryClient, { id: 'user-1' })- seedWorkspacePermissionsQuery(queryClient, ['plugin.install'])+ seedWorkspacePermissionsQuery(queryClient, [+ 'plugin.install',+ 'credential.use',+ 'credential.create',+ 'credential.manage',+ ])+ seedSystemFeatures(queryClient, { enable_marketplace: false })queryClient.setQueryDefaults(consoleQuery.workspaces.current.rbac.myPermissions.get.queryKey(), {staleTime: Infinity,})seedToolProviders(queryClient, toolProviderState)- const store = createStore()- store.set(queryClientAtom, queryClient)- store.set(agentComposerDraftAtom, initialDraft)- store.set(agentComposerSavedDraftAtom, initialDraft)+ return queryClient+}- const view = render(+function renderAgentTools(initialDraft: AgentSoulConfigFormState = agentToolsDraft) {+ const queryClient = createAgentToolsQueryClient()+ return render(<QueryClientTestProvider queryClient={queryClient}>- <JotaiProvider store={store}>+ <AgentComposerProvider initialDraft={initialDraft}><AgentTools />- </JotaiProvider>+ <ComposerStateSubscriber />+ </AgentComposerProvider></QueryClientTestProvider>,)-- return {- ...view,- store,- }}function renderReadonlyAgentTools({initialDraft = agentToolsDraft,- template = false,viewingVersion = false,}: {initialDraft?: AgentSoulConfigFormState- template?: booleanviewingVersion?: boolean} = {}) {- const queryClient = new QueryClient({- defaultOptions: {- queries: {- retry: false,- },- },- })- seedAccountProfileQuery(queryClient, { id: 'user-1' })- seedWorkspacePermissionsQuery(queryClient, ['plugin.install'])- queryClient.setQueryDefaults(consoleQuery.workspaces.current.rbac.myPermissions.get.queryKey(), {- staleTime: Infinity,- })- seedToolProviders(queryClient, toolProviderState)+ const queryClient = createAgentToolsQueryClient()return render(<QueryClientTestProvider queryClient={queryClient}><AgentComposerProvider initialDraft={initialDraft}><AgentOrchestrateViewingVersionContext value={viewingVersion}><AgentOrchestrateReadOnlyContext value>- {template ? <AgentTemplateTools /> : <AgentTools />}+ <AgentTools /></AgentOrchestrateReadOnlyContext></AgentOrchestrateViewingVersionContext></AgentComposerProvider>@@ -536,20 +435,37 @@ function renderReadonlyAgentTools({}describe('AgentTools', () => {+ let batchMarketplacePlugin: ReturnType<typeof marketplaceGooglePlugin> | undefined+ let fallbackMarketplacePlugin: ReturnType<typeof marketplaceGooglePlugin> | undefined+beforeEach(() => {- vi.clearAllMocks()toolProviderState.builtInTools = []toolProviderState.customTools = []- pluginAuthState.canOAuth = true- pluginAuthState.canApiKey = false- pluginAuthState.credentials = []- pluginAuthState.notAllowCustomCredential = false- pluginInstallState.installPackage- .mockReset()- .mockResolvedValue({ all_installed: true, task_id: '' })- pluginInstallState.manifest = undefined- pluginInstallState.fallbackManifest = undefined- pluginInstallState.invalidateInstalledPluginList.mockResolvedValue(undefined)+ batchMarketplacePlugin = undefined+ fallbackMarketplacePlugin = undefined+ service.credentialInfo.mockReset().mockResolvedValue(credentialInfo())+ service.installPackage.mockReset().mockResolvedValue({ all_installed: true, task_id: '' })+ service.postMarketplace.mockReset().mockImplementation(async (path: string) => {+ if (path === '/plugins/versions/batch') {+ return {+ data: {+ list: batchMarketplacePlugin ? [{ plugin: batchMarketplacePlugin }] : [],+ },+ }+ }+ throw new Error(`Unexpected marketplace POST: ${path}`)+ })+ service.getMarketplace.mockReset().mockImplementation(async (path: string) => {+ if (path === '/plugins/langgenius/google' && fallbackMarketplacePlugin) {+ return {+ data: {+ plugin: fallbackMarketplacePlugin,+ version: { version: fallbackMarketplacePlugin.version },+ },+ }+ }+ throw new Error(`Unexpected marketplace GET: ${path}`)+ })})describe('User Interactions', () => {@@ -557,12 +473,7 @@ describe('AgentTools', () => {const user = userEvent.setup()renderAgentTools()- await user.click(- screen.getByRole('button', {- name: 'DuckDuckGo',- }),- )-+ await user.click(screen.getByRole('button', { name: 'DuckDuckGo' }))await user.click(screen.getByRole('button', {name: 'agentV2.agentDetail.configure.tools.removeAction:{"name":"DuckDuckGo Image Search"}',@@ -571,7 +482,9 @@ describe('AgentTools', () => {expect(screen.queryByText('DuckDuckGo Image Search')).not.toBeInTheDocument()expect(screen.getByText('DuckDuckGo Search')).toBeInTheDocument()- expect(screen.getByText('DuckDuckGo')).toBeInTheDocument()+ expect(readComposerState().tools[0]).toMatchObject({+ actions: [{ id: 'duckduckgo-search' }],+ })})it('should remove all provider tools from the provider more-actions menu', async () => {@@ -590,11 +503,12 @@ describe('AgentTools', () => {)expect(screen.queryByText('DuckDuckGo')).not.toBeInTheDocument()- expect(screen.queryByText('DuckDuckGo Search')).not.toBeInTheDocument()- expect(screen.queryByText('Lark CLI')).not.toBeInTheDocument()+ expect(readComposerState().tools).toEqual([+ expect.objectContaining({ id: 'lark-cli', kind: 'cli' }),+ ])})- it('should open the tool picker directly from the add trigger', async () => {+ it('should open the real tool picker directly from the add trigger', async () => {const user = userEvent.setup()renderAgentTools()@@ -604,7 +518,7 @@ describe('AgentTools', () => {}),)- expect(screen.getByText('Mock tool picker')).toBeInTheDocument()+ expect(await screen.findByRole('dialog')).toBeInTheDocument()expect(screen.queryByRole('button', {name: /agentV2\.agentDetail\.configure\.tools\.addMenu\.cliTool\.label/,@@ -615,11 +529,6 @@ describe('AgentTools', () => {name: /agentV2\.agentDetail\.configure\.tools\.addMenu\.tool\.label/,}),).not.toBeInTheDocument()- expect(- screen.getByRole('button', {- name: 'agentV2.agentDetail.configure.tools.add',- }),- ).toBeInTheDocument()})it('should hide add, edit, and remove actions when viewing a version', async () => {@@ -637,11 +546,7 @@ describe('AgentTools', () => {}),).not.toBeInTheDocument()- await user.click(- screen.getByRole('button', {- name: 'DuckDuckGo',- }),- )+ await user.click(screen.getByRole('button', { name: 'DuckDuckGo' }))expect(screen.queryByRole('button', {@@ -653,16 +558,6 @@ describe('AgentTools', () => {name: 'agentV2.agentDetail.configure.tools.removeAction:{"name":"DuckDuckGo Image Search"}',}),).not.toBeInTheDocument()- expect(- screen.queryByRole('button', {- name: 'agentV2.agentDetail.configure.tools.editAction:{"name":"Lark CLI"}',- }),- ).not.toBeInTheDocument()- expect(- screen.queryByRole('button', {- name: 'agentV2.agentDetail.configure.tools.removeAction:{"name":"Lark CLI"}',- }),- ).not.toBeInTheDocument()})it('should hide the add action while a build draft is read-only', () => {@@ -684,125 +579,68 @@ describe('AgentTools', () => {name: 'agentV2.agentDetail.configure.tools.editAction:{"name":"Lark CLI"}',}),).not.toBeInTheDocument()- expect(- screen.queryByRole('button', {- name: 'agentV2.agentDetail.configure.tools.removeAction:{"name":"Lark CLI"}',- }),- ).not.toBeInTheDocument()})})describe('Display Metadata', () => {- it('shows a template tool icon from its published provider reference without marketplace metadata', () => {- const draft = {- ...reflectedUninstalledPluginDraft,- tools: reflectedUninstalledPluginDraft.tools.map((tool) => ({- ...tool,- pluginId: undefined,- providerType: CollectionType.builtIn,- })),- } satisfies AgentSoulConfigFormState-- renderReadonlyAgentTools({ initialDraft: draft, template: true })-- expect(- screen.getByText('https://marketplace.example.com/langgenius/google/icon'),- ).toBeInTheDocument()- })-- it('should enrich reflected provider tools with provider icon and localized names', async () => {+ it('should enrich reflected provider tools with provider metadata and localized names', async () => {const user = userEvent.setup()- toolProviderState.builtInTools = [- {- ...googleProvider,- allow_delete: false,- },- ]+ toolProviderState.builtInTools = [{ ...googleProvider, allow_delete: false }]renderAgentTools(reflectedAgentToolsDraft)- expect(- screen.getByRole('button', {- name: 'Google Tools',- }),- ).toBeInTheDocument()- expect(screen.getByText('https://example.com/google.svg')).toBeInTheDocument()-- await user.click(- screen.getByRole('button', {- name: 'Google Tools',- }),- )+ await user.click(screen.getByRole('button', { name: 'Google Tools' }))expect(screen.getByText('Google Search')).toBeInTheDocument()})- it('should let users install a missing provider and show its marketplace icon', async () => {+ it('should install a missing provider through the marketplace and show the installed catalog', async () => {const user = userEvent.setup()- pluginInstallState.manifest = {- label: {- en_US: 'Google Tools',- },- latest_package_identifier: 'langgenius/google:1.0.0@checksum',- }- const { queryClient } = renderAgentTools(reflectedUninstalledPluginDraft)- const builtInToolsKey = consoleQuery.workspaces.current.tools.builtin.get.queryKey()- queryClient.setQueryData(builtInToolsKey, [])-- expect(screen.getByRole('button', { name: 'Google Tools' })).toBeInTheDocument()- expect(- screen.getByText('https://marketplace.example.com/langgenius/google/icon'),- ).toBeInTheDocument()- expect(- screen.queryByRole('button', {- name: 'tools.notAuthorized',- }),- ).not.toBeInTheDocument()+ batchMarketplacePlugin = marketplaceGooglePlugin('langgenius/google:1.0.0@checksum')+ renderAgentTools(reflectedUninstalledPluginDraft)+ expect(await screen.findByRole('button', { name: 'Google Tools' })).toBeInTheDocument()const installButton = await screen.findByRole('button', {name: 'workflowAgent.nodes.agent.pluginInstaller.install',})- const installedProvider = { ...googleProvider, id: 'langgenius/google/google' }- toolProviderState.builtInTools = [installedProvider]+ service.installPackage.mockImplementationOnce(async () => {+ toolProviderState.builtInTools = [{ ...googleProvider, id: 'langgenius/google/google' }]+ return { all_installed: true, task_id: '' }+ })await user.click(installButton)+await waitFor(() =>- expect(pluginInstallState.installPackage).toHaveBeenCalledExactlyOnceWith({+ expect(service.installPackage).toHaveBeenCalledExactlyOnceWith({body: { plugin_unique_identifiers: ['langgenius/google:1.0.0@checksum'] },}),)-- expect(await screen.findByText('https://example.com/google.svg')).toBeInTheDocument()- await waitFor(() => {- expect(queryClient.getQueryData(builtInToolsKey)).toEqual([installedProvider])- expect(pluginInstallState.invalidateInstalledPluginList).toHaveBeenCalledTimes(1)- })+ await waitFor(() => expect(installButton).not.toBeInTheDocument())+ await user.click(screen.getByRole('button', { name: 'Google Tools' }))+ expect(await screen.findByText('Google Search')).toBeInTheDocument()})- it('should install the fallback package when batch marketplace metadata is unavailable', async () => {+ it('should install the fallback manifest and show the installed catalog', async () => {const user = userEvent.setup()- pluginInstallState.fallbackManifest = {- latest_package_identifier: 'langgenius/google:0.0.1@fallback',- }+ fallbackMarketplacePlugin = marketplaceGooglePlugin('langgenius/google:0.0.1@fallback')renderAgentTools(reflectedUninstalledPluginDraft)- expect(- screen.getByRole('button', {- name: 'google',- }),- ).toBeInTheDocument()- expect(- screen.getByText('https://marketplace.example.com/langgenius/google/icon'),- ).toBeInTheDocument()- await user.click(- await screen.findByRole('button', {- name: 'workflowAgent.nodes.agent.pluginInstaller.install',- }),- )+ const installButton = await screen.findByRole('button', {+ name: 'workflowAgent.nodes.agent.pluginInstaller.install',+ })+ service.installPackage.mockImplementationOnce(async () => {+ toolProviderState.builtInTools = [{ ...googleProvider, id: 'langgenius/google/google' }]+ return { all_installed: true, task_id: '' }+ })+ await user.click(installButton)+await waitFor(() =>- expect(pluginInstallState.installPackage).toHaveBeenCalledExactlyOnceWith({+ expect(service.installPackage).toHaveBeenCalledExactlyOnceWith({body: { plugin_unique_identifiers: ['langgenius/google:0.0.1@fallback'] },}),)+ await waitFor(() => expect(installButton).not.toBeInTheDocument())+ await user.click(await screen.findByRole('button', { name: 'Google Tools' }))+ expect(await screen.findByText('Google Search')).toBeInTheDocument()})it('should wait for the provider catalog before showing an uninstalled status', () => {@@ -812,47 +650,31 @@ describe('AgentTools', () => {expect(screen.queryByText('plugin.detailPanel.toolSelector.uninstalledTitle'),).not.toBeInTheDocument()- expect(- screen.queryByRole('button', {- name: 'tools.notAuthorized',- }),- ).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'tools.notAuthorized' })).not.toBeInTheDocument()})it('should use current team authorization for reflected Swagger API tools', () => {toolProviderState.customTools = [authorizedSwaggerProvider]renderAgentTools(reflectedAuthorizedSwaggerDraft)- expect(- screen.getByRole('button', {- name: 'Weather API',- }),- ).toBeInTheDocument()- expect(- screen.queryByRole('button', {- name: 'tools.notAuthorized',- }),- ).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Weather API' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'tools.notAuthorized' })).not.toBeInTheDocument()})it('should keep provider credential metadata display-only without dirtying the composer draft', () => {toolProviderState.builtInTools = [duckDuckGoProvider]- const { store } = renderAgentToolsWithStore(reflectedUnauthorizedNoCredentialDraft)+ renderAgentTools(reflectedUnauthorizedNoCredentialDraft)- expect(- screen.getByRole('button', {- name: 'DuckDuckGo',- }),- ).toBeInTheDocument()- expect(screen.queryByText('tools.notAuthorized')).not.toBeInTheDocument()- expect(store.get(agentComposerDraftAtom).tools[0]).toMatchObject({+ expect(screen.getByRole('button', { name: 'DuckDuckGo' })).toBeInTheDocument()+ const composerState = readComposerState()+ expect(composerState.tools[0]).toMatchObject({credentialType: 'unauthorized',credentialVariant: 'unauthorized',})- expect(store.get(isAgentComposerDirtyAtom)).toBe(false)+ expect(composerState.dirty).toBe(false)})- it('should open authorization actions for reflected OAuth provider tools', async () => {+ it('should open real authorization actions for reflected OAuth provider tools', async () => {const user = userEvent.setup()toolProviderState.builtInTools = [{@@ -864,25 +686,12 @@ describe('AgentTools', () => {]renderAgentTools(reflectedUnauthorizedOAuthCredentialTypeDraft)- expect(- screen.getByRole('button', {- name: 'tools.notAuthorized',- }),- ).toBeInTheDocument()- expect(- screen.queryByRole('button', { name: 'plugin.auth.useOAuthAuth' }),- ).not.toBeInTheDocument()-- await user.click(screen.getByRole('button', { name: 'tools.notAuthorized' }))+ await user.click(await screen.findByRole('button', { name: 'tools.notAuthorized' }))- expect(- screen.getByRole('button', {- name: 'plugin.auth.useOAuthAuth',- }),- ).toBeInTheDocument()+ expect(await screen.findByRole('button', { name: 'plugin.auth.useOAuthAuth' })).toBeEnabled()})- it('should bind an existing credential selected from the unauthorized status', async () => {+ it('should bind an existing queried credential to the composer draft', async () => {const user = userEvent.setup()toolProviderState.builtInTools = [{@@ -892,82 +701,50 @@ describe('AgentTools', () => {team_credentials: {},},]- pluginAuthState.credentials = [- {- id: 'workspace-oauth',- name: 'Workspace OAuth',- provider: 'google',- credential_type: CredentialTypeEnum.OAUTH2,- is_default: true,- },- ]- const { store } = renderAgentToolsWithStore(reflectedUnauthorizedOAuthCredentialTypeDraft)-- await user.click(screen.getByRole('button', { name: 'tools.notAuthorized' }))-- expect(store.get(agentComposerDraftAtom).tools[0]).toMatchObject({- credentialType: 'unauthorized',- credentialVariant: 'none',- })-- await user.click(screen.getByText('Workspace OAuth'))-- expect(store.get(agentComposerDraftAtom).tools[0]).toMatchObject({- credentialId: 'workspace-oauth',- credentialType: 'oauth2',- credentialVariant: 'authorized',+ service.credentialInfo.mockImplementation(async (url: string) => {+ if (+ new URL(url, 'http://localhost').pathname !==+ '/workspaces/current/tool-provider/builtin/google/credential/info'+ )+ throw new Error(`Unexpected credential GET: ${url}`)+ return credentialInfo([+ {+ id: 'workspace-oauth',+ name: 'Workspace OAuth',+ provider: 'google',+ credential_type: CredentialTypeEnum.OAUTH2,+ is_default: true,+ },+ ])})- })+ renderAgentTools(reflectedUnauthorizedOAuthCredentialTypeDraft)- it('should open provider tool settings with catalog icon and parameters', async () => {- const user = userEvent.setup()- toolProviderState.builtInTools = [duckDuckGoProvider]- renderAgentTools()+ await user.click(await screen.findByRole('button', { name: 'tools.notAuthorized' }))+ await user.click(await screen.findByText('Workspace OAuth'))- await user.click(- screen.getByRole('button', {- name: 'DuckDuckGo',- }),- )- await user.click(- screen.getByRole('button', {- name: 'agentV2.agentDetail.configure.tools.editAction:{"name":"DuckDuckGo Search"}',+ await waitFor(() =>+ expect(readComposerState().tools[0]).toMatchObject({+ credentialId: 'workspace-oauth',+ credentialType: 'oauth2',+ credentialVariant: 'authorized',}),)-- expect(screen.getByTestId('tool-icon')).toHaveTextContent(- 'https://example.com/duckduckgo.svg',- )- expect(screen.getByRole('form', { name: 'tool settings' })).toBeInTheDocument()- expect(screen.getByText('Search Query')).toBeInTheDocument()})- it('should close provider tool settings when the configured action leaves the draft', async () => {+ it('should open provider tool settings with the catalog parameter field', async () => {const user = userEvent.setup()toolProviderState.builtInTools = [duckDuckGoProvider]- const { store } = renderAgentToolsWithStore(agentToolsDraft)+ renderAgentTools()- await user.click(- screen.getByRole('button', {- name: 'DuckDuckGo',- }),- )+ await user.click(screen.getByRole('button', { name: 'DuckDuckGo' }))await user.click(screen.getByRole('button', {name: 'agentV2.agentDetail.configure.tools.editAction:{"name":"DuckDuckGo Search"}',}),)- expect(screen.getByRole('form', { name: 'tool settings' })).toBeInTheDocument()-- act(() => {- store.set(agentComposerDraftAtom, {- ...agentToolsDraft,- tools: [],- })- })-- expect(screen.queryByRole('form', { name: 'tool settings' })).not.toBeInTheDocument()+ expect(await screen.findByRole('textbox', { name: 'Search Query' })).toBeInTheDocument()+ expect(screen.getByText('Search the web with DuckDuckGo.')).toBeInTheDocument()})})})