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
fix(marketplace): fix preview overlay and image clipboard actions (#42411)
Coding On Stare18c171f74c1
diff --git a/knip.config.ts b/knip.config.tsindex 939a3143ac2..4cf2444d674 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -17,6 +17,7 @@ const config: KnipConfig = {'plugins/eslint/index.js',// Public surface consumed by the standalone Marketplace host.// The `!` suffix keeps these entries in `knip --production`.+ 'app/components/plugins/marketplace/detail-dialog/image-preview-message.ts!','app/components/plugins/marketplace/standalone/server.ts!','app/components/plugins/marketplace/standalone/client.ts!',],diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex e9734a65754..2ffecd2e868 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -1444,9 +1444,6 @@"web/app/components/base/image-uploader/image-preview.tsx": {"jsx-a11y/no-static-element-interactions": {"count": 1- },- "typescript/no-explicit-any": {- "count": 1}},"web/app/components/base/image-uploader/utils.ts": {diff --git a/web/app/components/base/image-gallery/__tests__/index.spec.tsx b/web/app/components/base/image-gallery/__tests__/index.spec.tsxindex 873a1a8dd39..7ce23a2df00 100644--- a/web/app/components/base/image-gallery/__tests__/index.spec.tsx+++ b/web/app/components/base/image-gallery/__tests__/index.spec.tsx@@ -10,6 +10,30 @@ vi.mock('react-i18next', () =>)describe('ImageGallery', () => {+ it('notifies the embedding owner while a preview is open, including unmount cleanup', async () => {+ const user = userEvent.setup()+ const onPreviewOpenChange = vi.fn()+ const { unmount } = render(+ <ImageGallery+ srcs={['https://example.com/image.png']}+ onPreviewOpenChange={onPreviewOpenChange}+ />,+ )++ expect(onPreviewOpenChange).not.toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: 'Preview image 1 of 1' }))+ expect(onPreviewOpenChange).toHaveBeenLastCalledWith(true)++ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(onPreviewOpenChange).toHaveBeenLastCalledWith(false)++ await user.click(screen.getByRole('button', { name: 'Preview image 1 of 1' }))+ expect(onPreviewOpenChange).toHaveBeenLastCalledWith(true)+ unmount()+ expect(onPreviewOpenChange).toHaveBeenLastCalledWith(false)+ })+it('previews the selected image and closes on Escape', async () => {const user = userEvent.setup()render(@@ -29,6 +53,30 @@ describe('ImageGallery', () => {})})+ it('releases and restores the embedding owner across page navigation', async () => {+ const user = userEvent.setup()+ const onPreviewOpenChange = vi.fn()+ render(+ <ImageGallery+ srcs={['https://example.com/image.png']}+ onPreviewOpenChange={onPreviewOpenChange}+ />,+ )+ await user.click(screen.getByRole('button', { name: 'Preview image 1 of 1' }))++ fireEvent(window, new Event('pagehide'))+ expect(onPreviewOpenChange).toHaveBeenLastCalledWith(false)++ fireEvent(window, new Event('pageshow'))+ expect(onPreviewOpenChange).toHaveBeenLastCalledWith(true)++ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ onPreviewOpenChange.mockClear()+ fireEvent(window, new Event('pageshow'))+ expect(onPreviewOpenChange).not.toHaveBeenCalled()+ })+it('removes an image that fails to load', () => {render(<ImageGallery srcs={['https://example.com/broken.png']} />)diff --git a/web/app/components/base/image-gallery/index.tsx b/web/app/components/base/image-gallery/index.tsxindex 62147bbf087..c713ae05f07 100644--- a/web/app/components/base/image-gallery/index.tsx+++ b/web/app/components/base/image-gallery/index.tsx@@ -2,13 +2,14 @@import type { FC } from 'react'import { cn } from '@langgenius/dify-ui/cn'import * as React from 'react'-import { useState } from 'react'+import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import ImagePreview from '@/app/components/base/image-uploader/image-preview'import s from './style.module.css'type Props = Readonly<{srcs: string[]+ onPreviewOpenChange?: (open: boolean) => void}>const getWidthStyle = (imgNum: number) => {@@ -29,9 +30,27 @@ const getWidthStyle = (imgNum: number) => {}}-const ImageGallery: FC<Props> = ({ srcs }) => {+const ImageGallery: FC<Props> = ({ srcs, onPreviewOpenChange }) => {const { t } = useTranslation('common')const [imagePreviewUrl, setImagePreviewUrl] = useState('')+ const isPreviewOpen = Boolean(imagePreviewUrl)++ // Synchronize embedding surfaces with the preview's lifetime, including+ // navigation that unmounts the gallery before the preview is dismissed.+ useEffect(() => {+ if (!isPreviewOpen || !onPreviewOpenChange) return++ onPreviewOpenChange(true)+ const handlePageHide = () => onPreviewOpenChange(false)+ const handlePageShow = () => onPreviewOpenChange(true)+ window.addEventListener('pagehide', handlePageHide)+ window.addEventListener('pageshow', handlePageShow)+ return () => {+ window.removeEventListener('pagehide', handlePageHide)+ window.removeEventListener('pageshow', handlePageShow)+ onPreviewOpenChange(false)+ }+ }, [isPreviewOpen, onPreviewOpenChange])const imgNum = srcs.lengthconst imgStyle = getWidthStyle(imgNum)diff --git a/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsx b/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsxindex 19441eef57b..66a7cf69f8a 100644--- a/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsx+++ b/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsx@@ -49,6 +49,12 @@ describe('ImagePreview', () => {beforeEach(() => {vi.clearAllMocks()+ vi.stubGlobal(+ 'fetch',+ vi+ .fn()+ .mockImplementation(async () => new Response(new Blob(['image'], { type: 'image/png' }))),+ )if (!navigator.clipboard) {Object.defineProperty(globalThis.navigator, 'clipboard', {@@ -75,7 +81,7 @@ describe('ImagePreview', () => {})globalThis.ClipboardItem = class {- constructor(public readonly data: Record<string, Blob>) {}+ constructor(public readonly data: Record<string, Blob | Promise<Blob>>) {}} as unknown as typeof ClipboardItemvi.spyOn(window, 'open').mockImplementation((...args: Parameters<Window['open']>) => {return mocks.windowOpen(...args)@@ -85,6 +91,7 @@ describe('ImagePreview', () => {afterEach(() => {globalThis.ClipboardItem = originalClipboardItemvi.restoreAllMocks()+ vi.unstubAllGlobals()})describe('Rendering', () => {@@ -289,21 +296,18 @@ describe('ImagePreview', () => {})describe('Action Buttons', () => {- it('should open valid url in new tab', async () => {- const user = userEvent.setup()- render(- <ImagePreview- url="https://example.com/image.png"- title="Preview Image"- onCancel={vi.fn()}- />,- )+ it.each(['https://example.com/image.png', '/image-proxy/github/example'])(+ 'should open valid url %s in new tab',+ async (url) => {+ const user = userEvent.setup()+ render(<ImagePreview url={url} title="Preview Image" onCancel={vi.fn()} />)- const openInTabButton = getOpenInTabButton()- await user.click(openInTabButton)+ const openInTabButton = getOpenInTabButton()+ await user.click(openInTabButton)- expect(mocks.windowOpen).toHaveBeenCalledWith('https://example.com/image.png', '_blank')- })+ expect(mocks.windowOpen).toHaveBeenCalledWith(url, '_blank')+ },+ )it('should open data image by writing to popup window document', async () => {const user = userEvent.setup()@@ -336,7 +340,7 @@ describe('ImagePreview', () => {})})- it('should fall back to download and show info toast when clipboard copy fails', async () => {+ it('keeps the preview open and reports clipboard denial without downloading or navigating', async () => {const user = userEvent.setup()const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})mocks.clipboardWrite.mockRejectedValue(new Error('copy failed'))@@ -346,21 +350,116 @@ describe('ImagePreview', () => {const copyButton = getCopyButton()await user.click(copyButton)- await waitFor(() => {- expect(mocks.downloadUrl).toHaveBeenCalledWith({- url: dataImage,- fileName: 'Preview Image.png',- })- })- expect(mocks.notify).toHaveBeenCalledWith(- expect.objectContaining({- type: 'info',+ await waitFor(() =>+ expect(mocks.notify).toHaveBeenCalledWith({+ type: 'error',+ message: 'common.operation.imageCopyFailed',}),)+ expect(mocks.downloadUrl).not.toHaveBeenCalled()+ expect(mocks.windowOpen).not.toHaveBeenCalled()+ expect(getOverlay()).toBeInTheDocument()expect(consoleErrorSpy).toHaveBeenCalled()consoleErrorSpy.mockRestore()})+ it('copies a remote PNG and starts the clipboard write before the image fetch resolves', async () => {+ const user = userEvent.setup()+ const png = new Blob(['png bytes'], { type: 'image/png' })+ let resolveFetch!: (response: Response) => void+ const fetchMock = vi.fn(+ () =>+ new Promise<Response>((resolve) => {+ resolveFetch = resolve+ }),+ )+ vi.stubGlobal('fetch', fetchMock)+ let copiedBlob: Blob | undefined+ mocks.clipboardWrite.mockImplementation(async ([item]) => {+ copiedBlob = await (item as unknown as { data: Record<string, Promise<Blob>> }).data[+ 'image/png'+ ]+ })+ render(+ <ImagePreview+ url="https://example.com/image.png"+ title="Preview Image"+ onCancel={vi.fn()}+ />,+ )++ await user.click(getCopyButton())++ expect(mocks.clipboardWrite).toHaveBeenCalledTimes(1)+ expect(copiedBlob).toBeUndefined()+ resolveFetch(new Response(png))+ await waitFor(() =>+ expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' })),+ )+ expect(copiedBlob?.type).toBe('image/png')+ expect(await copiedBlob?.text()).toBe('png bytes')+ expect(mocks.downloadUrl).not.toHaveBeenCalled()+ })++ it('converts a JPEG to PNG instead of labelling JPEG bytes as PNG', async () => {+ const user = userEvent.setup()+ const jpeg = new Blob(['jpeg bytes'], { type: 'image/jpeg' })+ const png = new Blob(['encoded png'], { type: 'image/png' })+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(jpeg)))+ const bitmap = { width: 12, height: 8, close: vi.fn() }+ vi.stubGlobal('createImageBitmap', vi.fn().mockResolvedValue(bitmap))+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({+ drawImage: vi.fn(),+ } as unknown as CanvasRenderingContext2D)+ vi.spyOn(HTMLCanvasElement.prototype, 'toBlob').mockImplementation((callback) =>+ callback(png),+ )+ let copiedBlob: Blob | undefined+ mocks.clipboardWrite.mockImplementation(async ([item]) => {+ copiedBlob = await (item as unknown as { data: Record<string, Promise<Blob>> }).data[+ 'image/png'+ ]+ })+ render(+ <ImagePreview+ url="https://example.com/image.jpg"+ title="Preview Image"+ onCancel={vi.fn()}+ />,+ )++ await user.click(getCopyButton())++ await waitFor(() => expect(copiedBlob).toBe(png))+ expect(bitmap.close).toHaveBeenCalled()+ expect(mocks.downloadUrl).not.toHaveBeenCalled()+ })++ it('reports an image fetch failure without leaving the preview', async () => {+ const user = userEvent.setup()+ vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')))+ mocks.clipboardWrite.mockImplementation(async ([item]) => {+ await (item as unknown as { data: Record<string, Promise<Blob>> }).data['image/png']+ })+ render(+ <ImagePreview+ url="https://example.com/image.png"+ title="Preview Image"+ onCancel={vi.fn()}+ />,+ )++ await user.click(getCopyButton())++ await waitFor(() =>+ expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' })),+ )+ expect(mocks.downloadUrl).not.toHaveBeenCalled()+ expect(mocks.windowOpen).not.toHaveBeenCalled()+ expect(getOverlay()).toBeInTheDocument()+ })+it('should copy image and show success toast', async () => {const user = userEvent.setup()mocks.clipboardWrite.mockResolvedValue()@@ -379,24 +478,21 @@ describe('ImagePreview', () => {)})- it('should call download action for valid url', async () => {- const user = userEvent.setup()- render(- <ImagePreview- url="https://example.com/image.png"- title="Preview Image"- onCancel={vi.fn()}- />,- )- const downloadButton = getDownloadButton()- await user.click(downloadButton)+ it.each(['https://example.com/image.png', '/image-proxy/github/example'])(+ 'should download valid url %s',+ async (url) => {+ const user = userEvent.setup()+ render(<ImagePreview url={url} title="Preview Image" onCancel={vi.fn()} />)+ const downloadButton = getDownloadButton()+ await user.click(downloadButton)- expect(mocks.downloadUrl).toHaveBeenCalledWith({- url: 'https://example.com/image.png',- fileName: 'Preview Image',- target: '_blank',- })- })+ expect(mocks.downloadUrl).toHaveBeenCalledWith({+ url,+ fileName: 'Preview Image',+ target: '_blank',+ })+ },+ )it('should show error toast for invalid download url', async () => {const user = userEvent.setup()diff --git a/web/app/components/base/image-uploader/image-preview.tsx b/web/app/components/base/image-uploader/image-preview.tsxindex 80593605269..97328610afa 100644--- a/web/app/components/base/image-uploader/image-preview.tsx+++ b/web/app/components/base/image-uploader/image-preview.tsx@@ -25,6 +25,31 @@ const isBase64 = (str: string): boolean => {}}+const fetchImageAsPng = async (url: string): Promise<Blob> => {+ const response = await fetch(url)+ if (!response.ok) throw new Error('Unable to load image')+ const blob = await response.blob()+ if (blob.type === 'image/png') return blob++ const bitmap = await createImageBitmap(blob)+ try {+ const canvas = document.createElement('canvas')+ canvas.width = bitmap.width+ canvas.height = bitmap.height+ const context = canvas.getContext('2d')+ if (!context) throw new Error('Unable to convert image')+ context.drawImage(bitmap, 0, 0)+ return await new Promise<Blob>((resolve, reject) => {+ canvas.toBlob((png) => {+ if (png) resolve(png)+ else reject(new Error('Unable to encode image'))+ }, 'image/png')+ })+ } finally {+ bitmap.close()+ }+}+const ImagePreview: FC<ImagePreviewProps> = ({ url, title, onCancel, onPrev, onNext }) => {const { t } = useTranslation()const [scale, setScale] = useState(1)@@ -36,7 +61,7 @@ const ImagePreview: FC<ImagePreviewProps> = ({ url, title, onCancel, onPrev, onNconst openInNewTab = () => {// Open in a new window, considering the case when the page is inside an iframe- if (url.startsWith('http') || url.startsWith('https')) {+ if (url.startsWith('http') || url.startsWith('/')) {window.open(url, '_blank')} else if (url.startsWith('data:image')) {// Base64 image@@ -49,7 +74,7 @@ const ImagePreview: FC<ImagePreviewProps> = ({ url, title, onCancel, onPrev, onNconst downloadImage = () => {// Open in a new window, considering the case when the page is inside an iframe- if (url.startsWith('http') || url.startsWith('https') || url.startsWith('data:image')) {+ if (url.startsWith('http') || url.startsWith('/') || url.startsWith('data:image')) {downloadUrl({ url, fileName: title, target: '_blank' })return}@@ -69,31 +94,19 @@ const ImagePreview: FC<ImagePreviewProps> = ({ url, title, onCancel, onPrev, onN})}- const imageBase64ToBlob = (base64: string, type = 'image/png'): Blob => {- const byteCharacters = atob(base64)- const byteArrays = []-- for (let offset = 0; offset < byteCharacters.length; offset += 512) {- const slice = byteCharacters.slice(offset, offset + 512)- const byteNumbers = Array.from({ length: slice.length })- for (let i = 0; i < slice.length; i++) byteNumbers[i] = slice.charCodeAt(i)-- const byteArray = new Uint8Array(byteNumbers as any)- byteArrays.push(byteArray)- }-- return new Blob(byteArrays, { type })- }-const imageCopy = useCallback(() => {const shareImage = async () => {try {- const base64Data = url.split(',')[1]- const blob = imageBase64ToBlob(base64Data!, 'image/png')+ if (!navigator.clipboard?.write || typeof ClipboardItem === 'undefined')+ throw new Error('Image clipboard is unavailable')+ const png = fetchImageAsPng(isBase64(url) ? `data:image/png;base64,${url}` : url)+ // Handle a rejected fetch even if clipboard permission is denied before+ // the browser consumes the item. Keep write in the click gesture for Safari.+ void png.catch(noop)await navigator.clipboard.write([new ClipboardItem({- [blob.type]: blob,+ 'image/png': png,}),])setIsCopied(true)@@ -102,13 +115,12 @@ const ImagePreview: FC<ImagePreviewProps> = ({ url, title, onCancel, onPrev, onN} catch (err) {console.error('Failed to copy image:', err)- downloadUrl({ url, fileName: `${title}.png` })-- toast.info(t(($) => $['operation.imageDownloaded'], { ns: 'common' }))+ setIsCopied(false)+ toast.error(t(($) => $['operation.imageCopyFailed'], { ns: 'common' }))}}shareImage()- }, [t, title, url])+ }, [t, url])const handleWheel = useCallback((e: React.WheelEvent<HTMLDivElement>) => {if (e.deltaY < 0) zoomIn()diff --git a/web/app/components/plugins/marketplace/detail-dialog/__tests__/frame.spec.tsx b/web/app/components/plugins/marketplace/detail-dialog/__tests__/frame.spec.tsxnew file mode 100644index 00000000000..5d9635ae555--- /dev/null+++ b/web/app/components/plugins/marketplace/detail-dialog/__tests__/frame.spec.tsx@@ -0,0 +1,160 @@+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { describe, expect, it, vi } from 'vitest'+import MarketplaceDetailDialogFrame from '../frame'++const title = 'Plugin details'+const src = 'about:blank?plugin=first'+const closeName = 'common.operation.close'+const previewMessage = { type: 'dify-marketplace:image-preview', open: true }++const getFrame = () => screen.getByTitle(title) as HTMLIFrameElement++function sendMessage(data: unknown, options?: MessageEventInit) {+ fireEvent(+ window,+ new MessageEvent('message', {+ data,+ origin: 'null',+ source: getFrame().contentWindow,+ ...options,+ }),+ )+}++describe('MarketplaceDetailDialogFrame image preview', () => {+ it('lets the preview own closing until it closes, even without another message handler', async () => {+ const user = userEvent.setup()+ const onOpenChange = vi.fn()+ render(+ <MarketplaceDetailDialogFrame open src={src} title={title} onOpenChange={onOpenChange} />,+ )++ fireEvent.load(getFrame())+ sendMessage(previewMessage)++ expect(screen.queryByRole('button', { name: closeName })).not.toBeInTheDocument()+ expect(screen.getByRole('dialog', { name: title })).toBeInTheDocument()+ expect(onOpenChange).not.toHaveBeenCalled()++ sendMessage({ ...previewMessage, open: false })+ await user.click(screen.getByRole('button', { name: closeName }))+ expect(onOpenChange).toHaveBeenCalledWith(false)+ })++ it('accepts preview updates only from this iframe and its expected origin', () => {+ render(<MarketplaceDetailDialogFrame open src={src} title={title} onOpenChange={vi.fn()} />)++ sendMessage(previewMessage, { origin: 'https://another-marketplace.example' })+ expect(screen.getByRole('button', { name: closeName })).toBeInTheDocument()++ sendMessage(previewMessage, { source: window })+ expect(screen.getByRole('button', { name: closeName })).toBeInTheDocument()++ sendMessage(previewMessage)+ expect(screen.queryByRole('button', { name: closeName })).not.toBeInTheDocument()++ sendMessage({ ...previewMessage, open: false }, { source: window })+ expect(screen.queryByRole('button', { name: closeName })).not.toBeInTheDocument()+ })++ it.each([+ null,+ 'dify-marketplace:image-preview',+ { type: 'dify-marketplace:image-preview' },+ { type: 'dify-marketplace:image-preview', open: 'true' },+ { type: 'dify-marketplace:image-preview', open: 1 },+ { type: 'dify-marketplace:another-message', open: true },+ ])('ignores malformed or unrelated preview data: %j', (data) => {+ render(<MarketplaceDetailDialogFrame open src={src} title={title} onOpenChange={vi.fn()} />)++ sendMessage(data)+ expect(screen.getByRole('button', { name: closeName })).toBeInTheDocument()+ })++ it('continues forwarding other trusted marketplace messages and replies', () => {+ const request = {+ type: 'dify-marketplace:install-plugin',+ pluginUniqueIdentifier: 'test/plugin:1',+ }+ const response = { type: 'dify-marketplace:install-plugin-status', status: 'success' }+ const onMessage = vi.fn((_data, reply) => reply(response))+ render(+ <MarketplaceDetailDialogFrame+ open+ src={src}+ title={title}+ onMessage={onMessage}+ onOpenChange={vi.fn()}+ />,+ )+ const postMessage = vi.spyOn(getFrame().contentWindow!, 'postMessage')++ sendMessage(request)++ expect(onMessage).toHaveBeenCalledWith(request, expect.any(Function))+ expect(postMessage).toHaveBeenCalledWith(response, 'null')+ })++ it('keeps an active preview above the close button when the iframe load arrives after fallback reveal', async () => {+ vi.useFakeTimers()+ try {+ render(<MarketplaceDetailDialogFrame open src={src} title={title} onOpenChange={vi.fn()} />)+ await act(() => vi.advanceTimersByTimeAsync(15_000))+ expect(getFrame()).not.toHaveAttribute('inert')++ sendMessage(previewMessage)+ expect(screen.queryByRole('button', { name: closeName })).not.toBeInTheDocument()++ fireEvent.load(getFrame())++ expect(screen.queryByRole('button', { name: closeName })).not.toBeInTheDocument()+ } finally {+ vi.useRealTimers()+ }+ })++ it('starts another detail URL with its own close button', () => {+ const onOpenChange = vi.fn()+ const { rerender } = render(+ <MarketplaceDetailDialogFrame open src={src} title={title} onOpenChange={onOpenChange} />,+ )+ sendMessage(previewMessage)+ expect(screen.queryByRole('button', { name: closeName })).not.toBeInTheDocument()++ rerender(+ <MarketplaceDetailDialogFrame+ open+ src="about:blank?plugin=second"+ title={title}+ onOpenChange={onOpenChange}+ />,+ )++ expect(screen.getByRole('button', { name: closeName })).toBeInTheDocument()+ })++ it('restores the close button after the controlled details dialog closes and reopens', async () => {+ const onOpenChange = vi.fn()+ const { rerender } = render(+ <MarketplaceDetailDialogFrame open src={src} title={title} onOpenChange={onOpenChange} />,+ )+ sendMessage(previewMessage)+ expect(screen.queryByRole('button', { name: closeName })).not.toBeInTheDocument()++ rerender(+ <MarketplaceDetailDialogFrame+ open={false}+ src={src}+ title={title}+ onOpenChange={onOpenChange}+ />,+ )+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ rerender(+ <MarketplaceDetailDialogFrame open src={src} title={title} onOpenChange={onOpenChange} />,+ )++ expect(screen.getByRole('button', { name: closeName })).toBeInTheDocument()+ })+})diff --git a/web/app/components/plugins/marketplace/detail-dialog/frame.tsx b/web/app/components/plugins/marketplace/detail-dialog/frame.tsxindex ab31dcc31af..dd7a68f92da 100644--- a/web/app/components/plugins/marketplace/detail-dialog/frame.tsx+++ b/web/app/components/plugins/marketplace/detail-dialog/frame.tsx@@ -12,6 +12,7 @@ import {import { IconButton } from '@langgenius/dify-ui/icon-button'import { useEffect, useRef, useState } from 'react'import { useTranslation } from '#i18n'+import { isMarketplaceImagePreviewMessage } from './image-preview-message'type ReplyToMarketplaceFrame = (data: unknown) => void@@ -39,6 +40,12 @@ export default function MarketplaceDetailDialogFrame({const iframeRef = useRef<HTMLIFrameElement>(null)const closeButtonRef = useRef<HTMLButtonElement>(null)const [isLoading, setIsLoading] = useState(true)+ const [imagePreview, setImagePreview] = useState({ src, dialogOpen: open, open: false })++ // A controlled close/reopen or another detail URL starts a fresh frame+ // session, including when a close transition has not finished unmounting.+ if (imagePreview.src !== src || imagePreview.dialogOpen !== open)+ setImagePreview({ src, dialogOpen: open, open: false })useEffect(() => {if (!open) return@@ -48,14 +55,19 @@ export default function MarketplaceDetailDialogFrame({}, [open, src])useEffect(() => {- if (!open || !onMessage) return+ if (!open) returnconst marketplaceOrigin = new URL(src, window.location.href).originconst handleMessage = (event: MessageEvent) => {if (event.source !== iframeRef.current?.contentWindow || event.origin !== marketplaceOrigin)return- onMessage(event.data, (payload) => {+ if (isMarketplaceImagePreviewMessage(event.data)) {+ setImagePreview({ src, dialogOpen: open, open: event.data.open })+ return+ }++ onMessage?.(event.data, (payload) => {iframeRef.current?.contentWindow?.postMessage(payload, marketplaceOrigin)})}@@ -65,7 +77,10 @@ export default function MarketplaceDetailDialogFrame({}, [onMessage, open, src])const handleOpenChange = (nextOpen: boolean) => {- if (!nextOpen) setIsLoading(true)+ if (!nextOpen) {+ setIsLoading(true)+ setImagePreview({ src, dialogOpen: open, open: false })+ }onOpenChange(nextOpen)}@@ -119,18 +134,22 @@ export default function MarketplaceDetailDialogFrame({src={src}title={title}/>- <DialogClose- render={- <IconButton- ref={closeButtonRef}- aria-label={t(($) => $['operation.close'], { ns: 'common' })}- size="sm"- className="absolute top-5 right-5 z-10 size-8 rounded-lg"- >- <span aria-hidden className="i-ri-close-line size-4" />- </IconButton>- }- />+ {/* The image preview lives inside a different document, so its+ backdrop cannot cover this host control through z-index. */}+ {!imagePreview.open && (+ <DialogClose+ render={+ <IconButton+ ref={closeButtonRef}+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}+ size="sm"+ className="absolute top-5 right-5 z-10 size-8 rounded-lg"+ >+ <span aria-hidden className="i-ri-close-line size-4" />+ </IconButton>+ }+ />+ )}</DialogPopup></DialogPortal></Dialog>diff --git a/web/app/components/plugins/marketplace/detail-dialog/image-preview-message.ts b/web/app/components/plugins/marketplace/detail-dialog/image-preview-message.tsnew file mode 100644index 00000000000..eab1a778d8c--- /dev/null+++ b/web/app/components/plugins/marketplace/detail-dialog/image-preview-message.ts@@ -0,0 +1,19 @@+export const MARKETPLACE_IMAGE_PREVIEW_MESSAGE = 'dify-marketplace:image-preview'++export type MarketplaceImagePreviewMessage = {+ type: typeof MARKETPLACE_IMAGE_PREVIEW_MESSAGE+ open: boolean+}++export function isMarketplaceImagePreviewMessage(+ data: unknown,+): data is MarketplaceImagePreviewMessage {+ return (+ typeof data === 'object' &&+ data !== null &&+ 'type' in data &&+ data.type === MARKETPLACE_IMAGE_PREVIEW_MESSAGE &&+ 'open' in data &&+ typeof data.open === 'boolean'+ )+}diff --git a/web/i18n/ar-TN/common.json b/web/i18n/ar-TN/common.jsonindex e6243a6c028..a6455c71a31 100644--- a/web/i18n/ar-TN/common.json+++ b/web/i18n/ar-TN/common.json@@ -474,6 +474,7 @@"operation.fill": "ملء تلقائي","operation.format": "تنسيق","operation.imageCopied": "تم نسخ الصورة",+ "operation.imageCopyFailed": "تعذّر نسخ الصورة. يرجى تنزيلها بدلاً من ذلك.","operation.imageDownloaded": "تم تنزيل الصورة","operation.in": "في","operation.learnMore": "تعرف على المزيد",diff --git a/web/i18n/de-DE/common.json b/web/i18n/de-DE/common.jsonindex 0a5d56112fa..25907e54b99 100644--- a/web/i18n/de-DE/common.json+++ b/web/i18n/de-DE/common.json@@ -474,6 +474,7 @@"operation.fill": "Automatisch ausfüllen","operation.format": "Format","operation.imageCopied": "Kopiertes Bild",+ "operation.imageCopyFailed": "Das Bild konnte nicht kopiert werden. Bitte laden Sie es stattdessen herunter.","operation.imageDownloaded": "Bild heruntergeladen","operation.in": "in","operation.learnMore": "Mehr erfahren",diff --git a/web/i18n/en-US/common.json b/web/i18n/en-US/common.jsonindex cc3e1373db8..27418cea05d 100644--- a/web/i18n/en-US/common.json+++ b/web/i18n/en-US/common.json@@ -474,6 +474,7 @@"operation.fill": "Autofill","operation.format": "Format","operation.imageCopied": "Image copied",+ "operation.imageCopyFailed": "Could not copy the image. Please download it instead.","operation.imageDownloaded": "Image downloaded","operation.in": "in","operation.learnMore": "Learn more",diff --git a/web/i18n/es-ES/common.json b/web/i18n/es-ES/common.jsonindex 47c37b1d093..8000423afb7 100644--- a/web/i18n/es-ES/common.json+++ b/web/i18n/es-ES/common.json@@ -474,6 +474,7 @@"operation.fill": "Autocompletar","operation.format": "Formato","operation.imageCopied": "Imagen copiada",+ "operation.imageCopyFailed": "No se pudo copiar la imagen. Descárgala en su lugar.","operation.imageDownloaded": "Imagen descargada","operation.in": "en","operation.learnMore": "Aprender más",diff --git a/web/i18n/fa-IR/common.json b/web/i18n/fa-IR/common.jsonindex a22d747cffc..d3b439caf99 100644--- a/web/i18n/fa-IR/common.json+++ b/web/i18n/fa-IR/common.json@@ -474,6 +474,7 @@"operation.fill": "پر کردن خودکار","operation.format": "قالب","operation.imageCopied": "تصویر کپی شده",+ "operation.imageCopyFailed": "تصویر کپی نشد. لطفاً بهجای آن تصویر را دانلود کنید.","operation.imageDownloaded": "تصویر دانلود شد","operation.in": "در","operation.learnMore": "اطلاعات بیشتر",diff --git a/web/i18n/fr-FR/common.json b/web/i18n/fr-FR/common.jsonindex e1a261b03fb..1115008f6fd 100644--- a/web/i18n/fr-FR/common.json+++ b/web/i18n/fr-FR/common.json@@ -474,6 +474,7 @@"operation.fill": "Remplissage auto","operation.format": "Format","operation.imageCopied": "Image copied",+ "operation.imageCopyFailed": "Impossible de copier l’image. Veuillez la télécharger à la place.","operation.imageDownloaded": "Image téléchargée","operation.in": "dans","operation.learnMore": "En savoir plus",diff --git a/web/i18n/hi-IN/common.json b/web/i18n/hi-IN/common.jsonindex c8787e35bdc..e282692a184 100644--- a/web/i18n/hi-IN/common.json+++ b/web/i18n/hi-IN/common.json@@ -474,6 +474,7 @@"operation.fill": "ऑटोफिल","operation.format": "फॉर्मेट","operation.imageCopied": "कॉपी की गई छवि",+ "operation.imageCopyFailed": "इमेज कॉपी नहीं हो सकी। कृपया इसे डाउनलोड करें।","operation.imageDownloaded": "छवि डाउनलोड की गई","operation.in": "में","operation.learnMore": "अधिक जानें",diff --git a/web/i18n/id-ID/common.json b/web/i18n/id-ID/common.jsonindex fc00999beb7..805ffd9168c 100644--- a/web/i18n/id-ID/common.json+++ b/web/i18n/id-ID/common.json@@ -474,6 +474,7 @@"operation.fill": "Isi otomatis","operation.format": "Format","operation.imageCopied": "Gambar yang disalin",+ "operation.imageCopyFailed": "Gambar tidak dapat disalin. Silakan unduh sebagai gantinya.","operation.imageDownloaded": "Gambar diunduh","operation.in": "di","operation.learnMore": "Pelajari lebih lanjut",diff --git a/web/i18n/it-IT/common.json b/web/i18n/it-IT/common.jsonindex 37bbb62203f..1d92c4abf83 100644--- a/web/i18n/it-IT/common.json+++ b/web/i18n/it-IT/common.json@@ -474,6 +474,7 @@"operation.fill": "Compilazione automatica","operation.format": "Formato","operation.imageCopied": "Immagine copiata",+ "operation.imageCopyFailed": "Impossibile copiare l’immagine. Scaricala invece.","operation.imageDownloaded": "Immagine scaricata","operation.in": "in","operation.learnMore": "Scopri di più",diff --git a/web/i18n/ja-JP/common.json b/web/i18n/ja-JP/common.jsonindex 8b8ac21597b..ac269c6421c 100644--- a/web/i18n/ja-JP/common.json+++ b/web/i18n/ja-JP/common.json@@ -474,6 +474,7 @@"operation.fill": "自動入力","operation.format": "フォーマット","operation.imageCopied": "コピーした画像",+ "operation.imageCopyFailed": "画像をコピーできませんでした。代わりにダウンロードしてください。","operation.imageDownloaded": "画像がダウンロードされました","operation.in": "中","operation.learnMore": "詳細はこちら",diff --git a/web/i18n/ko-KR/common.json b/web/i18n/ko-KR/common.jsonindex 2bc8745564d..cea78dacec9 100644--- a/web/i18n/ko-KR/common.json+++ b/web/i18n/ko-KR/common.json@@ -474,6 +474,7 @@"operation.fill": "자동 입력","operation.format": "형식","operation.imageCopied": "복사된 이미지",+ "operation.imageCopyFailed": "이미지를 복사할 수 없습니다. 대신 다운로드해 주세요.","operation.imageDownloaded": "이미지 다운로드됨","operation.in": "안으로","operation.learnMore": "자세히 알아보기",diff --git a/web/i18n/lo-LA/common.json b/web/i18n/lo-LA/common.jsonindex 1cf54041176..ae8482d0221 100644--- a/web/i18n/lo-LA/common.json+++ b/web/i18n/lo-LA/common.json@@ -474,6 +474,7 @@"operation.fill": "ຕື່ມຂໍ້ມູນອັດຕະໂນມັດ","operation.format": "ຈັດຮູບແບບ","operation.imageCopied": "ຄັດລອກຮູບແລ້ວ",+ "operation.imageCopyFailed": "ບໍ່ສາມາດສຳເນົາຮູບພາບໄດ້. ກະລຸນາດາວໂຫຼດຮູບພາບແທນ.","operation.imageDownloaded": "ດາວໂຫຼດຮູບແລ້ວ","operation.in": "ໃນ","operation.learnMore": "ຮຽນຮູ້ເພີ່ມເຕີມ",diff --git a/web/i18n/nl-NL/common.json b/web/i18n/nl-NL/common.jsonindex 401e64aa3a6..94140469646 100644--- a/web/i18n/nl-NL/common.json+++ b/web/i18n/nl-NL/common.json@@ -474,6 +474,7 @@"operation.fill": "Automatisch invullen","operation.format": "Format","operation.imageCopied": "Image copied",+ "operation.imageCopyFailed": "De afbeelding kon niet worden gekopieerd. Download deze in plaats daarvan.","operation.imageDownloaded": "Image downloaded","operation.in": "in","operation.learnMore": "Meer informatie",diff --git a/web/i18n/pl-PL/common.json b/web/i18n/pl-PL/common.jsonindex 0b373763e03..1736e5eb631 100644--- a/web/i18n/pl-PL/common.json+++ b/web/i18n/pl-PL/common.json@@ -474,6 +474,7 @@"operation.fill": "Autouzupełnianie","operation.format": "Format","operation.imageCopied": "Skopiowany obraz",+ "operation.imageCopyFailed": "Nie można skopiować obrazu. Zamiast tego pobierz go.","operation.imageDownloaded": "Obraz pobrany","operation.in": "w","operation.learnMore": "Dowiedz się więcej",diff --git a/web/i18n/pt-BR/common.json b/web/i18n/pt-BR/common.jsonindex e300285b72e..f3bd441e5d1 100644--- a/web/i18n/pt-BR/common.json+++ b/web/i18n/pt-BR/common.json@@ -474,6 +474,7 @@"operation.fill": "Preenchimento automático","operation.format": "Formato","operation.imageCopied": "Imagem copiada",+ "operation.imageCopyFailed": "Não foi possível copiar a imagem. Baixe-a em vez disso.","operation.imageDownloaded": "Imagem baixada","operation.in": "em","operation.learnMore": "Saiba mais",diff --git a/web/i18n/ro-RO/common.json b/web/i18n/ro-RO/common.jsonindex 88b9d6f491a..92f3d7c821e 100644--- a/web/i18n/ro-RO/common.json+++ b/web/i18n/ro-RO/common.json@@ -474,6 +474,7 @@"operation.fill": "Completare automată","operation.format": "Format","operation.imageCopied": "Imagine copiată",+ "operation.imageCopyFailed": "Imaginea nu a putut fi copiată. Descărcați-o în schimb.","operation.imageDownloaded": "Imagine descărcată","operation.in": "în","operation.learnMore": "Află mai multe",diff --git a/web/i18n/ru-RU/common.json b/web/i18n/ru-RU/common.jsonindex 6a40dc22040..0be7d670a74 100644--- a/web/i18n/ru-RU/common.json+++ b/web/i18n/ru-RU/common.json@@ -474,6 +474,7 @@"operation.fill": "Автозаполнение","operation.format": "Формат","operation.imageCopied": "Скопированное изображение",+ "operation.imageCopyFailed": "Не удалось скопировать изображение. Попробуйте скачать его.","operation.imageDownloaded": "Изображение загружено","operation.in": "в","operation.learnMore": "Узнать больше",diff --git a/web/i18n/sl-SI/common.json b/web/i18n/sl-SI/common.jsonindex c1bf276b01d..62feb5826a0 100644--- a/web/i18n/sl-SI/common.json+++ b/web/i18n/sl-SI/common.json@@ -474,6 +474,7 @@"operation.fill": "Samodejno izpolni","operation.format": "Format","operation.imageCopied": "Kopirana slika",+ "operation.imageCopyFailed": "Slike ni bilo mogoče kopirati. Namesto tega jo prenesite.","operation.imageDownloaded": "Slika prenesena","operation.in": "v","operation.learnMore": "Izvedi več",diff --git a/web/i18n/th-TH/common.json b/web/i18n/th-TH/common.jsonindex a417db74dea..f5818f03845 100644--- a/web/i18n/th-TH/common.json+++ b/web/i18n/th-TH/common.json@@ -474,6 +474,7 @@"operation.fill": "กรอกอัตโนมัติ","operation.format": "รูปแบบ","operation.imageCopied": "ภาพที่คัดลอก",+ "operation.imageCopyFailed": "ไม่สามารถคัดลอกรูปภาพได้ โปรดดาวน์โหลดรูปภาพแทน","operation.imageDownloaded": "ดาวน์โหลดรูปภาพแล้ว","operation.in": "ใน","operation.learnMore": "ศึกษาเพิ่มเติม",diff --git a/web/i18n/tr-TR/common.json b/web/i18n/tr-TR/common.jsonindex 6ac2294a338..b48035b0e71 100644--- a/web/i18n/tr-TR/common.json+++ b/web/i18n/tr-TR/common.json@@ -474,6 +474,7 @@"operation.fill": "Otomatik doldur","operation.format": "Format","operation.imageCopied": "Kopyalanan görüntü",+ "operation.imageCopyFailed": "Görüntü kopyalanamadı. Lütfen bunun yerine indirin.","operation.imageDownloaded": "Resim indirildi","operation.in": "içinde","operation.learnMore": "Daha fazla bilgi",diff --git a/web/i18n/uk-UA/common.json b/web/i18n/uk-UA/common.jsonindex 1df899ae444..b85bba18130 100644--- a/web/i18n/uk-UA/common.json+++ b/web/i18n/uk-UA/common.json@@ -474,6 +474,7 @@"operation.fill": "Автозаповнення","operation.format": "Формат","operation.imageCopied": "Скопійоване зображення",+ "operation.imageCopyFailed": "Не вдалося скопіювати зображення. Спробуйте завантажити його.","operation.imageDownloaded": "Зображення завантажено","operation.in": "В","operation.learnMore": "Дізнатися більше",diff --git a/web/i18n/vi-VN/common.json b/web/i18n/vi-VN/common.jsonindex 0416f8c1ac4..3bf169e1089 100644--- a/web/i18n/vi-VN/common.json+++ b/web/i18n/vi-VN/common.json@@ -474,6 +474,7 @@"operation.fill": "Tự động điền","operation.format": "Định dạng","operation.imageCopied": "Hình ảnh sao chép",+ "operation.imageCopyFailed": "Không thể sao chép hình ảnh. Vui lòng tải ảnh xuống.","operation.imageDownloaded": "Hình ảnh đã được tải xuống","operation.in": "trong","operation.learnMore": "Tìm hiểu thêm",diff --git a/web/i18n/zh-Hans/common.json b/web/i18n/zh-Hans/common.jsonindex ce86a05b3cd..41929210309 100644--- a/web/i18n/zh-Hans/common.json+++ b/web/i18n/zh-Hans/common.json@@ -474,6 +474,7 @@"operation.fill": "一键填入","operation.format": "格式化","operation.imageCopied": "图片已复制",+ "operation.imageCopyFailed": "无法复制图片,请尝试下载图片。","operation.imageDownloaded": "图片已下载","operation.in": "在","operation.learnMore": "了解更多",diff --git a/web/i18n/zh-Hant/common.json b/web/i18n/zh-Hant/common.jsonindex d28f1066dac..9ffedb2a0fc 100644--- a/web/i18n/zh-Hant/common.json+++ b/web/i18n/zh-Hant/common.json@@ -474,6 +474,7 @@"operation.fill": "一鍵填入","operation.format": "格式","operation.imageCopied": "複製的圖片",+ "operation.imageCopyFailed": "無法複製圖片,請嘗試下載圖片。","operation.imageDownloaded": "圖片已下載","operation.in": "在","operation.learnMore": "瞭解更多",