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
refactor(plugins): migrate readme queries to generated contracts (#42725)
yyh8253405c0bba
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 013ce466cf0..0247d6beee9 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -4768,7 +4768,7 @@},"web/service/use-plugins.ts": {"@tanstack/query/prefer-query-options": {- "count": 13+ "count": 11},"dify/require-disable-directive-description": {"count": 1diff --git a/web/app/components/base/markdown-blocks/__tests__/paragraph.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/paragraph.spec.tsxindex a49d3461237..bce32c90840 100644--- a/web/app/components/base/markdown-blocks/__tests__/paragraph.spec.tsx+++ b/web/app/components/base/markdown-blocks/__tests__/paragraph.spec.tsx@@ -1,3 +1,5 @@+import type { ReactNode } from 'react'+import type { ExtraProps } from 'streamdown'import { render, screen } from '@testing-library/react'import { describe, expect, it, vi } from 'vite-plus/test'import Paragraph from '../paragraph'@@ -8,125 +10,91 @@ vi.mock('@/app/components/base/image-gallery', () => ({),}))-type MockChildNode = {- tagName?: string- properties?: { src?: string }- children?: MockChildNode[]-}--type MockNode = {- children?: MockChildNode[]-}--type ParagraphProps = {- node: MockNode- children?: React.ReactNode-}--const renderParagraph = (props: ParagraphProps) => {- return render(<Paragraph {...props} />)+const renderParagraph = (+ nodeChildren: NonNullable<ExtraProps['node']>['children'],+ children: ReactNode,+) => {+ const node: NonNullable<ExtraProps['node']> = {+ type: 'element',+ tagName: 'p',+ properties: {},+ children: nodeChildren,+ }+ return render(<Paragraph node={node}>{children}</Paragraph>)}describe('Paragraph', () => {- it('should render normal paragraph when no image child exists', () => {- renderParagraph({- node: { children: [] },- children: 'Hello world',- })+ it('renders a normal paragraph for text and comment nodes', () => {+ renderParagraph(+ [+ { type: 'comment', value: 'A comment' },+ { type: 'text', value: 'Hello world' },+ ],+ 'Hello world',+ )expect(screen.getByText('Hello world').tagName).toBe('P')})- it('should render image gallery when first child is img', () => {- renderParagraph({- node: {- children: [- {- tagName: 'img',- properties: { src: 'test.png' },- },- ],- },- children: ['Image only'],- })+ it('renders the image gallery when the first child is an image', () => {+ renderParagraph(+ [{ type: 'element', tagName: 'img', properties: { src: 'test.png' }, children: [] }],+ ['Image only'],+ )- expect(screen.getByTestId('image-gallery')).toBeInTheDocument()expect(screen.getByTestId('image-gallery')).toHaveTextContent('test.png')})- it('should render additional content after image when children length > 1', () => {- renderParagraph({- node: {- children: [- {- tagName: 'img',- properties: { src: 'test.png' },- },- ],- },- children: ['Image', <span key="1">Caption</span>],- })+ it('preserves additional content after the leading image', () => {+ renderParagraph(+ [{ type: 'element', tagName: 'img', properties: { src: 'test.png' }, children: [] }],+ ['Image', <span key="caption">Caption</span>],+ )- expect(screen.getByTestId('image-gallery')).toBeInTheDocument()+ expect(screen.getByTestId('image-gallery')).toHaveTextContent('test.png')expect(screen.getByText('Caption')).toBeInTheDocument()})- it('should render paragraph when first child exists but is not img', () => {- renderParagraph({- node: {- children: [- {- tagName: 'div',- },- ],- },- children: 'Not image',- })+ it('renders a paragraph when its element children contain no image', () => {+ renderParagraph(+ [{ type: 'element', tagName: 'span', properties: {}, children: [] }],+ 'Not image',+ )expect(screen.getByText('Not image').tagName).toBe('P')})- it('should render paragraph when children_node is undefined', () => {- renderParagraph({- node: {},- children: 'Fallback',- })-- expect(screen.getByText('Fallback').tagName).toBe('P')- })-- it('should render div instead of p when image is not the first child', () => {- renderParagraph({- node: {- children: [{ tagName: 'span' }, { tagName: 'img', properties: { src: 'test.png' } }],- },- children: [<span key="0">Text before</span>, <img key="1" src="test.png" alt="" />],- })-- const wrapper = screen.getByText('Text before').closest('.markdown-p')- expect(wrapper).toBeInTheDocument()- expect(wrapper!.tagName).toBe('DIV')+ it('uses a block wrapper when an image follows text', () => {+ renderParagraph(+ [+ { type: 'text', value: 'Text before' },+ { type: 'element', tagName: 'img', properties: { src: 'test.png' }, children: [] },+ ],+ [<span key="text">Text before</span>, <img key="image" src="test.png" alt="Diagram" />],+ )++ expect(screen.getByText('Text before').parentElement?.tagName).toBe('DIV')+ expect(screen.getByRole('img', { name: 'Diagram' })).toHaveAttribute('src', 'test.png')})- it('should render div when image is nested inside a link', () => {- renderParagraph({- node: {- children: [- {- tagName: 'a',- children: [{ tagName: 'img', properties: { src: 'nested.png' } }],- },- ],- },- children: (- <a href="#">- <img src="nested.png" alt="" />- </a>- ),- })-- const wrapper = screen.getByRole('link').closest('.markdown-p')- expect(wrapper).toBeInTheDocument()- expect(wrapper!.tagName).toBe('DIV')+ it('uses a block wrapper for an image nested inside a link', () => {+ renderParagraph(+ [+ {+ type: 'element',+ tagName: 'a',+ properties: { href: '#' },+ children: [+ { type: 'element', tagName: 'img', properties: { src: 'nested.png' }, children: [] },+ ],+ },+ ],+ <a href="#">+ <img src="nested.png" alt="Linked diagram" />+ </a>,+ )++ expect(screen.getByRole('link').parentElement?.tagName).toBe('DIV')+ expect(screen.getByRole('img', { name: 'Linked diagram' })).toHaveAttribute('src', 'nested.png')})})diff --git a/web/app/components/base/markdown-blocks/__tests__/plugin-assets.browser.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/plugin-assets.browser.spec.tsxnew file mode 100644index 00000000000..4387f3deee8--- /dev/null+++ b/web/app/components/base/markdown-blocks/__tests__/plugin-assets.browser.spec.tsx@@ -0,0 +1,136 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render } from 'vitest-browser-react'+import { PluginImg } from '../plugin-img'++const { request } = vi.hoisted(() => ({ request: vi.fn<() => Promise<Response>>() }))+vi.mock('@/service/base', () => ({ request }))+// Keep the unrelated marketplace image fallback local; all asset bytes still go+// through the generated Console client and the browser's real image decoder.+vi.mock('@/config', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/config')>()),+ MARKETPLACE_API_PREFIX:+ 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7#',+}))++async function pngResponse(width: number, height: number) {+ const canvas = document.createElement('canvas')+ canvas.width = width+ canvas.height = height+ const context = canvas.getContext('2d')+ if (!context) throw new Error('Canvas context unavailable')+ context.fillStyle = 'red'+ context.fillRect(0, 0, width, height)+ const blob = await new Promise<Blob>((resolve, reject) =>+ canvas.toBlob((value) => {+ if (value) resolve(value)+ else reject(new Error('PNG encoding failed'))+ }, 'image/png'),+ )+ return new Response(await blob.arrayBuffer(), {+ headers: { 'content-type': 'application/octet-stream' },+ })+}++// happy-dom cannot decode an octet-stream asset, or establish that a revoked+// object URL is unusable. These are the additional browser regression contracts.+it('decodes binary assets and retires object URLs on source replacement and unmount', async () => {+ request.mockReset()+ request.mockImplementation(() => pngResponse(2, 3))+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: 300_000 } },+ })+ const revoke = vi.spyOn(URL, 'revokeObjectURL')+ const pluginInfo = { pluginUniqueIdentifier: 'org/plugin:1@hash', pluginId: 'org/plugin' }+ const view = (src: string) => (+ <QueryClientProvider client={queryClient}>+ <PluginImg pluginInfo={pluginInfo} src={src} />+ </QueryClientProvider>+ )+ const screen = await render(view('_assets/first.png'))+ try {+ await expect+ .poll(() => screen.getByTestId('gallery-image').element().getAttribute('src'))+ .toMatch(/^blob:/)+ const firstImage = screen.getByTestId('gallery-image').element()+ if (!(firstImage instanceof HTMLImageElement)) throw new TypeError('Expected an image')+ await firstImage.decode()+ expect([firstImage.naturalWidth, firstImage.naturalHeight]).toEqual([2, 3])+ const firstUrl = firstImage.src+ expect(revoke).not.toHaveBeenCalled()+ request.mockImplementation(() => pngResponse(4, 5))+ await screen.rerender(view('_assets/second.png'))+ await expect+ .poll(() => screen.getByTestId('gallery-image').element().getAttribute('src'))+ .not.toBe(firstUrl)+ await expect+ .poll(() => screen.getByTestId('gallery-image').element().getAttribute('src'))+ .toMatch(/^blob:/)+ const secondImage = screen.getByTestId('gallery-image').element()+ if (!(secondImage instanceof HTMLImageElement)) throw new TypeError('Expected an image')+ await secondImage.decode()+ expect([secondImage.naturalWidth, secondImage.naturalHeight]).toEqual([4, 5])+ expect(revoke).toHaveBeenCalledWith(firstUrl)+ const secondUrl = secondImage.src+ await screen.unmount()+ expect(revoke).toHaveBeenCalledWith(secondUrl)+ const releasedImage = new Image()+ releasedImage.src = secondUrl+ await expect(releasedImage.decode()).rejects.toThrow()+ expect(request).toHaveBeenCalledTimes(2)+ } finally {+ await screen.unmount()+ queryClient.clear()+ revoke.mockRestore()+ }+})++it('recovers after a malformed asset causes the real gallery to remove its image button', async () => {+ request.mockReset()+ request.mockImplementation(+ async () =>+ new Response(new Uint8Array([0, 1, 2, 3]), {+ headers: { 'content-type': 'application/octet-stream' },+ }),+ )+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: 300_000 } },+ })+ const failedImages: string[] = []+ const handleImageError = (event: Event) => {+ if (event.target instanceof HTMLImageElement && event.target.src.startsWith('blob:'))+ failedImages.push(event.target.src)+ }+ document.addEventListener('error', handleImageError, true)+ const pluginInfo = { pluginUniqueIdentifier: 'org/plugin:1@hash', pluginId: 'org/plugin' }+ const view = (src: string) => (+ <QueryClientProvider client={queryClient}>+ <PluginImg pluginInfo={pluginInfo} src={src} />+ </QueryClientProvider>+ )+ const screen = await render(view('_assets/malformed.png'))+ try {+ await expect.poll(() => failedImages.length).toBe(1)+ await expect.element(screen.getByTestId('gallery-image')).not.toBeInTheDocument()+ await expect+ .element(screen.getByRole('button', { name: /^common\.imageGallery\.previewImage/ }))+ .not.toBeInTheDocument()++ request.mockImplementation(() => pngResponse(6, 7))+ await screen.rerender(view('_assets/valid.png'))+ await expect+ .element(screen.getByRole('button', { name: /^common\.imageGallery\.previewImage/ }))+ .toBeVisible()+ await expect+ .poll(() => screen.getByTestId('gallery-image').element().getAttribute('src'))+ .toMatch(/^blob:/)+ const recoveredImage = screen.getByTestId('gallery-image').element()+ if (!(recoveredImage instanceof HTMLImageElement)) throw new TypeError('Expected an image')+ await recoveredImage.decode()+ expect([recoveredImage.naturalWidth, recoveredImage.naturalHeight]).toEqual([6, 7])+ expect(request).toHaveBeenCalledTimes(2)+ } finally {+ document.removeEventListener('error', handleImageError, true)+ await screen.unmount()+ queryClient.clear()+ }+})diff --git a/web/app/components/base/markdown-blocks/__tests__/plugin-img.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/plugin-img.spec.tsxindex 032fd9e171e..ce704d458e4 100644--- a/web/app/components/base/markdown-blocks/__tests__/plugin-img.spec.tsx+++ b/web/app/components/base/markdown-blocks/__tests__/plugin-img.spec.tsx@@ -1,84 +1,241 @@-import { cleanup, render, screen } from '@testing-library/react'-import * as React from 'react'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { cleanup, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { toast } from '@/app/notifications'+import { consoleQuery } from '@/service/console'import { PluginImg } from '../plugin-img'--/* -------------------- Mocks -------------------- */--vi.mock('@/app/components/base/image-gallery', () => ({- __esModule: true,- default: ({ srcs }: { srcs: string[] }) => <div data-testid="image-gallery">{srcs[0]}</div>,+import { PluginParagraph } from '../plugin-paragraph'+import { getMarkdownImageURL } from '../utils'++const { request } = vi.hoisted(() => ({+ request:+ vi.fn<+ (+ url: string,+ init: RequestInit,+ options: { request: Request; silent?: boolean },+ ) => Promise<Response>+ >(),}))+vi.mock('@/service/base', () => ({ request }))-const mockUsePluginReadmeAsset = vi.fn()-vi.mock('@/service/use-plugins', () => ({- usePluginReadmeAsset: (args: unknown) => mockUsePluginReadmeAsset(args),-}))--const mockGetMarkdownImageURL = vi.fn()-vi.mock('../utils', () => ({- getMarkdownImageURL: (src: string, pluginId?: string) => mockGetMarkdownImageURL(src, pluginId),-}))+const pluginInfo = { pluginUniqueIdentifier: 'org/plugin:1.0.0@hash', pluginId: 'org/plugin' }+const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47])+let queryClient: QueryClient-/* -------------------- Tests -------------------- */--describe('PluginImg', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- afterEach(() => {- cleanup()+beforeEach(() => {+ vi.clearAllMocks()+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: 300_000 } },})+ request.mockImplementation(+ async () => new Response(bytes, { headers: { 'content-type': 'application/octet-stream' } }),+ )+ let nextUrl = 0+ vi.spyOn(URL, 'createObjectURL').mockImplementation(() => `blob:asset-${++nextUrl}`)+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})+})- it('uses blob URL when assetData exists', () => {- const fakeBlob = new Blob(['test'])- const fakeObjectUrl = 'blob:test-url'-- mockUsePluginReadmeAsset.mockReturnValue({ data: fakeBlob })- mockGetMarkdownImageURL.mockReturnValue('fallback-url')+afterEach(() => {+ cleanup()+ queryClient.clear()+ vi.restoreAllMocks()+})- const createSpy = vi.spyOn(URL, 'createObjectURL').mockReturnValue(fakeObjectUrl)+const renderImage = (src: string, info = pluginInfo) =>+ render(<PluginImg src={src} pluginInfo={info} />, {+ wrapper: ({ children }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ ),+ })- const revokeSpy = vi.spyOn(URL, 'revokeObjectURL')+it('shares normalized resource requests between image and paragraph consumers and caches binary bytes', async () => {+ render(+ <QueryClientProvider client={queryClient}>+ <PluginImg src="./_assets/logo.png" pluginInfo={pluginInfo} />+ <PluginParagraph+ pluginInfo={pluginInfo}+ node={{+ type: 'element',+ tagName: 'p',+ properties: {},+ children: [+ {+ type: 'element',+ tagName: 'img',+ properties: { src: '_assets/logo.png' },+ children: [],+ },+ ],+ }}+ />+ </QueryClientProvider>,+ )+ await waitFor(() =>+ expect(+ screen.getAllByTestId('gallery-image').map((image) => image.getAttribute('src')),+ ).toEqual(['blob:asset-1', 'blob:asset-2']),+ )+ expect(request).toHaveBeenCalledOnce()+ const [url, , options] = request.mock.calls[0]!+ expect(new URL(url).pathname).toBe('/console/api/workspaces/current/plugin/asset')+ expect(new URL(url).searchParams.get('file_name')).toBe('logo.png')+ expect(new URL(url).searchParams.get('plugin_unique_identifier')).toBe(+ pluginInfo.pluginUniqueIdentifier,+ )+ expect(options.request.method).toBe('GET')+ expect(options.silent).toBe(true)+ const cached = queryClient.getQueryData(+ consoleQuery.workspaces.current.plugin.asset.get.queryKey({+ input: {+ query: {+ file_name: 'logo.png',+ plugin_unique_identifier: pluginInfo.pluginUniqueIdentifier,+ },+ },+ }),+ )+ expect(cached).toBeInstanceOf(Blob)+ if (!(cached instanceof Blob)) throw new TypeError('Expected binary asset cache')+ expect(cached.type).toBe('application/octet-stream')+ expect(new Uint8Array(await cached.arrayBuffer())).toEqual(bytes)+ expect(URL.revokeObjectURL).not.toHaveBeenCalled()+})- const { unmount } = render(- <PluginImg src="file.png" pluginInfo={{ pluginUniqueIdentifier: 'abc', pluginId: '123' }} />,+it.each([+ { src: 'https://example.com/logo.png', info: pluginInfo },+ { src: '_assets/logo.png', info: { ...pluginInfo, pluginUniqueIdentifier: '' } },+ { src: '', info: pluginInfo },+])('keeps non-requestable resources on their existing fallback ($src)', ({ src, info }) => {+ renderImage(src, info)+ if (src)+ expect(screen.getByTestId('gallery-image')).toHaveAttribute(+ 'src',+ getMarkdownImageURL(src, info.pluginId),)+ else expect(screen.queryByTestId('gallery-image')).not.toBeInTheDocument()+ expect(request).not.toHaveBeenCalled()+})- const gallery = screen.getByTestId('image-gallery')- expect(gallery.textContent).toBe(fakeObjectUrl)-- expect(createSpy).toHaveBeenCalledWith(fakeBlob)-+it.each(['plugin', 'source'] as const)(+ 'retires the old image and open preview when its %s changes',+ async (change) => {+ const user = userEvent.setup()+ const { rerender, unmount } = renderImage('_assets/logo.png')+ await waitFor(() =>+ expect(screen.getByTestId('gallery-image')).toHaveAttribute('src', 'blob:asset-1'),+ )+ await user.click(screen.getByRole('button', { name: /^common\.imageGallery\.previewImage/ }))+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ let resolveResponse: ((response: Response) => void) | undefined+ request.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveResponse = resolve+ }),+ )+ const src = change === 'source' ? '_assets/other.png' : '_assets/logo.png'+ const info =+ change === 'plugin'+ ? { ...pluginInfo, pluginUniqueIdentifier: 'org/plugin:2.0.0@new' }+ : pluginInfo+ rerender(<PluginImg src={src} pluginInfo={info} />)+ expect(screen.getByTestId('gallery-image')).toHaveAttribute(+ 'src',+ getMarkdownImageURL(src, info.pluginId),+ )+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:asset-1')+ await waitFor(() => expect(request).toHaveBeenCalledTimes(2))+ resolveResponse?.(+ new Response(bytes, { headers: { 'content-type': 'application/octet-stream' } }),+ )+ await waitFor(() =>+ expect(screen.getByTestId('gallery-image')).toHaveAttribute('src', 'blob:asset-2'),+ )unmount()+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:asset-2')+ },+)++it('retains the marketplace fallback when the asset request fails', async () => {+ request.mockImplementation(async () =>+ Response.json({ message: 'Missing asset' }, { status: 404 }),+ )+ renderImage('_assets/missing.png')+ await waitFor(() => expect(queryClient.getQueryCache().getAll()[0]?.state.status).toBe('error'))+ expect(screen.getByTestId('gallery-image')).toHaveAttribute(+ 'src',+ getMarkdownImageURL('_assets/missing.png', pluginInfo.pluginId),+ )+ expect(URL.createObjectURL).not.toHaveBeenCalled()+})- expect(revokeSpy).toHaveBeenCalledWith(fakeObjectUrl)- })-- it('falls back to getMarkdownImageURL when no assetData', () => {- mockUsePluginReadmeAsset.mockReturnValue({ data: undefined })- mockGetMarkdownImageURL.mockReturnValue('computed-url')+it('inherits asset retries from the client and stays silent when the first HTTP attempt fails', async () => {+ queryClient.setDefaultOptions({ queries: { retry: 2, retryDelay: 0, staleTime: 300_000 } })+ request.mockImplementationOnce(async () =>+ Response.json({ message: 'Temporarily unavailable' }, { status: 503 }),+ )+ const errorToast = vi.spyOn(toast, 'error')+ renderImage('_assets/retry.png')++ await waitFor(() =>+ expect(screen.getByTestId('gallery-image')).toHaveAttribute('src', 'blob:asset-1'),+ )+ expect(request).toHaveBeenCalledTimes(2)+ expect(request.mock.calls.every(([, , options]) => options.silent === true)).toBe(true)+ expect(errorToast).not.toHaveBeenCalled()+})- render(- <PluginImg src="file.png" pluginInfo={{ pluginUniqueIdentifier: 'abc', pluginId: '123' }} />,+it.each([+ { kind: 'image', status: 'pending' },+ { kind: 'image', status: 'failed' },+ { kind: 'paragraph', status: 'pending' },+ { kind: 'paragraph', status: 'failed' },+])(+ 'closes a $status $kind fallback preview when only the plugin version changes',+ async ({ kind, status }) => {+ const user = userEvent.setup()+ request.mockImplementation(() =>+ status === 'pending'+ ? new Promise<Response>(() => {})+ : Promise.resolve(Response.json({ message: 'Missing asset' }, { status: 404 })),)-- const gallery = screen.getByTestId('image-gallery')- expect(gallery.textContent).toBe('computed-url')-- expect(mockGetMarkdownImageURL).toHaveBeenCalledWith('file.png', '123')- })-- it('works without pluginInfo', () => {- mockUsePluginReadmeAsset.mockReturnValue({ data: undefined })- mockGetMarkdownImageURL.mockReturnValue('default-url')-- render(<PluginImg src="file.png" />)-- const gallery = screen.getByTestId('image-gallery')- expect(gallery.textContent).toBe('default-url')-- expect(mockGetMarkdownImageURL).toHaveBeenCalledWith('file.png', undefined)- })-})+ const src = '_assets/logo.png'+ const view = (info: typeof pluginInfo) =>+ kind === 'image' ? (+ <PluginImg src={src} pluginInfo={info} />+ ) : (+ <PluginParagraph+ pluginInfo={info}+ node={{+ type: 'element',+ tagName: 'p',+ properties: {},+ children: [{ type: 'element', tagName: 'img', properties: { src }, children: [] }],+ }}+ />+ )+ const { rerender } = render(view(pluginInfo), {+ wrapper: ({ children }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ ),+ })+ await waitFor(() => expect(request).toHaveBeenCalledOnce())+ if (status === 'failed')+ await waitFor(() =>+ expect(queryClient.getQueryCache().getAll()[0]?.state.status).toBe('error'),+ )+ await user.click(screen.getByRole('button', { name: /^common\.imageGallery\.previewImage/ }))+ expect(screen.getByRole('dialog')).toBeInTheDocument()++ rerender(view({ ...pluginInfo, pluginUniqueIdentifier: 'org/plugin:2.0.0@new' }))+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(screen.getByTestId('gallery-image')).toHaveAttribute(+ 'src',+ getMarkdownImageURL(src, pluginInfo.pluginId),+ )+ await waitFor(() => expect(request).toHaveBeenCalledTimes(2))+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ },+)diff --git a/web/app/components/base/markdown-blocks/__tests__/plugin-paragraph.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/plugin-paragraph.spec.tsxindex 48479f9d4c1..203b1932d03 100644--- a/web/app/components/base/markdown-blocks/__tests__/plugin-paragraph.spec.tsx+++ b/web/app/components/base/markdown-blocks/__tests__/plugin-paragraph.spec.tsx@@ -1,193 +1,117 @@import type { ExtraProps } from 'streamdown'-import { render, screen } from '@testing-library/react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { cleanup, 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 { usePluginReadmeAsset } from '@/service/use-plugins'import { PluginParagraph } from '../plugin-paragraph'-import { getMarkdownImageURL, hasImageChild } from '../utils'--// Mock dependencies-vi.mock('@/service/use-plugins', () => ({- usePluginReadmeAsset: vi.fn(),-}))--vi.mock('../utils', () => ({- getMarkdownImageURL: vi.fn(),- hasImageChild: vi.fn((): boolean => false),-}))--vi.mock('@/app/components/base/image-uploader/image-preview', () => ({- default: ({ url, onCancel }: { url: string; onCancel: () => void }) => (- <div data-testid="image-preview-modal">- <span>{url}</span>- <button onClick={onCancel} type="button">- Close- </button>- </div>- ),-}))--/**- * Helper to build a minimal hast-compatible Element node for testing.- * The runtime code only reads `node.children[*].tagName` and `.properties.src`,- * so we keep the mock minimal and cast to satisfy the full hast Element type.- */-type MockChild = { tagName?: string; properties?: { src?: string } }--function mockNode(children: MockChild[]): ExtraProps['node'] {- return {- type: 'element',- tagName: 'p',- properties: {},- children,- } as unknown as ExtraProps['node']-}--type HookReturn = {- data?: Blob- isLoading?: boolean- error?: Error | null-}--describe('PluginParagraph', () => {- const mockPluginInfo = {- pluginUniqueIdentifier: 'test-plugin-id',- pluginId: 'plugin-123',- }-- beforeEach(() => {- vi.clearAllMocks()-- // Ensure URL globals exist in the test environment using globalThis- if (!globalThis.URL.createObjectURL) {- globalThis.URL.createObjectURL = vi.fn()- globalThis.URL.revokeObjectURL = vi.fn()- }-- // Default mock return to prevent destructuring errors- vi.mocked(usePluginReadmeAsset).mockReturnValue({- data: undefined,- isLoading: false,- error: null,- } as HookReturn as ReturnType<typeof usePluginReadmeAsset>)- })-- it('should render a standard paragraph when not an image', () => {- const node = mockNode([{ tagName: 'span' }])- render(<PluginParagraph node={node}>Hello World</PluginParagraph>)-- expect(screen.getByTestId('standard-paragraph')).toHaveTextContent('Hello World')- })-- it('should render an ImageGallery when the first child is an image', () => {- const node = mockNode([{ tagName: 'img', properties: { src: 'test-img.png' } }])- vi.mocked(getMarkdownImageURL).mockReturnValue('https://cdn.com/test-img.png')-- const { container } = render(- <PluginParagraph pluginInfo={mockPluginInfo} node={node}>- <img src="test-img.png" alt="" />- </PluginParagraph>,- )-- expect(screen.getByTestId('image-paragraph-wrapper')).toBeInTheDocument()- // Query by selector since alt="" removes the 'img' role from the accessibility tree- const img = container.querySelector('img')- expect(img).toHaveAttribute('src', 'https://cdn.com/test-img.png')- })-- it('should use a blob URL when asset data is successfully fetched', () => {- const node = mockNode([{ tagName: 'img', properties: { src: 'test-img.png' } }])- const mockBlob = new Blob([''], { type: 'image/png' })- vi.mocked(usePluginReadmeAsset).mockReturnValue({- data: mockBlob,- } as HookReturn as ReturnType<typeof usePluginReadmeAsset>)-- vi.spyOn(globalThis.URL, 'createObjectURL').mockReturnValue('blob:actual-blob-url')-- const { container } = render(- <PluginParagraph pluginInfo={mockPluginInfo} node={node}>- <img src="test-img.png" alt="" />- </PluginParagraph>,- )-- const img = container.querySelector('img')- expect(img).toHaveAttribute('src', 'blob:actual-blob-url')- })-- it('should render remaining children below the image gallery', () => {- const node = mockNode([- { tagName: 'img', properties: { src: 'test-img.png' } },- { tagName: 'text' },- ])-- render(- <PluginParagraph pluginInfo={mockPluginInfo} node={node}>- <img src="test-img.png" alt="" />- <span>Caption Text</span>- </PluginParagraph>,- )-- expect(screen.getByTestId('remaining-children')).toHaveTextContent('Caption Text')- })-- it('should revoke the blob URL on unmount to prevent memory leaks', () => {- const node = mockNode([{ tagName: 'img', properties: { src: 'test-img.png' } }])- const mockBlob = new Blob([''], { type: 'image/png' })- vi.mocked(usePluginReadmeAsset).mockReturnValue({- data: mockBlob,- } as HookReturn as ReturnType<typeof usePluginReadmeAsset>)-- const revokeSpy = vi.spyOn(globalThis.URL, 'revokeObjectURL')- vi.spyOn(globalThis.URL, 'createObjectURL').mockReturnValue('blob:cleanup-test')-- const { unmount } = render(- <PluginParagraph pluginInfo={mockPluginInfo} node={node}>- <img src="test-img.png" alt="" />- </PluginParagraph>,- )-- unmount()- expect(revokeSpy).toHaveBeenCalledWith('blob:cleanup-test')- })-- it('should open the image preview modal when an image in the gallery is clicked', async () => {- const user = userEvent.setup()- const node = mockNode([{ tagName: 'img', properties: { src: 'test-img.png' } }])- vi.mocked(getMarkdownImageURL).mockReturnValue('https://cdn.com/gallery.png')-- const { container } = render(- <PluginParagraph pluginInfo={mockPluginInfo} node={node}>- <img src="test-img.png" alt="" />- </PluginParagraph>,- )-- const img = container.querySelector('img')- if (img) await user.click(img)-- // ImageGallery is not mocked, so it should trigger the preview- expect(screen.getByTestId('image-preview-modal')).toBeInTheDocument()- expect(screen.getByText('https://cdn.com/gallery.png')).toBeInTheDocument()-- const closeBtn = screen.getByText('Close')- await user.click(closeBtn)- expect(screen.queryByTestId('image-preview-modal')).not.toBeInTheDocument()+import { getMarkdownImageURL } from '../utils'++const { request } = vi.hoisted(() => ({ request: vi.fn<() => Promise<Response>>() }))+vi.mock('@/service/base', () => ({ request }))+const pluginInfo = { pluginUniqueIdentifier: 'org/plugin:1@hash', pluginId: 'org/plugin' }+const imageNode = (src: string): ExtraProps['node'] => ({+ type: 'element',+ tagName: 'p',+ properties: {},+ children: [{ type: 'element', tagName: 'img', properties: { src }, children: [] }],+})+let queryClient: QueryClient+beforeEach(() => {+ vi.clearAllMocks()+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: 300_000 } },})+ request.mockImplementation(+ async () =>+ new Response('image-bytes', { headers: { 'content-type': 'application/octet-stream' } }),+ )+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:paragraph-image')+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})+})+afterEach(() => {+ cleanup()+ queryClient.clear()+ vi.restoreAllMocks()+})+const wrapper = ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+)++it('displays the leading asset with its caption and preserves ordinary paragraph content without requesting assets', async () => {+ const { unmount } = render(+ <>+ <PluginParagraph pluginInfo={pluginInfo} node={imageNode('./_assets/caption.png')}>+ <img src="./_assets/caption.png" alt="" />+ <span>Image caption</span>+ </PluginParagraph>+ <PluginParagraph pluginInfo={pluginInfo}>Ordinary paragraph</PluginParagraph>+ </>,+ { wrapper },+ )+ await waitFor(() =>+ expect(screen.getByTestId('gallery-image')).toHaveAttribute('src', 'blob:paragraph-image'),+ )+ expect(screen.getByText('Image caption')).toBeInTheDocument()+ expect(screen.getByText('Ordinary paragraph').tagName).toBe('P')+ expect(request).toHaveBeenCalledOnce()+ expect(URL.revokeObjectURL).not.toHaveBeenCalled()++ unmount()++ expect(URL.revokeObjectURL).toHaveBeenCalledExactlyOnceWith('blob:paragraph-image')+})- it('should render div instead of p when image is not the first child', () => {- vi.mocked(hasImageChild).mockReturnValue(true)-- const node = mockNode([- { tagName: 'span' },- { tagName: 'img', properties: { src: 'test.png' } },- ])-- render(- <PluginParagraph node={node}>- <span>Text</span>- </PluginParagraph>,- )+it('uses nested image children without issuing a duplicate leading-image request', () => {+ render(+ <PluginParagraph+ pluginInfo={pluginInfo}+ node={{+ type: 'element',+ tagName: 'p',+ properties: {},+ children: [+ { type: 'text', value: 'Description' },+ {+ type: 'element',+ tagName: 'img',+ properties: { src: '_assets/nested.png' },+ children: [],+ },+ ],+ }}+ >+ <span>Description</span>+ <img src="https://example.com/nested.png" alt="Nested diagram" />+ </PluginParagraph>,+ { wrapper },+ )+ expect(screen.getByText('Description')).toBeInTheDocument()+ expect(screen.getByRole('img', { name: 'Nested diagram' })).toHaveAttribute(+ 'src',+ 'https://example.com/nested.png',+ )+ expect(request).not.toHaveBeenCalled()+})- expect(screen.getByTestId('image-fallback-paragraph')).toBeInTheDocument()- expect(screen.getByTestId('image-fallback-paragraph').tagName).toBe('DIV')- })+it('closes the obsolete asset preview when the paragraph changes to an external image and releases its URL', async () => {+ const user = userEvent.setup()+ const { rerender, unmount } = render(+ <PluginParagraph pluginInfo={pluginInfo} node={imageNode('_assets/old.png')} />,+ { wrapper },+ )+ await waitFor(() =>+ expect(screen.getByTestId('gallery-image')).toHaveAttribute('src', 'blob:paragraph-image'),+ )+ await user.click(screen.getByRole('button', { name: /^common\.imageGallery\.previewImage/ }))+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ rerender(+ <PluginParagraph pluginInfo={pluginInfo} node={imageNode('https://example.com/new.png')} />,+ )+ expect(screen.getByTestId('gallery-image')).toHaveAttribute(+ 'src',+ getMarkdownImageURL('https://example.com/new.png', pluginInfo.pluginId),+ )+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(URL.revokeObjectURL).toHaveBeenCalledExactlyOnceWith('blob:paragraph-image')+ expect(request).toHaveBeenCalledOnce()+ unmount()})diff --git a/web/app/components/base/markdown-blocks/plugin-asset-query.ts b/web/app/components/base/markdown-blocks/plugin-asset-query.tsnew file mode 100644index 00000000000..3367a415559--- /dev/null+++ b/web/app/components/base/markdown-blocks/plugin-asset-query.ts@@ -0,0 +1,21 @@+import { skipToken } from '@tanstack/react-query'+import { consoleQuery } from '@/service/console'++export function pluginAssetQueryOptions(+ fileName: string | undefined,+ pluginUniqueIdentifier: string | undefined,+) {+ const isAssetFile = fileName?.startsWith('./_assets') || fileName?.startsWith('_assets')++ return consoleQuery.workspaces.current.plugin.asset.get.queryOptions({+ input:+ pluginUniqueIdentifier && fileName && isAssetFile+ ? {+ query: {+ plugin_unique_identifier: pluginUniqueIdentifier,+ file_name: fileName.replace(/^\.\/_assets\//, '').replace(/^_assets\//, ''),+ },+ }+ : skipToken,+ })+}diff --git a/web/app/components/base/markdown-blocks/plugin-img.tsx b/web/app/components/base/markdown-blocks/plugin-img.tsxindex f8cf3b81a91..d7101b96d06 100644--- a/web/app/components/base/markdown-blocks/plugin-img.tsx+++ b/web/app/components/base/markdown-blocks/plugin-img.tsx@@ -4,9 +4,10 @@ import type { SimplePluginInfo } from '../markdown/streamdown-wrapper'* Extracted from the main markdown renderer for modularity.* Uses the ImageGallery component to display images.*/+import { useQuery } from '@tanstack/react-query'import { memo, useEffect, useMemo, useState } from 'react'import ImageGallery from '@/app/components/base/image-gallery'-import { usePluginReadmeAsset } from '@/service/use-plugins'+import { pluginAssetQueryOptions } from './plugin-asset-query'import { getMarkdownImageURL } from './utils'type ImgProps = {@@ -16,11 +17,8 @@ type ImgProps = {export const PluginImg = memo<ImgProps>(({ src, pluginInfo }) => {const { pluginUniqueIdentifier, pluginId } = pluginInfo || {}- const { data: assetData } = usePluginReadmeAsset({- plugin_unique_identifier: pluginUniqueIdentifier,- file_name: src,- })- const [blobUrl, setBlobUrl] = useState<string>()+ const { data: assetData } = useQuery(pluginAssetQueryOptions(src, pluginUniqueIdentifier))+ const [blobUrl, setBlobUrl] = useState<{ data: Blob; url: string }>()useEffect(() => {if (!assetData) {@@ -29,7 +27,7 @@ export const PluginImg = memo<ImgProps>(({ src, pluginInfo }) => {}const objectUrl = URL.createObjectURL(assetData)- setBlobUrl(objectUrl)+ setBlobUrl({ data: assetData, url: objectUrl })return () => {URL.revokeObjectURL(objectUrl)@@ -37,16 +35,16 @@ export const PluginImg = memo<ImgProps>(({ src, pluginInfo }) => {}, [assetData])const imageUrl = useMemo(() => {- if (blobUrl) return blobUrl+ if (blobUrl && blobUrl.data === assetData) return blobUrl.urlreturn getMarkdownImageURL(src, pluginId)- }, [blobUrl, pluginId, src])+ }, [assetData, blobUrl, pluginId, src])const srcs = useMemo(() => [imageUrl], [imageUrl])return (<div className="markdown-img-wrapper">- <ImageGallery srcs={srcs} />+ <ImageGallery key={JSON.stringify([pluginUniqueIdentifier, imageUrl])} srcs={srcs} /></div>)})diff --git a/web/app/components/base/markdown-blocks/plugin-paragraph.tsx b/web/app/components/base/markdown-blocks/plugin-paragraph.tsxindex e4de9e633d6..39479747e57 100644--- a/web/app/components/base/markdown-blocks/plugin-paragraph.tsx+++ b/web/app/components/base/markdown-blocks/plugin-paragraph.tsx@@ -1,16 +1,12 @@import type { ExtraProps } from 'streamdown'import type { SimplePluginInfo } from '../markdown/streamdown-wrapper'+import { useQuery } from '@tanstack/react-query'import * as React from 'react'import { useEffect, useMemo, useState } from 'react'import ImageGallery from '@/app/components/base/image-gallery'-import { usePluginReadmeAsset } from '@/service/use-plugins'+import { pluginAssetQueryOptions } from './plugin-asset-query'import { getMarkdownImageURL, hasImageChild } from './utils'-type HastChildNode = {- tagName?: string- properties?: { src?: string; [key: string]: unknown }-}-type PluginParagraphProps = {pluginInfo?: SimplePluginInfonode?: ExtraProps['node']@@ -19,17 +15,14 @@ type PluginParagraphProps = {export const PluginParagraph: React.FC<PluginParagraphProps> = ({ pluginInfo, node, children }) => {const { pluginUniqueIdentifier, pluginId } = pluginInfo || {}- const childrenNode = node?.children as HastChildNode[] | undefined+ const childrenNode = node?.childrenconst firstChild = childrenNode?.[0]- const isImageParagraph = firstChild?.tagName === 'img'- const imageSrc = isImageParagraph ? firstChild?.properties?.src : undefined+ const isImageParagraph = firstChild?.type === 'element' && firstChild.tagName === 'img'+ const imageSrc = isImageParagraph ? firstChild.properties.src : undefined- const { data: assetData } = usePluginReadmeAsset({- plugin_unique_identifier: pluginUniqueIdentifier,- file_name: isImageParagraph && imageSrc ? imageSrc : '',- })+ const { data: assetData } = useQuery(pluginAssetQueryOptions(imageSrc, pluginUniqueIdentifier))- const [blobUrl, setBlobUrl] = useState<string>()+ const [blobUrl, setBlobUrl] = useState<{ data: Blob; url: string }>()useEffect(() => {if (!assetData) {@@ -38,7 +31,7 @@ export const PluginParagraph: React.FC<PluginParagraphProps> = ({ pluginInfo, no}const objectUrl = URL.createObjectURL(assetData)- setBlobUrl(objectUrl)+ setBlobUrl({ data: assetData, url: objectUrl })return () => {URL.revokeObjectURL(objectUrl)@@ -46,12 +39,12 @@ export const PluginParagraph: React.FC<PluginParagraphProps> = ({ pluginInfo, no}, [assetData])const imageUrl = useMemo(() => {- if (blobUrl) return blobUrl+ if (blobUrl && blobUrl.data === assetData) return blobUrl.urlif (isImageParagraph && imageSrc) return getMarkdownImageURL(imageSrc, pluginId)return ''- }, [blobUrl, imageSrc, isImageParagraph, pluginId])+ }, [assetData, blobUrl, imageSrc, isImageParagraph, pluginId])if (isImageParagraph) {const remainingChildren =@@ -59,7 +52,7 @@ export const PluginParagraph: React.FC<PluginParagraphProps> = ({ pluginInfo, noreturn (<div className="markdown-img-wrapper" data-testid="image-paragraph-wrapper">- <ImageGallery srcs={[imageUrl]} />+ <ImageGallery key={JSON.stringify([pluginUniqueIdentifier, imageUrl])} srcs={[imageUrl]} />{remainingChildren && (<div className="mt-2" data-testid="remaining-children">{remainingChildren}diff --git a/web/app/components/base/markdown-blocks/utils.ts b/web/app/components/base/markdown-blocks/utils.tsindex 1bbed2a26de..d78c204f1b0 100644--- a/web/app/components/base/markdown-blocks/utils.ts+++ b/web/app/components/base/markdown-blocks/utils.ts@@ -1,17 +1,14 @@+import type { ExtraProps } from 'streamdown'import { ALLOW_UNSAFE_DATA_SCHEME, MARKETPLACE_API_PREFIX } from '@/config'-type MdastNode = {- tagName?: string- children?: MdastNode[]- [key: string]: unknown-}--export const hasImageChild = (children: MdastNode[] | undefined): boolean => {+export const hasImageChild = (+ children: NonNullable<ExtraProps['node']>['children'] | undefined,+): boolean => {return (- children?.some((child) => {- if (child.tagName === 'img') return true- return child.children ? hasImageChild(child.children) : false- }) ?? false+ children?.some(+ (child) =>+ child.type === 'element' && (child.tagName === 'img' || hasImageChild(child.children)),+ ) ?? false)}diff --git a/web/app/components/plugins/readme-panel/README.md b/web/app/components/plugins/readme-panel/README.mdnew file mode 100644index 00000000000..a11ea72a412--- /dev/null+++ b/web/app/components/plugins/readme-panel/README.md@@ -0,0 +1,56 @@+# Plugin Readme reading++The panel owns Readme loading, empty and error presentation. Its store owns the+selected plugin and drawer/dialog session, while TanStack Query owns the fetched+text and binary resources.++## API and type ownership++The Console `PluginReadmeApi` and `PluginAssetApi` controllers in+`api/controllers/console/workspace/plugin.py` own the public HTTP contracts.+`PluginReadmeResponse` contains `readme: string`; `BinaryFileResponse` is generated+as `Blob | File`. The backend adapts the daemon's Readme content to the Console+response. A successful empty string and a failed request are distinct outcomes:+the panel displays its empty state for the former and its failure state for the+latter.++Consume `consoleQuery.workspaces.current.plugin.readme.get` and+`consoleQuery.workspaces.current.plugin.asset.get` directly. Keep the generated+responses in the cache; do not mirror their types or cache object URLs.++## Query and display decisions++| Operation | Shared policy | Consumer-owned input and presentation |+| -------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |+| Readme text | Silent transport errors; no retries; normal client freshness | Complete plugin unique identifier and model-language value; loading, empty and failure presentation |+| Local resource | Silent transport errors; normal client freshness and observer retries | Complete plugin unique identifier and normalized asset filename; marketplace image fallback and object URL lifetime |++The normal browser client freshness is five minutes. A missing required input+uses `skipToken`. Text identity includes the language; asset identity includes+the normalized filename. Both include the full plugin identifier, so changing+plugin versions selects a different cache entry.++Readme requests retain the existing model-language mapping (`en_US`, `zh_Hans`,+and other locale values with an underscore). Display metadata uses its separate+plugin-language fallback. Do not interchange these mappings or switch Readme+requests to the backend's default language as part of a query migration.++Markdown resource consumers own eligibility and filename normalization for+`./_assets` and `_assets` references. Ordinary external image URLs use the existing+Markdown fallback without a Console asset request. Each mounted image consumer+creates its own object URL from the cached binary and releases it on replacement+or unmount. A changed resource must not display a URL owned by the previous+resource or retain its image-preview session.++Both endpoints read plugin package content. They do not mutate installation,+permissions, or catalog state, so they add no mutation invalidation. Workspace+switching remains the existing full-document reload boundary. This module does+not own installation-task polling, plugin settings, or general Markdown rendering.++## Verification boundary++Exercise the production consumers with generated queries and an intercepted HTTP+boundary. Cover text states and locale/version isolation, resource admission and+fallback, and replacement/unmount cleanup. Browser verification must also prove+that the actual binary response produces a decodable image and that switching+resources restores the current image after an earlier image failed.diff --git a/web/app/components/plugins/readme-panel/__tests__/datasource.spec.tsx b/web/app/components/plugins/readme-panel/__tests__/datasource.spec.tsxindex 3667b8a2881..0cea327fb10 100644--- a/web/app/components/plugins/readme-panel/__tests__/datasource.spec.tsx+++ b/web/app/components/plugins/readme-panel/__tests__/datasource.spec.tsx@@ -1,21 +1,23 @@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 { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'import { createDatasourceProvider } from '@/app/components/rag-pipeline/__tests__/datasource-fixtures'import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { ReadmeEntrance } from '../entrance'import ReadmePanel from '../index'import { useReadmePanelStore } from '../store'-const { get } = vi.hoisted(() => ({ get: vi.fn() }))-vi.mock('@/service/base', () => ({ get }))+const fetchMock = vi.fn<typeof fetch>()beforeEach(() => {vi.clearAllMocks()useReadmePanelStore.setState({ currentPanel: undefined })- get.mockResolvedValue({ readme: '# Datasource documentation' })+ vi.stubGlobal('fetch', fetchMock)+ fetchMock.mockImplementation(async () => Response.json({ readme: '# Datasource documentation' }))})+afterEach(() => vi.unstubAllGlobals())+describe('datasource Readme', () => {it.each(['drawer', 'dialog'] as const)('opens a raw catalog provider in a %s without installed-plugin metadata',@@ -39,16 +41,14 @@ describe('datasource Readme', () => {expect(screen.getByText('Load files')).toBeInTheDocument()expect(document.querySelector('img[src="/datasource.svg"]')).toBeInTheDocument()expect(useReadmePanelStore.getState().currentPanel?.detail).toBe(provider)- expect(get).toHaveBeenCalledWith(- '/workspaces/current/plugin/readme',- {- params: {- plugin_unique_identifier: provider.plugin_unique_identifier,- language: 'en_US',- },- },- { silent: true },- )+ expect(fetchMock).toHaveBeenCalledTimes(1)+ const [request] = fetchMock.mock.calls[0]!+ const url = new URL(request instanceof Request ? request.url : String(request))+ expect(url.pathname).toMatch(/\/workspaces\/current\/plugin\/readme$/)+ expect(Object.fromEntries(url.searchParams)).toEqual({+ plugin_unique_identifier: provider.plugin_unique_identifier,+ language: 'en_US',+ })expect(screen.queryByRole('button', { name: 'plugin.detailPanel.operation.update' }),).not.toBeInTheDocument()diff --git a/web/app/components/plugins/readme-panel/__tests__/entrance.spec.tsx b/web/app/components/plugins/readme-panel/__tests__/entrance.spec.tsxindex 0822e4aabe3..e3b2522b8fe 100644--- a/web/app/components/plugins/readme-panel/__tests__/entrance.spec.tsx+++ b/web/app/components/plugins/readme-panel/__tests__/entrance.spec.tsx@@ -1,72 +1,20 @@-import { fireEvent, render, screen } from '@testing-library/react'-import { beforeEach, describe, expect, it } from 'vite-plus/test'+import { render, screen } from '@testing-library/react'+import { describe, expect, it } from 'vite-plus/test'+import { createPluginDetail } from '../../plugin-detail-panel/__tests__/endpoint-fixture'import { ReadmeEntrance } from '../entrance'-import { useReadmePanelStore } from '../store'-describe('ReadmeEntrance', () => {- beforeEach(() => {- useReadmePanelStore.setState({ currentPanel: undefined })- })-- it('should render readme button for non-builtin plugin with unique identifier', () => {- const pluginDetail = {- id: 'custom-plugin',- name: 'custom-plugin',- plugin_unique_identifier: 'org/custom-plugin',- } as never- render(<ReadmeEntrance pluginDetail={pluginDetail} />)-- expect(screen.getByRole('button')).toBeInTheDocument()- })-- it('should open drawer presentation by default', () => {- const pluginDetail = {- id: 'custom-plugin',- name: 'custom-plugin',- plugin_unique_identifier: 'org/custom-plugin',- } as never- render(<ReadmeEntrance pluginDetail={pluginDetail} />)-- const button = screen.getByRole('button')- fireEvent.click(button)-- expect(useReadmePanelStore.getState().currentPanel).toEqual({- detail: pluginDetail,- presentation: 'drawer',- triggerId: button.id,- })- })-- it('should open dialog presentation when requested', () => {- const pluginDetail = {- id: 'custom-plugin',- name: 'custom-plugin',- plugin_unique_identifier: 'org/custom-plugin',- } as never- render(<ReadmeEntrance pluginDetail={pluginDetail} presentation="dialog" />)-- fireEvent.click(screen.getByRole('button'))-- expect(useReadmePanelStore.getState().currentPanel?.presentation).toBe('dialog')- })-- it('should return null for builtin tools', () => {- const pluginDetail = { id: 'code', name: 'Code', plugin_unique_identifier: 'org/code' } as never- const { container } = render(<ReadmeEntrance pluginDetail={pluginDetail} />)-- expect(container.innerHTML).toBe('')- })-- it('should return null when plugin_unique_identifier is missing', () => {- const pluginDetail = { id: 'some-plugin', name: 'Some Plugin' } as never- const { container } = render(<ReadmeEntrance pluginDetail={pluginDetail} />)+describe('ReadmeEntrance admission', () => {+ it('does not offer a Readme for a built-in tool', () => {+ render(<ReadmeEntrance pluginDetail={{ ...createPluginDetail(), id: 'code' }} />)- expect(container.innerHTML).toBe('')+ expect(screen.queryByRole('button')).not.toBeInTheDocument()})- it('should return null when pluginDetail is null', () => {- const { container } = render(<ReadmeEntrance pluginDetail={null as never} />)+ it('does not offer a Readme without a plugin identifier', () => {+ render(+ <ReadmeEntrance pluginDetail={{ ...createPluginDetail(), plugin_unique_identifier: '' }} />,+ )- expect(container.innerHTML).toBe('')+ expect(screen.queryByRole('button')).not.toBeInTheDocument()})})diff --git a/web/app/components/plugins/readme-panel/__tests__/index.spec.tsx b/web/app/components/plugins/readme-panel/__tests__/index.spec.tsxindex 259ee1c80b5..907802ce0d4 100644--- a/web/app/components/plugins/readme-panel/__tests__/index.spec.tsx+++ b/web/app/components/plugins/readme-panel/__tests__/index.spec.tsx@@ -1,245 +1,203 @@-import type { ReactElement } from 'react'-import type { PluginDetail } from '../../types'-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { fireEvent, render, screen } from '@testing-library/react'-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'-import { PluginCategoryEnum, PluginSource } from '../../types'+import type { Locale } from '@/i18n/locale'+import { QueryClient } from '@tanstack/react-query'+import { act, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { toast } from '@/app/notifications'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'+import { createPluginDetail } from '../../plugin-detail-panel/__tests__/endpoint-fixture'import { ReadmeEntrance } from '../entrance'import ReadmePanel from '../index'import { useReadmePanelStore } from '../store'-;(- globalThis as typeof globalThis & {- BASE_UI_ANIMATIONS_DISABLED: boolean- }-).BASE_UI_ANIMATIONS_DISABLED = true--const mockUsePluginReadme = vi.fn()-vi.mock('@/service/use-plugins', () => ({- usePluginReadme: (params: { plugin_unique_identifier: string; language?: string }) =>- mockUsePluginReadme(params),-}))--let mockLanguage = 'en-US'-vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({- useLanguage: () => mockLanguage,+let mockLocale: Locale = 'en-US'+vi.mock('#i18n', async (importOriginal) => ({+ ...(await importOriginal<typeof import('#i18n')>()),+ useLocale: () => mockLocale,}))vi.mock('../../plugin-detail-panel/detail-header', () => ({- default: ({ detail, isReadmeView }: { detail: PluginDetail; isReadmeView: boolean }) => (- <div data-testid="detail-header" data-is-readme-view={isReadmeView}>- {detail.name}- </div>- ),+ default: ({ detail }: { detail: { name: string } }) => <p>{detail.name}</p>,}))-const createMockPluginDetail = (overrides: Partial<PluginDetail> = {}): PluginDetail => ({- id: 'test-plugin-id',- created_at: '2024-01-01T00:00:00Z',- updated_at: '2024-01-01T00:00:00Z',- name: 'test-plugin',- plugin_id: 'test-plugin-id',- plugin_unique_identifier: '[email protected]',- declaration: {- plugin_unique_identifier: '[email protected]',- version: '1.0.0',- author: 'test-author',- icon: 'test-icon.png',- name: 'test-plugin',- category: PluginCategoryEnum.tool,- label: { 'en-US': 'Test Plugin' } as Record<string, string>,- description: { 'en-US': 'Test plugin description' } as Record<string, string>,- created_at: '2024-01-01T00:00:00Z',- resource: null,- plugins: null,- verified: true,- endpoint: { settings: [], endpoints: [] },- model: null,- tags: [],- agent_strategy: null,- meta: { version: '1.0.0' },- trigger: {- events: [],- identity: {- author: 'test-author',- name: 'test-plugin',- label: { 'en-US': 'Test Plugin' } as Record<string, string>,- description: { 'en-US': 'Test plugin description' } as Record<string, string>,- icon: 'test-icon.png',- tags: [],- },- subscription_constructor: {- credentials_schema: [],- oauth_schema: { client_schema: [], credentials_schema: [] },- parameters: [],- },- subscription_schema: [],- },- },- installation_id: 'install-123',- tenant_id: 'tenant-123',- endpoints_setups: 0,- endpoints_active: 0,- version: '1.0.0',- latest_version: '1.0.0',- latest_unique_identifier: '[email protected]',- source: PluginSource.marketplace,- status: 'active' as const,- deprecated_reason: '',- alternative_plugin_id: '',- ...overrides,-})+const fetchMock = vi.fn<typeof fetch>()-const createQueryClient = () =>- new QueryClient({+function createQueryClient() {+ return new QueryClient({defaultOptions: {- queries: {- retry: false,- },+ queries: { staleTime: 5 * 60 * 1000, retry: 2, retryDelay: 0 },},})--const renderWithQueryClient = (ui: ReactElement) => {- const queryClient = createQueryClient()- return render(<QueryClientProvider client={queryClient}>{ui}</QueryClientProvider>)}-const openReadmePanel = (- detail = createMockPluginDetail(),- presentation: 'drawer' | 'dialog' = 'drawer',-) => {- useReadmePanelStore.getState().openReadmePanel({- detail,- presentation,- triggerId: 'readme-trigger',- })+function openPanel(identifier = 'langgenius/test:1.0.0') {+ const detail = { ...createPluginDetail(), plugin_unique_identifier: identifier }+ act(() => useReadmePanelStore.getState().openReadmePanel({ detail }))return detail}-describe('ReadmePanel', () => {- beforeEach(() => {- vi.clearAllMocks()- mockLanguage = 'en-US'- useReadmePanelStore.setState({ currentPanel: undefined })- mockUsePluginReadme.mockReturnValue({- data: null,- isLoading: false,- error: null,- })- })+function readmeURL(input: Parameters<typeof fetch>[0]) {+ return new URL(input instanceof Request ? input.url : String(input))+}- it('should return null when no readme panel is open', () => {- const { container } = renderWithQueryClient(<ReadmePanel />)+beforeEach(() => {+ vi.clearAllMocks()+ mockLocale = 'en-US'+ useReadmePanelStore.setState({ currentPanel: undefined })+ vi.stubGlobal('fetch', fetchMock)+ fetchMock.mockImplementation(async () => Response.json({ readme: '# Plugin documentation' }))+})- expect(container.firstChild).toBeNull()- })+afterEach(() => {+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})- it('should render drawer presentation with plugin header content', () => {- openReadmePanel()+describe('ReadmePanel', () => {+ it.each(['drawer', 'dialog'] as const)(+ 'opens the %s from its entrance and closes the active panel',+ async (presentation) => {+ const user = userEvent.setup()+ const detail = createPluginDetail()+ render(+ <>+ <ReadmeEntrance pluginDetail={detail} presentation={presentation} />+ <ReadmePanel />+ </>,+ { queryClient: createQueryClient() },+ )+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(fetchMock).not.toHaveBeenCalled()++ await user.click(+ screen.getByRole('button', { name: 'plugin.readmeInfo.needHelpCheckReadme' }),+ )++ expect(+ await screen.findByRole('dialog', { name: 'plugin.readmeInfo.title' }),+ ).toBeInTheDocument()+ expect(+ await screen.findByRole('heading', { name: 'Plugin documentation' }),+ ).toBeInTheDocument()+ expect(screen.getByText(detail.name)).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'common.operation.close' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(useReadmePanelStore.getState().currentPanel).toBeUndefined()+ },+ )- renderWithQueryClient(<ReadmePanel />)+ it('shows loading until the requested Readme arrives', async () => {+ let resolveResponse!: (response: Response) => void+ fetchMock.mockReturnValue(+ new Promise<Response>((resolve) => {+ resolveResponse = resolve+ }),+ )+ openPanel()+ render(<ReadmePanel />, { queryClient: createQueryClient() })- expect(screen.getByRole('dialog')).toBeInTheDocument()- expect(screen.getByText('plugin.readmeInfo.title')).toBeInTheDocument()- expect(screen.getByTestId('detail-header')).toHaveAttribute('data-is-readme-view', 'true')- expect(screen.getByRole('dialog')).toHaveClass('data-[swipe-direction=left]:w-150')- })+ expect(screen.getByRole('progressbar', { name: 'common.loading' })).toBeInTheDocument()+ await act(async () => resolveResponse(Response.json({ readme: '# Loaded documentation' })))- it('should render dialog presentation when requested', () => {- openReadmePanel(createMockPluginDetail(), 'dialog')+ expect(await screen.findByRole('heading', { name: 'Loaded documentation' })).toBeInTheDocument()+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()+ })- renderWithQueryClient(<ReadmePanel />)+ it('shows the empty state when the server has no Readme', async () => {+ fetchMock.mockImplementation(async () => Response.json({ readme: '' }))+ openPanel()+ render(<ReadmePanel />, { queryClient: createQueryClient() })- expect(screen.getByRole('dialog')).toHaveClass('max-w-200')+ expect(await screen.findByText('plugin.readmeInfo.noReadmeAvailable')).toBeInTheDocument()+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()})- it('should close the active panel when close button is clicked', () => {- openReadmePanel()-- renderWithQueryClient(<ReadmePanel />)- fireEvent.click(screen.getByRole('button', { name: 'common.operation.close' }))+ it('shows a local error without a toast or automatic retries', async () => {+ const notifyError = vi.spyOn(toast, 'error')+ vi.spyOn(console, 'error').mockImplementation(() => {})+ fetchMock.mockImplementation(async () =>+ Response.json(+ { code: 'internal_server_error', message: 'Readme unavailable' },+ { status: 500 },+ ),+ )+ openPanel()+ render(<ReadmePanel />, { queryClient: createQueryClient() })- expect(useReadmePanelStore.getState().currentPanel).toBeUndefined()+ expect(await screen.findByText('plugin.readmeInfo.failedToFetch')).toBeInTheDocument()+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(notifyError).not.toHaveBeenCalled()})- it('should render loading, error, empty, and readme states from the readme query', () => {- openReadmePanel()- mockUsePluginReadme.mockReturnValue({- data: null,- isLoading: true,- error: null,- })- const { rerender } = renderWithQueryClient(<ReadmePanel />)- expect(screen.getByRole('progressbar')).toBeInTheDocument()+ it('does not fetch or stay loading when the panel has no plugin identifier', async () => {+ openPanel('')+ render(<ReadmePanel />, { queryClient: createQueryClient() })- mockUsePluginReadme.mockReturnValue({- data: null,- isLoading: false,- error: new Error('Failed to fetch'),- })- rerender(<ReadmePanel />)- expect(screen.getByText('plugin.readmeInfo.failedToFetch')).toBeInTheDocument()+ expect(await screen.findByText('plugin.readmeInfo.noReadmeAvailable')).toBeInTheDocument()+ expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()+ expect(fetchMock).not.toHaveBeenCalled()+ })- mockUsePluginReadme.mockReturnValue({- data: { readme: '' },- isLoading: false,- error: null,+ it('keeps plugin versions isolated when an earlier request finishes last', async () => {+ let resolveOldResponse!: (response: Response) => void+ const oldResponse = new Promise<Response>((resolve) => {+ resolveOldResponse = resolve})- rerender(<ReadmePanel />)- expect(screen.getByText('plugin.readmeInfo.noReadmeAvailable')).toBeInTheDocument()-- mockUsePluginReadme.mockReturnValue({- data: { readme: '# Test Readme Content' },- isLoading: false,- error: null,+ fetchMock.mockImplementation(async (input) => {+ const url = readmeURL(input)+ expect(url.pathname).toMatch(/\/workspaces\/current\/plugin\/readme$/)+ return url.searchParams.get('plugin_unique_identifier') === 'langgenius/test:1.0.0'+ ? oldResponse+ : Response.json({ readme: '# Version two' })})- rerender(<ReadmePanel />)- expect(screen.getByTestId('markdown-body')).toBeInTheDocument()- })-- it('should call usePluginReadme with the plugin identifier and selected language', () => {- openReadmePanel(- createMockPluginDetail({- plugin_unique_identifier: '[email protected]',- }),- )+ openPanel()+ render(<ReadmePanel />, { queryClient: createQueryClient() })+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))- renderWithQueryClient(<ReadmePanel />)+ openPanel('langgenius/test:2.0.0')+ expect(await screen.findByRole('heading', { name: 'Version two' })).toBeInTheDocument()+ await act(async () => resolveOldResponse(Response.json({ readme: '# Version one' })))- expect(mockUsePluginReadme).toHaveBeenCalledWith({- plugin_unique_identifier: '[email protected]',- language: 'en-US',- })+ expect(screen.getByRole('heading', { name: 'Version two' })).toBeInTheDocument()+ expect(screen.queryByRole('heading', { name: 'Version one' })).not.toBeInTheDocument()+ expect(fetchMock).toHaveBeenCalledTimes(2)})- it('should pass undefined language for zh-Hans locale', () => {- mockLanguage = 'zh-Hans'- openReadmePanel(- createMockPluginDetail({- plugin_unique_identifier: '[email protected]',- }),- )-- renderWithQueryClient(<ReadmePanel />)-- expect(mockUsePluginReadme).toHaveBeenCalledWith({- plugin_unique_identifier: '[email protected]',- language: undefined,+ it('uses the real locale conversion and reuses only the matching language cache', async () => {+ const requestedLanguages: Array<string | null> = []+ fetchMock.mockImplementation(async (input) => {+ const url = readmeURL(input)+ expect(url.searchParams.get('plugin_unique_identifier')).toBe('langgenius/test:1.0.0')+ const language = url.searchParams.get('language')+ requestedLanguages.push(language)+ return Response.json({+ readme:+ language === 'zh_Hans'+ ? '# 中文说明'+ : language === 'de_DE'+ ? '# Deutsche Dokumentation'+ : '# English Readme',+ })})- })+ openPanel()+ const { rerender } = render(<ReadmePanel />, { queryClient: createQueryClient() })+ expect(await screen.findByRole('heading', { name: 'English Readme' })).toBeInTheDocument()- it('should open correctly from ReadmeEntrance through the global host', () => {- const detail = createMockPluginDetail()-- renderWithQueryClient(- <>- <ReadmeEntrance pluginDetail={detail} />- <ReadmePanel />- </>,- )+ mockLocale = 'zh-Hans'+ rerender(<ReadmePanel />)+ expect(await screen.findByRole('heading', { name: '中文说明' })).toBeInTheDocument()+ expect(screen.queryByRole('heading', { name: 'English Readme' })).not.toBeInTheDocument()- fireEvent.click(screen.getByRole('button', { name: /plugin\.readmeInfo\.needHelpCheckReadme/ }))+ mockLocale = 'de-DE'+ rerender(<ReadmePanel />)+ expect(+ await screen.findByRole('heading', { name: 'Deutsche Dokumentation' }),+ ).toBeInTheDocument()- expect(screen.getByRole('dialog')).toBeInTheDocument()+ mockLocale = 'en-US'+ rerender(<ReadmePanel />)+ expect(await screen.findByRole('heading', { name: 'English Readme' })).toBeInTheDocument()+ expect(requestedLanguages).toEqual(['en_US', 'zh_Hans', 'de_DE'])})})diff --git a/web/app/components/plugins/readme-panel/content.tsx b/web/app/components/plugins/readme-panel/content.tsxindex 8eeab64b8d1..fb8277dc6de 100644--- a/web/app/components/plugins/readme-panel/content.tsx+++ b/web/app/components/plugins/readme-panel/content.tsx@@ -2,13 +2,14 @@import type { ReactNode } from 'react'import type { ReadmePanelState } from './store'+import { skipToken, useQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { Markdown } from '@/app/components/base/markdown'import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'import { resolveDatasourceIcon } from '@/app/components/rag-pipeline/utils/datasource-icon'import { useGetLanguage } from '@/context/i18n'-import { usePluginReadme } from '@/service/use-plugins'+import { consoleQuery } from '@/service/console'import Icon from '../card/base/card-icon'import Description from '../card/base/description'import OrgInfo from '../card/base/org-info'@@ -25,16 +26,24 @@ export function ReadmePanelContent({ detail, title, closeButton }: ReadmePanelCoconst { t } = useTranslation()const language = useLanguage()const locale = useGetLanguage()- const pluginUniqueIdentifier = detail.plugin_unique_identifier || ''+ const pluginUniqueIdentifier = detail.plugin_unique_identifierconst {data: readmeData,isLoading,error,- } = usePluginReadme({- plugin_unique_identifier: pluginUniqueIdentifier,- language: language === 'zh-Hans' ? undefined : language,- })+ } = useQuery(+ consoleQuery.workspaces.current.plugin.readme.get.queryOptions({+ input: pluginUniqueIdentifier+ ? {+ query: {+ plugin_unique_identifier: pluginUniqueIdentifier,+ language,+ },+ }+ : skipToken,+ }),+ )let readmeContent: ReactNodeif (isLoading) {diff --git a/web/service/console/query-policies.ts b/web/service/console/query-policies.tsindex e60387b65c7..0d2b1e1de25 100644--- a/web/service/console/query-policies.ts+++ b/web/service/console/query-policies.ts@@ -24,6 +24,21 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {},workspaces: {current: {+ plugin: {+ readme: {+ get: {+ queryOptions: {+ context: { silent: true },+ retry: false,+ },+ },+ },+ asset: {+ get: {+ queryOptions: { context: { silent: true } },+ },+ },+ },endpoints: {post: {mutationOptions: {diff --git a/web/service/use-plugins.ts b/web/service/use-plugins.tsindex 94beb197847..685dea548f5 100644--- a/web/service/use-plugins.ts+++ b/web/service/use-plugins.ts@@ -1529,44 +1529,3 @@ export const useFetchDynamicOptions = (}),})}--export const usePluginReadme = ({- plugin_unique_identifier,- language,-}: {- plugin_unique_identifier: string- language?: string-}) => {- return useQuery({- queryKey: ['pluginReadme', plugin_unique_identifier, language],- queryFn: () =>- get<{ readme: string }>(- '/workspaces/current/plugin/readme',- { params: { plugin_unique_identifier, language } },- { silent: true },- ),- enabled: !!plugin_unique_identifier,- retry: 0,- })-}--export const usePluginReadmeAsset = ({- file_name,- plugin_unique_identifier,-}: {- file_name?: string- plugin_unique_identifier?: string-}) => {- const normalizedFileName = file_name?.replace(/^\.\/_assets\//, '').replace(/^_assets\//, '')- const isAssetFile = file_name?.startsWith('./_assets') || file_name?.startsWith('_assets')- return useQuery({- queryKey: ['pluginReadmeAsset', plugin_unique_identifier, normalizedFileName],- queryFn: () =>- get<Blob>(- '/workspaces/current/plugin/asset',- { params: { plugin_unique_identifier, file_name: normalizedFileName } },- { silent: true },- ),- enabled: !!plugin_unique_identifier && !!isAssetFile,- })-}