Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

test(web): exercise upload and PDF preview behavior in Browser Mode (#45525)

Stephen Zhoub111dbaf286d
diff --git a/web/app/components/base/file-uploader/__tests__/pdf-preview.browser.spec.tsx b/web/app/components/base/file-uploader/__tests__/pdf-preview.browser.spec.tsx
new file mode 100644
index 00000000000..5a8892ca906
--- /dev/null
+++ b/web/app/components/base/file-uploader/__tests__/pdf-preview.browser.spec.tsx
@@ -0,0 +1,89 @@
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import {
+ createPreviewPdf,
+ guardPreviewFetch,
+ hasPaintedPdfText,
+} from '@/test/fixtures/preview-files'
+import { TransferMethod } from '@/types/app'
+import { FileItem } from '../file-uploader-in-chat-input/file-item'
+
+beforeEach(() => onTestFinished(guardPreviewFetch()))
+
+async function openPdf() {
+ await page.viewport(1024, 768)
+ await render(
+ <FileItem
+ file={{
+ id: 'pdf-1',
+ name: 'document.pdf',
+ type: 'application/pdf',
+ size: 2048,
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'document',
+ originalFile: createPreviewPdf('document.pdf'),
+ }}
+ canPreview
+ />,
+ )
+ await page.getByRole('button', { name: 'document.pdf' }).click()
+ const dialog = page.getByRole('dialog', { name: 'document.pdf' })
+ const text = dialog.getByText('Dify local preview')
+ await expect.element(text).toBeVisible()
+ await expect.poll(() => hasPaintedPdfText(dialog.element())).toBe(true)
+ await document.fonts.ready
+ // Cached PDFs can paint before the dialog's native entry-scale transition finishes.
+ await expect
+ .poll(() =>
+ dialog
+ .element()
+ .getAnimations()
+ .some((animation) => animation.playState === 'running'),
+ )
+ .toBe(false)
+ return { dialog, text }
+}
+
+it('bounds the rendered PDF zoom and restores readable original sizing after reopening', async () => {
+ const { dialog, text } = await openPdf()
+ const initialWidth = text.element().getBoundingClientRect().width
+ expect(initialWidth).toBeGreaterThan(0)
+ const zoomIn = dialog.getByRole('button', { name: 'common.operation.zoomIn' })
+ const zoomOut = dialog.getByRole('button', { name: 'common.operation.zoomOut' })
+ const width = () => text.element().getBoundingClientRect().width
+ await zoomIn.click()
+ await expect.poll(width).toBeCloseTo(initialWidth * 1.2, 0)
+ await zoomOut.click()
+ await expect.poll(width).toBeCloseTo(initialWidth, 0)
+ for (let step = 0; step < 20; step++) await zoomIn.click()
+ await expect.poll(width).toBeCloseTo(initialWidth * 15, 0)
+ for (let step = 0; step < 25; step++) await zoomOut.click()
+ await expect.poll(width).toBeCloseTo(initialWidth * 0.5, 0)
+ // These must remain hittable above the scaled document.
+ await dialog.getByRole('button', { name: 'common.operation.close' }).click()
+ await expect.element(dialog).not.toBeInTheDocument()
+ const trigger = page.getByRole('button', { name: 'document.pdf' })
+ await expect.element(trigger).toHaveFocus()
+ await trigger.click()
+ await expect.element(text).toBeVisible()
+ await expect.poll(width).toBeCloseTo(initialWidth, 0)
+})
+
+it('zooms the loaded PDF with popup shortcuts while Close keeps native focus', async () => {
+ const { dialog, text } = await openPdf()
+ const close = dialog.getByRole('button', { name: 'common.operation.close' })
+ await expect.element(close).toHaveFocus()
+ const initialWidth = text.element().getBoundingClientRect().width
+ await userEvent.keyboard('{ArrowUp}')
+ await expect
+ .poll(() => text.element().getBoundingClientRect().width / initialWidth)
+ .toBeCloseTo(1.2, 2)
+ await expect.element(close).toHaveFocus()
+ await userEvent.keyboard('{ArrowDown}')
+ await expect
+ .poll(() => text.element().getBoundingClientRect().width / initialWidth)
+ .toBeCloseTo(1, 2)
+ await userEvent.keyboard('{Escape}')
+ await expect.element(dialog).not.toBeInTheDocument()
+})
diff --git a/web/app/components/base/file-uploader/__tests__/pdf-preview.spec.tsx b/web/app/components/base/file-uploader/__tests__/pdf-preview.spec.tsx
deleted file mode 100644
index 60c641c889f..00000000000
--- a/web/app/components/base/file-uploader/__tests__/pdf-preview.spec.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-import type { ReactNode } from 'react'
-import { render, screen, waitFor } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { TransferMethod } from '@/types/app'
-import { FileItem } from '../file-uploader-in-chat-input/file-item'
-
-let mockBasePath = ''
-vi.mock('@/utils/var', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/utils/var')>()),
- get basePath() {
- return mockBasePath
- },
-}))
-
-vi.mock('../pdf-highlighter-adapter', () => ({
- PdfLoader: ({
- children,
- beforeLoad,
- workerSrc,
- }: {
- children: (doc: unknown) => ReactNode
- beforeLoad: ReactNode
- workerSrc: string
- }) => (
- <div data-testid="pdf-loader" data-worker-src={workerSrc}>
- {beforeLoad}
- {children({ numPages: 1 })}
- </div>
- ),
- PdfHighlighter: () => <div>PDF page</div>,
-}))
-
-const file = {
- id: 'pdf-1',
- name: 'document.pdf',
- type: 'application/pdf',
- size: 2048,
- progress: 100,
- transferMethod: TransferMethod.local_file,
- supportFileType: 'document',
- url: 'https://example.com/doc.pdf',
-}
-
-async function openPdf(user: ReturnType<typeof userEvent.setup>) {
- render(<FileItem file={file} canPreview />)
- await user.click(screen.getByRole('button', { name: 'document.pdf' }))
- await screen.findByText('PDF page')
-}
-
-function scaleContainer() {
- return screen.getByTestId('pdf-loader').parentElement!
-}
-
-beforeEach(() => {
- mockBasePath = ''
-})
-
-it('provides a named preview while loading the PDF worker from the configured base path', async () => {
- const user = userEvent.setup()
- mockBasePath = '/dify'
- await openPdf(user)
- expect(screen.getByRole('dialog', { name: 'document.pdf' })).toBeInTheDocument()
- expect(screen.getByTestId('pdf-loader')).toHaveAttribute(
- 'data-worker-src',
- '/dify/pdf.worker.min.mjs',
- )
-})
-
-it('uses the root worker path without a deployment base path', async () => {
- const user = userEvent.setup()
- await openPdf(user)
- expect(screen.getByTestId('pdf-loader')).toHaveAttribute('data-worker-src', '/pdf.worker.min.mjs')
-})
-
-it('zooms within its limits and starts again at the original scale after reopening', async () => {
- const user = userEvent.setup()
- await openPdf(user)
- const zoomIn = screen.getByRole('button', { name: 'common.operation.zoomIn' })
- const zoomOut = screen.getByRole('button', { name: 'common.operation.zoomOut' })
- await user.click(zoomIn)
- expect(scaleContainer()).toHaveStyle({ transform: 'scale(1.2)' })
- await user.click(zoomOut)
- expect(scaleContainer()).toHaveStyle({ transform: 'scale(1)' })
- for (let step = 0; step < 20; step++) await user.click(zoomIn)
- expect(scaleContainer()).toHaveStyle({ transform: 'scale(15)' })
- for (let step = 0; step < 25; step++) await user.click(zoomOut)
- expect(scaleContainer()).toHaveStyle({ transform: 'scale(0.5)' })
- await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- await user.click(screen.getByRole('button', { name: 'document.pdf' }))
- await screen.findByText('PDF page')
- expect(scaleContainer()).toHaveStyle({ transform: 'scale(1)' })
-})
-
-it('keeps popup-level zoom shortcuts working while Close has focus', async () => {
- const user = userEvent.setup()
- await openPdf(user)
- const close = screen.getByRole('button', { name: 'common.operation.close' })
- close.focus()
- await user.keyboard('{ArrowUp}')
- expect(scaleContainer()).toHaveStyle({ transform: 'scale(1.2)' })
- await user.keyboard('{ArrowDown}')
- expect(scaleContainer()).toHaveStyle({ transform: 'scale(1)' })
- await user.keyboard('{Escape}')
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
-})
diff --git a/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.browser.spec.tsx b/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.browser.spec.tsx
new file mode 100644
index 00000000000..a8d46828745
--- /dev/null
+++ b/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.browser.spec.tsx
@@ -0,0 +1,160 @@
+import type { ComponentProps } from 'react'
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
+import { guardUnexpectedFetch } from '@/test/unexpected-fetch'
+import { TransferMethod } from '@/types/app'
+import { FileItem } from '../../file-uploader-in-chat-input/file-item'
+import { FileContextProvider, useStore } from '../../store'
+import FileFromLinkOrLocal from '../index'
+
+// oxlint-disable-next-line typescript/no-deprecated -- Control the generated remote-file client's transport without replacing file processing or the store.
+const request = vi.hoisted(() => vi.fn<typeof import('@/service/base').request>())
+// oxlint-disable-next-line typescript/no-deprecated -- Local uploads still use the XHR transport.
+const upload = vi.hoisted(() => vi.fn<typeof import('@/service/base').upload>())
+vi.mock('@/service/base', () => ({ request, upload, post: vi.fn() }))
+vi.mock('@/next/navigation', () => ({ useParams: () => ({}), usePathname: () => '/apps' }))
+
+function Files() {
+ const files = useStore((s) => s.files)
+ return (
+ <ul aria-label="Uploaded files">
+ {files.map((file) => (
+ <li key={file.id}>
+ <FileItem file={file} />
+ </li>
+ ))}
+ </ul>
+ )
+}
+async function setup(props: Partial<ComponentProps<typeof FileFromLinkOrLocal>> = {}) {
+ await page.viewport(800, 600)
+ const { wrapper: Query } = createConsoleQueryWrapper()
+ const onChange = vi.fn()
+ await render(
+ <Query>
+ <FileContextProvider onChange={onChange}>
+ <div style={{ padding: 200 }}>
+ <FileFromLinkOrLocal
+ fileConfig={{
+ enabled: true,
+ allowed_file_types: [SupportUploadFileTypes.document],
+ allowed_file_extensions: [],
+ number_limits: 1,
+ }}
+ trigger={(triggerProps, state) => (
+ <button {...triggerProps}>{state.open ? 'Close uploads' : 'Open uploads'}</button>
+ )}
+ {...props}
+ />
+ <Files />
+ </div>
+ </FileContextProvider>
+ </Query>,
+ )
+ await page.getByRole('button', { name: 'Open uploads' }).click()
+ return { onChange }
+}
+
+beforeEach(() => {
+ onTestFinished(guardUnexpectedFetch())
+ upload.mockReset()
+ request.mockReset().mockImplementation(async () =>
+ Response.json({
+ id: 'uploaded-file',
+ name: 'report.pdf',
+ mime_type: 'application/pdf',
+ size: 10,
+ url: 'https://example.com/report.pdf',
+ }),
+ )
+})
+
+it.each([
+ { showFromLink: true, showFromLocal: false },
+ { showFromLink: false, showFromLocal: true },
+ { showFromLink: true, showFromLocal: true },
+])('offers configured upload methods: %o', async (props) => {
+ await setup(props)
+ const input = page.getByPlaceholder(/pasteFileLinkInputPlaceholder/)
+ const local = page.getByRole('button', { name: /uploadFromComputer/ })
+ if (props.showFromLink) await expect.element(input).toBeVisible()
+ else await expect.element(input).not.toBeInTheDocument()
+ if (props.showFromLocal) await expect.element(local).toBeVisible()
+ else await expect.element(local).not.toBeInTheDocument()
+})
+
+it('corrects an invalid link and renders the uploaded result while enforcing the limit', async () => {
+ const { onChange } = await setup()
+ const input = page.getByPlaceholder(/pasteFileLinkInputPlaceholder/)
+ const submit = page.getByRole('button', { name: 'common.operation.ok' })
+ await expect.element(submit).toBeDisabled()
+ await input.fill('invalid-url')
+ await submit.click()
+ await expect.element(page.getByText(/pasteFileLinkInvalid/)).toBeVisible()
+ expect(request).not.toHaveBeenCalled()
+ await input.fill('https://example.com/report.pdf')
+ await expect.element(page.getByText(/pasteFileLinkInvalid/)).not.toBeInTheDocument()
+ await submit.click()
+ const list = page.getByRole('list', { name: 'Uploaded files' })
+ await expect.element(list.getByText('https://example.com/report.pdf')).toBeVisible()
+ await expect.element(list.getByText('10.00 bytes')).toBeVisible()
+ await expect.element(list.getByRole('progressbar')).not.toBeInTheDocument()
+ expect(await request.mock.calls[0]?.[2]?.request?.json()).toEqual({
+ url: 'https://example.com/report.pdf',
+ })
+ expect(onChange).toHaveBeenLastCalledWith([
+ expect.objectContaining({
+ uploadedId: 'uploaded-file',
+ progress: 100,
+ transferMethod: TransferMethod.remote_url,
+ }),
+ ])
+ await expect.element(input).toHaveValue('')
+ await expect.element(input).toBeDisabled()
+ await expect.element(page.getByRole('button', { name: /uploadFromComputer/ })).toBeDisabled()
+})
+
+it('dismisses the actual upload popup and returns focus to its trigger', async () => {
+ await setup()
+ await page.getByRole('button', { name: 'Close uploads' }).click()
+ await expect
+ .element(page.getByPlaceholder(/pasteFileLinkInputPlaceholder/))
+ .not.toBeInTheDocument()
+ await expect.element(page.getByRole('button', { name: 'Open uploads' })).toHaveFocus()
+})
+
+it('publishes a pending local upload after its popup closes in the same input session', async () => {
+ const pending = createDeferred<Awaited<ReturnType<typeof upload>>>()
+ upload.mockReturnValue(pending.promise)
+ const { onChange } = await setup({ showFromLink: false })
+ const button = page.getByRole('button', { name: /uploadFromComputer/ })
+ await expect.element(button).toBeVisible()
+ // The production chooser is an unlabeled native input inside the labeled upload button.
+ const input = page.elementLocator(button.element().querySelector('input[type="file"]')!)
+ await input.upload(new File(['report'], 'report.txt', { type: 'text/plain' }))
+ await expect.element(page.getByRole('progressbar', { name: 'custom.uploading' })).toBeVisible()
+ await page.getByRole('button', { name: 'Close uploads' }).click()
+ await expect.element(button).not.toBeInTheDocument()
+ const selected = upload.mock.calls[0]![0].data.get('file') as File
+ expect(selected.name).toBe('report.txt')
+ expect(await selected.text()).toBe('report')
+ pending.resolve({ id: 'uploaded-report' })
+ await expect.element(page.getByRole('progressbar')).not.toBeInTheDocument()
+ await expect
+ .element(page.getByRole('list', { name: 'Uploaded files' }).getByText('report.txt'))
+ .toBeVisible()
+ expect(onChange).toHaveBeenLastCalledWith([
+ expect.objectContaining({
+ uploadedId: 'uploaded-report',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ }),
+ ])
+ await page.getByRole('button', { name: 'Open uploads' }).click()
+ await expect.element(page.getByRole('button', { name: /uploadFromComputer/ })).toBeDisabled()
+ await userEvent.keyboard('{Escape}')
+ await expect.element(button).not.toBeInTheDocument()
+})
diff --git a/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.spec.tsx b/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.spec.tsx
deleted file mode 100644
index 7dddebe6fcf..00000000000
--- a/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import type { ComponentProps } from 'react'
-import type { FileEntity } from '../../types'
-import type { FileUpload } from '@/app/components/base/features/types'
-import { act, render, screen, waitFor } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { SupportUploadFileTypes } from '@/app/components/workflow/types'
-import { createConsoleQueryWrapper } from '@/test/console/query-data'
-import { createDeferred } from '@/test/deferred'
-import { TransferMethod } from '@/types/app'
-import { FileContextProvider } from '../../store'
-import FileFromLinkOrLocal from '../index'
-
-const request = vi.hoisted(() => vi.fn<typeof import('@/service/base').request>())
-// oxlint-disable-next-line typescript/no-deprecated -- Control the existing XHR upload transport while exercising the real uploader lifecycle.
-const upload = vi.hoisted(() => vi.fn<typeof import('@/service/base').upload>())
-vi.mock('@/service/base', () => ({ request, upload }))
-vi.mock('@/next/navigation', () => ({ useParams: () => ({}), usePathname: () => '/apps' }))
-
-const config: FileUpload = {
- enabled: true,
- allowed_file_types: [SupportUploadFileTypes.document],
- allowed_file_extensions: [],
- number_limits: 1,
-}
-const setup = async (
- props: Partial<ComponentProps<typeof FileFromLinkOrLocal>> = {},
- files: FileEntity[] = [],
-) => {
- const user = userEvent.setup()
- const onChange = vi.fn()
- render(
- <FileContextProvider value={files} onChange={onChange}>
- <FileFromLinkOrLocal
- fileConfig={config}
- trigger={(triggerProps, state) => (
- <button {...triggerProps}>{state.open ? 'Close uploads' : 'Open uploads'}</button>
- )}
- {...props}
- />
- </FileContextProvider>,
- { wrapper: createConsoleQueryWrapper().wrapper },
- )
- await user.click(screen.getByRole('button', { name: 'Open uploads' }))
- return { user, onChange }
-}
-
-beforeEach(() => {
- upload.mockReset()
- request.mockReset()
- request.mockImplementation(async () =>
- Response.json({
- id: 'uploaded-file',
- name: 'report.pdf',
- mime_type: 'application/pdf',
- size: 10,
- url: 'https://example.com/report.pdf',
- }),
- )
-})
-
-it.each([
- { showFromLink: true, showFromLocal: false },
- { showFromLink: false, showFromLocal: true },
- { showFromLink: true, showFromLocal: true },
-])('offers configured upload methods: %o', async (props) => {
- await setup(props)
- expect(!!screen.queryByPlaceholderText(/pasteFileLinkInputPlaceholder/)).toBe(props.showFromLink)
- expect(!!screen.queryByRole('button', { name: /uploadFromComputer/ })).toBe(props.showFromLocal)
-})
-
-it('rejects an invalid link, clears the error on editing, and persists a valid upload', async () => {
- const { user, onChange } = await setup()
- const input = screen.getByPlaceholderText(/pasteFileLinkInputPlaceholder/)
- const submit = screen.getByRole('button', { name: 'common.operation.ok' })
- expect(submit).toBeDisabled()
- await user.type(input, 'invalid-url')
- await user.click(submit)
- expect(screen.getByText(/pasteFileLinkInvalid/)).toBeInTheDocument()
- expect(request).not.toHaveBeenCalled()
- await user.clear(input)
- await user.type(input, 'https://example.com/report.pdf')
- expect(screen.queryByText(/pasteFileLinkInvalid/)).not.toBeInTheDocument()
- await user.click(submit)
- await waitFor(() => expect(request).toHaveBeenCalled())
- expect(await request.mock.calls[0]?.[2]?.request?.json()).toEqual({
- url: 'https://example.com/report.pdf',
- })
- await waitFor(() =>
- expect(onChange).toHaveBeenLastCalledWith([
- expect.objectContaining({
- uploadedId: 'uploaded-file',
- progress: 100,
- transferMethod: TransferMethod.remote_url,
- }),
- ]),
- )
- expect(input).toHaveValue('')
- expect(input).toBeDisabled()
- expect(screen.getByRole('button', { name: /uploadFromComputer/ })).toBeDisabled()
-})
-
-it('dismisses the upload popover through its trigger', async () => {
- const { user } = await setup()
- await user.click(screen.getByRole('button', { name: 'Close uploads' }))
- await waitFor(() =>
- expect(screen.queryByPlaceholderText(/pasteFileLinkInputPlaceholder/)).not.toBeInTheDocument(),
- )
- expect(screen.getByRole('button', { name: 'Open uploads' })).toBeInTheDocument()
-})
-
-it('finishes a local upload after its popover closes while the input session remains active', async () => {
- const pending = createDeferred<Awaited<ReturnType<typeof upload>>>()
- upload.mockReturnValue(pending.promise)
- const { user, onChange } = await setup({ showFromLink: false })
- const button = screen.getByRole('button', { name: /uploadFromComputer/ })
- const input = button.querySelector<HTMLInputElement>('input[type="file"]')!
- await user.upload(input, new File(['report'], 'report.txt', { type: 'text/plain' }))
- await waitFor(() => expect(upload).toHaveBeenCalledOnce())
- await user.click(screen.getByRole('button', { name: 'Close uploads' }))
- expect(screen.queryByRole('button', { name: /uploadFromComputer/ })).not.toBeInTheDocument()
-
- await act(async () => pending.resolve({ id: 'uploaded-report' }))
-
- expect(onChange).toHaveBeenLastCalledWith([
- expect.objectContaining({ uploadedId: 'uploaded-report', progress: 100 }),
- ])
-})
diff --git a/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/file-item.browser.spec.tsx b/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/file-item.browser.spec.tsx
new file mode 100644
index 00000000000..895f0a6361a
--- /dev/null
+++ b/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/file-item.browser.spec.tsx
@@ -0,0 +1,227 @@
+import type { FileEntity } from '../../types'
+import { useState } from 'react'
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { PreviewMode } from '@/app/components/base/features/types'
+import { previewImage } from '@/test/fixtures/preview-files'
+import { guardUnexpectedFetch } from '@/test/unexpected-fetch'
+import { TransferMethod } from '@/types/app'
+import FileInAttachmentItem from '../file-item'
+
+const createFile = (overrides: Partial<FileEntity> = {}): FileEntity => ({
+ id: 'file-1',
+ name: 'document.pdf',
+ size: 2048,
+ type: 'application/pdf',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'document',
+ uploadedId: 'uploaded-1',
+ url: 'https://example.com/document.pdf',
+ ...overrides,
+})
+const action = (name: string, filename = 'document.pdf') =>
+ page.getByRole('button', { name: `common.operation.${name} ${filename}` })
+
+function EditableAttachments({ initialFiles }: { initialFiles: FileEntity[] }) {
+ const [files, setFiles] = useState(initialFiles)
+ return (
+ <ul aria-label="Attachments">
+ {files.map((file) => (
+ <li key={file.id}>
+ <FileInAttachmentItem
+ file={file}
+ showDeleteAction
+ canPreview
+ previewMode={PreviewMode.NewPage}
+ onRemove={(id) => setFiles((current) => current.filter((item) => item.id !== id))}
+ />
+ </li>
+ ))}
+ </ul>
+ )
+}
+
+function RetryAttachment({ file }: { file: FileEntity }) {
+ const [uploadedId, setUploadedId] = useState<string>()
+ return (
+ <>
+ <FileInAttachmentItem
+ file={uploadedId ? { ...file, progress: 100, uploadedId } : file}
+ canPreview
+ previewMode={PreviewMode.NewPage}
+ onReUpload={(id) => {
+ if (id === file.id) setUploadedId(`uploaded-${id}`)
+ }}
+ />
+ <FileInAttachmentItem file={createFile({ id: 'second', name: 'second.pdf' })} />
+ </>
+ )
+}
+
+function captureDownloads() {
+ const downloads: { url: string; filename: string; target: string; rel: string }[] = []
+ const handleClick = (event: MouseEvent) => {
+ if (!(event.target instanceof HTMLAnchorElement) || !event.target.download) return
+ event.preventDefault()
+ downloads.push({
+ url: event.target.href,
+ filename: event.target.download,
+ target: event.target.target,
+ rel: event.target.rel,
+ })
+ }
+ document.addEventListener('click', handleClick, true)
+ onTestFinished(() => document.removeEventListener('click', handleClick, true))
+ return downloads
+}
+
+beforeEach(async () => {
+ await page.viewport(800, 600)
+ onTestFinished(guardUnexpectedFetch())
+})
+afterEach(() => vi.restoreAllMocks())
+
+it('shows file metadata without actions the caller disabled', async () => {
+ await render(<FileInAttachmentItem file={createFile()} showDownloadAction={false} />)
+ await expect.element(page.getByText('document.pdf')).toBeVisible()
+ await expect.element(page.getByText('pdf')).toBeVisible()
+ await expect.element(page.getByText('2.00 KB')).toBeVisible()
+ await expect
+ .element(page.getByRole('button', { name: /operation.remove|operation.download/ }))
+ .not.toBeInTheDocument()
+})
+
+it('replaces progress with Retry on failure and applies retry to the selected attachment', async () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null)
+ const uploading = createFile({ progress: 50, uploadedId: undefined })
+ const screen = await render(<RetryAttachment file={uploading} />)
+ await expect
+ .element(page.getByRole('progressbar', { name: 'custom.uploading' }))
+ .toHaveAttribute('aria-valuenow', '50')
+ await screen.rerender(<RetryAttachment file={{ ...uploading, progress: -1 }} />)
+ await expect.element(page.getByRole('progressbar')).not.toBeInTheDocument()
+ await action('retry').click()
+ await expect.element(action('retry')).not.toBeInTheDocument()
+ await expect.element(page.getByText('document.pdf')).toBeVisible()
+ await expect.element(page.getByText('second.pdf')).toBeVisible()
+ expect(open).not.toHaveBeenCalled()
+})
+
+it('downloads and removes the chosen file without opening its new-page preview', async () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null)
+ const downloads = captureDownloads()
+ await render(
+ <EditableAttachments
+ initialFiles={[createFile(), createFile({ id: 'second', name: 'second.pdf' })]}
+ />,
+ )
+ await action('download').click()
+ expect(downloads).toEqual([
+ {
+ url: 'https://example.com/document.pdf',
+ filename: 'document.pdf',
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ },
+ ])
+ expect(open).not.toHaveBeenCalled()
+ await action('remove').click()
+ await expect.element(page.getByText('document.pdf')).not.toBeInTheDocument()
+ await expect.element(page.getByText('second.pdf')).toBeVisible()
+ expect(open).not.toHaveBeenCalled()
+ await page.getByText('second.pdf').click()
+ expect(open).toHaveBeenCalledExactlyOnceWith('https://example.com/document.pdf', '_blank')
+})
+
+it.each([
+ { url: previewImage, base64Url: undefined },
+ { url: undefined, base64Url: previewImage },
+])(
+ 'decodes the attachment image and dismisses its real preview using $url / $base64Url',
+ async ({ url, base64Url }) => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null)
+ await render(
+ <FileInAttachmentItem
+ file={createFile({
+ name: 'photo.svg',
+ type: 'image/svg+xml',
+ supportFileType: 'image',
+ url,
+ base64Url,
+ })}
+ canPreview
+ previewMode={PreviewMode.NewPage}
+ />,
+ )
+ await action('view', 'photo.svg').click()
+ const dialog = page.getByRole('dialog', { name: 'photo.svg' })
+ const image = dialog.getByRole('img', { name: 'photo.svg' })
+ await expect.element(image).toBeVisible()
+ await expect.poll(() => (image.element() as HTMLImageElement).naturalWidth).toBe(80)
+ expect(open).not.toHaveBeenCalled()
+ await dialog.getByRole('button', { name: 'common.operation.cancel' }).click()
+ await expect.element(dialog).not.toBeInTheDocument()
+ await expect.element(action('view', 'photo.svg')).toHaveFocus()
+ },
+)
+
+it('uses the local fallback URL for actual download attributes and new-page navigation', async () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null)
+ const downloads = captureDownloads()
+ await render(
+ <FileInAttachmentItem
+ file={createFile({ url: undefined, base64Url: previewImage })}
+ canPreview
+ previewMode={PreviewMode.NewPage}
+ />,
+ )
+ await action('download').click()
+ expect(downloads).toEqual([
+ { url: previewImage, filename: 'document.pdf', target: '_blank', rel: 'noopener noreferrer' },
+ ])
+ await page.getByText('document.pdf').click()
+ expect(open).toHaveBeenCalledExactlyOnceWith(previewImage, '_blank')
+})
+
+it('disables unavailable attachment actions through native keyboard focus', async () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null)
+ const downloads = captureDownloads()
+ await render(
+ <>
+ <button>Before attachment</button>
+ <FileInAttachmentItem
+ file={createFile({ supportFileType: 'image', url: undefined, base64Url: undefined })}
+ canPreview
+ previewMode={PreviewMode.NewPage}
+ />
+ <button>After attachment</button>
+ </>,
+ )
+ await expect.element(action('download')).toBeDisabled()
+ await expect.element(action('view')).toBeDisabled()
+ await page.getByRole('button', { name: 'Before attachment' }).click()
+ await userEvent.tab()
+ await expect.element(page.getByRole('button', { name: 'After attachment' })).toHaveFocus()
+ await page.getByText('document.pdf').click()
+ expect(downloads).toEqual([])
+ expect(open).not.toHaveBeenCalled()
+ await expect.element(page.getByRole('dialog')).not.toBeInTheDocument()
+})
+
+it('keeps filename navigation inactive when preview is disabled or limited to the current page', async () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null)
+ const screen = await render(
+ <FileInAttachmentItem
+ file={createFile()}
+ canPreview={false}
+ previewMode={PreviewMode.NewPage}
+ />,
+ )
+ await page.getByText('document.pdf').click()
+ await screen.rerender(
+ <FileInAttachmentItem file={createFile()} canPreview previewMode={PreviewMode.CurrentPage} />,
+ )
+ await page.getByText('document.pdf').click()
+ expect(open).not.toHaveBeenCalled()
+})
diff --git a/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/file-item.spec.tsx b/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/file-item.spec.tsx
deleted file mode 100644
index fa03c0a29bc..00000000000
--- a/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/file-item.spec.tsx
+++ /dev/null
@@ -1,205 +0,0 @@
-import type { FileEntity } from '../../types'
-import { render, screen, waitFor, within } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { PreviewMode } from '@/app/components/base/features/types'
-import { TransferMethod } from '@/types/app'
-import { downloadUrl } from '@/utils/download'
-import FileInAttachmentItem from '../file-item'
-
-vi.mock('@/utils/download', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/utils/download')>()),
- downloadUrl: vi.fn(),
-}))
-
-const createFile = (overrides: Partial<FileEntity> = {}): FileEntity => ({
- id: 'file-1',
- name: 'document.pdf',
- size: 2048,
- type: 'application/pdf',
- progress: 100,
- transferMethod: TransferMethod.local_file,
- supportFileType: 'document',
- uploadedId: 'uploaded-1',
- url: 'https://example.com/document.pdf',
- ...overrides,
-})
-
-const action = (name: string, fileName = 'document.pdf') =>
- screen.getByRole('button', { name: `common.operation.${name} ${fileName}` })
-
-describe('FileInAttachmentItem', () => {
- beforeEach(() => vi.clearAllMocks())
- afterEach(() => vi.restoreAllMocks())
-
- it('shows file metadata and only enables the requested actions', () => {
- render(<FileInAttachmentItem file={createFile()} showDownloadAction={false} />)
- expect(screen.getByText('document.pdf')).toBeInTheDocument()
- expect(screen.getByText('pdf')).toBeInTheDocument()
- expect(screen.getByText('2.00 KB')).toBeInTheDocument()
- expect(screen.queryByRole('button', { name: /operation.remove/ })).not.toBeInTheDocument()
- expect(screen.queryByRole('button', { name: /operation.download/ })).not.toBeInTheDocument()
- })
-
- it('transitions from upload progress to retry and then uploaded state', async () => {
- const user = userEvent.setup()
- const onReUpload = vi.fn()
- const { rerender } = render(
- <FileInAttachmentItem
- file={createFile({ progress: 50, uploadedId: undefined })}
- onReUpload={onReUpload}
- />,
- )
- expect(screen.getByRole('progressbar', { name: 'custom.uploading' })).toHaveAttribute(
- 'aria-valuenow',
- '50',
- )
- rerender(
- <FileInAttachmentItem
- file={createFile({ progress: -1, uploadedId: undefined })}
- onReUpload={onReUpload}
- />,
- )
- expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
- await user.click(action('retry'))
- expect(onReUpload).toHaveBeenCalledExactlyOnceWith('file-1')
- rerender(<FileInAttachmentItem file={createFile()} onReUpload={onReUpload} />)
- expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
- expect(screen.queryByRole('button', { name: /operation.retry/ })).not.toBeInTheDocument()
- })
-
- it('removes or downloads the file without opening its new-page preview', async () => {
- const user = userEvent.setup()
- const open = vi.spyOn(window, 'open').mockReturnValue(null)
- const onRemove = vi.fn()
- render(
- <FileInAttachmentItem
- file={createFile()}
- showDeleteAction
- onRemove={onRemove}
- canPreview
- previewMode={PreviewMode.NewPage}
- />,
- )
- await user.click(action('remove'))
- expect(onRemove).toHaveBeenCalledExactlyOnceWith('file-1')
- await user.click(action('download'))
- expect(downloadUrl).toHaveBeenCalledExactlyOnceWith({
- url: 'https://example.com/document.pdf',
- fileName: 'document.pdf',
- target: '_blank',
- })
- expect(open).not.toHaveBeenCalled()
- await user.click(screen.getByText('document.pdf'))
- expect(open).toHaveBeenCalledExactlyOnceWith('https://example.com/document.pdf', '_blank')
- })
-
- it('retries without opening the attachment preview', async () => {
- const user = userEvent.setup()
- const open = vi.spyOn(window, 'open').mockReturnValue(null)
- const onReUpload = vi.fn()
- render(
- <FileInAttachmentItem
- file={createFile({ progress: -1 })}
- onReUpload={onReUpload}
- canPreview
- previewMode={PreviewMode.NewPage}
- />,
- )
- await user.click(action('retry'))
- expect(onReUpload).toHaveBeenCalledExactlyOnceWith('file-1')
- expect(open).not.toHaveBeenCalled()
- })
-
- it.each([
- { url: 'https://example.com/photo.png', base64Url: undefined },
- { url: undefined, base64Url: 'data:image/png;base64,YWJj' },
- ])('opens and dismisses an image preview using $url / $base64Url', async ({ url, base64Url }) => {
- const user = userEvent.setup()
- const open = vi.spyOn(window, 'open').mockReturnValue(null)
- render(
- <FileInAttachmentItem
- file={createFile({
- name: 'photo.png',
- type: 'image/png',
- supportFileType: 'image',
- url,
- base64Url,
- })}
- canPreview
- previewMode={PreviewMode.NewPage}
- />,
- )
- expect(screen.getByRole('img')).toHaveAttribute('src', base64Url || url)
- await user.click(action('view', 'photo.png'))
- const dialog = await screen.findByRole('dialog', { name: 'photo.png' })
- expect(within(dialog).getByRole('img', { name: 'photo.png' })).toHaveAttribute(
- 'src',
- url || base64Url,
- )
- expect(open).not.toHaveBeenCalled()
- await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- })
-
- it('uses the local image as a fallback for download and new-page preview', async () => {
- const user = userEvent.setup()
- const open = vi.spyOn(window, 'open').mockReturnValue(null)
- const base64Url = 'data:image/png;base64,YWJj'
- render(
- <FileInAttachmentItem
- file={createFile({ url: undefined, base64Url })}
- canPreview
- previewMode={PreviewMode.NewPage}
- />,
- )
- await user.click(action('download'))
- expect(downloadUrl).toHaveBeenCalledExactlyOnceWith({
- url: base64Url,
- fileName: 'document.pdf',
- target: '_blank',
- })
- await user.click(screen.getByText('document.pdf'))
- expect(open).toHaveBeenCalledExactlyOnceWith(base64Url, '_blank')
- })
-
- it.each([undefined, ''])(
- 'does not open or download a missing attachment URL (%s)',
- async (url) => {
- const user = userEvent.setup()
- const open = vi.spyOn(window, 'open').mockReturnValue(null)
- render(
- <FileInAttachmentItem
- file={createFile({ supportFileType: 'image', url, base64Url: url })}
- canPreview
- previewMode={PreviewMode.NewPage}
- />,
- )
- expect(action('download')).toBeDisabled()
- expect(action('view')).toBeDisabled()
- await user.click(action('download'))
- await user.click(action('view'))
- await user.click(screen.getByText('document.pdf'))
- expect(downloadUrl).not.toHaveBeenCalled()
- expect(open).not.toHaveBeenCalled()
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
- },
- )
-
- it('does not open a new page when preview is disabled or uses the current page', async () => {
- const user = userEvent.setup()
- const open = vi.spyOn(window, 'open').mockReturnValue(null)
- const { rerender } = render(
- <FileInAttachmentItem
- file={createFile()}
- canPreview={false}
- previewMode={PreviewMode.NewPage}
- />,
- )
- await user.click(screen.getByText('document.pdf'))
- rerender(
- <FileInAttachmentItem file={createFile()} canPreview previewMode={PreviewMode.CurrentPage} />,
- )
- await user.click(screen.getByText('document.pdf'))
- expect(open).not.toHaveBeenCalled()
- })
-})
diff --git a/web/features/new-rag/upload/__tests__/local-file-preview-policy.spec.ts b/web/features/new-rag/upload/__tests__/local-file-preview-policy.spec.ts
new file mode 100644
index 00000000000..b2aacf3ed48
--- /dev/null
+++ b/web/features/new-rag/upload/__tests__/local-file-preview-policy.spec.ts
@@ -0,0 +1,16 @@
+import { canPreviewLocalFile } from '../local-file-preview-policy'
+
+it('offers component previews for browser-readable upload formats', () => {
+ const previewable = ['csv', 'htm', 'html', 'json', 'jsonl', 'md', 'pdf', 'text', 'txt']
+ const parserRequired = ['doc', 'docx', 'epub', 'ppt', 'pptx', 'rtf', 'xls', 'xlsx']
+ expect(
+ previewable.every((extension) =>
+ canPreviewLocalFile(new File(['content'], `document.${extension}`)),
+ ),
+ ).toBe(true)
+ expect(
+ parserRequired.every(
+ (extension) => !canPreviewLocalFile(new File(['content'], `document.${extension}`)),
+ ),
+ ).toBe(true)
+})
diff --git a/web/features/new-rag/upload/__tests__/local-file-preview.browser.spec.tsx b/web/features/new-rag/upload/__tests__/local-file-preview.browser.spec.tsx
new file mode 100644
index 00000000000..24924ec72d1
--- /dev/null
+++ b/web/features/new-rag/upload/__tests__/local-file-preview.browser.spec.tsx
@@ -0,0 +1,63 @@
+import { useState } from 'react'
+import { page } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import {
+ createPreviewPdf,
+ guardPreviewFetch,
+ hasPaintedPdfText,
+} from '@/test/fixtures/preview-files'
+import { LocalFilePreview } from '../local-file-preview'
+
+function Preview({ file }: { file: File }) {
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+ <button onClick={() => setOpen(true)}>Preview file</button>
+ <LocalFilePreview file={file} open={open} onOpenChange={setOpen} />
+ </>
+ )
+}
+
+beforeEach(() => onTestFinished(guardPreviewFetch()))
+
+afterEach(() => vi.restoreAllMocks())
+
+it('reads UTF-8 HTML as inert text and closes the real preview', async () => {
+ await page.viewport(1024, 768)
+ const file = new File(
+ ['<script>document.title="EXECUTED"</script>\n让状态可分析'],
+ '状态分析.html',
+ { type: 'text/html' },
+ )
+ const title = document.title
+ await render(<Preview file={file} />)
+ await page.getByRole('button', { name: 'Preview file' }).click()
+ const dialog = page.getByRole('dialog', { name: file.name })
+ await expect
+ .element(dialog.getByLabelText(file.name))
+ .toHaveTextContent('<script>document.title="EXECUTED"</script> 让状态可分析')
+ expect(document.title).toBe(title)
+ await dialog.getByRole('button', { name: 'common.operation.close' }).click()
+ await expect.element(dialog).not.toBeInTheDocument()
+ await expect.element(page.getByRole('button', { name: 'Preview file' })).toHaveFocus()
+})
+
+it('renders a local PDF, releases its resource on Close and loads it again on reopen', async () => {
+ await page.viewport(1024, 768)
+ const revoke = vi.spyOn(URL, 'revokeObjectURL')
+ const create = vi.spyOn(URL, 'createObjectURL')
+ await render(<Preview file={createPreviewPdf()} />)
+ const trigger = page.getByRole('button', { name: 'Preview file' })
+ await trigger.click()
+ const dialog = page.getByRole('dialog', { name: 'guide.pdf' })
+ await expect.element(dialog.getByText('Dify local preview')).toBeVisible()
+ await expect.poll(() => hasPaintedPdfText(dialog.element())).toBe(true)
+ const resource = create.mock.results[0]!.value as string
+ expect(revoke).not.toHaveBeenCalledWith(resource)
+ await dialog.getByRole('button', { name: 'common.operation.close' }).click()
+ await expect.element(dialog).not.toBeInTheDocument()
+ await expect.poll(() => revoke.mock.calls.some(([url]) => url === resource)).toBe(true)
+ await trigger.click()
+ await expect.element(dialog.getByText('Dify local preview')).toBeVisible()
+ expect(create.mock.results.some((result) => result.value !== resource)).toBe(true)
+})
diff --git a/web/features/new-rag/upload/__tests__/local-file-preview.spec.tsx b/web/features/new-rag/upload/__tests__/local-file-preview.spec.tsx
deleted file mode 100644
index f03ea5ae48e..00000000000
--- a/web/features/new-rag/upload/__tests__/local-file-preview.spec.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { render, screen, within } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { LocalFilePreview } from '../local-file-preview'
-import { canPreviewLocalFile } from '../local-file-preview-policy'
-
-vi.mock('@/app/components/base/file-uploader/pdf-preview', () => ({
- PdfPreview: ({ url }: { url: string }) => (
- <div role="img" aria-label="PDF preview" data-url={url}>
- PDF preview
- </div>
- ),
-}))
-
-describe('LocalFilePreview', () => {
- afterEach(() => {
- vi.restoreAllMocks()
- })
-
- it('offers component previews for browser-readable upload formats', () => {
- const previewableExtensions = [
- 'csv',
- 'htm',
- 'html',
- 'json',
- 'jsonl',
- 'md',
- 'pdf',
- 'text',
- 'txt',
- ]
- const parserRequiredExtensions = ['doc', 'docx', 'epub', 'ppt', 'pptx', 'rtf', 'xls', 'xlsx']
-
- expect(
- previewableExtensions.every((extension) =>
- canPreviewLocalFile(new File(['content'], `document.${extension}`)),
- ),
- ).toBe(true)
- expect(
- parserRequiredExtensions.every(
- (extension) => !canPreviewLocalFile(new File(['content'], `document.${extension}`)),
- ),
- ).toBe(true)
- })
-
- it('renders UTF-8 HTML as inert text inside the app', async () => {
- const user = userEvent.setup()
- const onOpenChange = vi.fn()
- const file = new File(['<script>错误</script>\n让状态可分析'], '状态分析.html', {
- type: 'text/html',
- })
-
- render(<LocalFilePreview file={file} open onOpenChange={onOpenChange} />)
-
- const dialog = await screen.findByRole('dialog', { name: file.name })
- const preview = await within(dialog).findByLabelText(file.name)
- expect(preview).toHaveTextContent('<script>错误</script> 让状态可分析')
- expect(dialog.querySelector('script')).not.toBeInTheDocument()
-
- await user.click(within(dialog).getByRole('button', { name: 'common.operation.close' }))
- expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false, expect.anything())
- })
-
- it('previews PDFs with a component-owned object URL and releases it on unmount', async () => {
- const user = userEvent.setup()
- const onOpenChange = vi.fn()
- const createObjectUrl = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:pdf-preview')
- const revokeObjectUrl = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
- const file = new File(['pdf'], 'guide.pdf', { type: 'application/pdf' })
-
- const { unmount } = render(<LocalFilePreview file={file} open onOpenChange={onOpenChange} />)
-
- const preview = await screen.findByRole('img', { name: 'PDF preview' })
- expect(preview).toHaveAttribute('data-url', 'blob:pdf-preview')
- expect(createObjectUrl).toHaveBeenCalledWith(expect.any(Blob))
-
- await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
- expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false, expect.anything())
-
- unmount()
- expect(revokeObjectUrl).toHaveBeenCalledWith('blob:pdf-preview')
- })
-})
diff --git a/web/test/fixtures/preview-files.ts b/web/test/fixtures/preview-files.ts
new file mode 100644
index 00000000000..03af841f61c
--- /dev/null
+++ b/web/test/fixtures/preview-files.ts
@@ -0,0 +1,60 @@
+// A complete, local PDF lets preview tests exercise the real loader, worker and canvas.
+export function createPreviewPdf(name = 'guide.pdf') {
+ const content = 'BT /F1 24 Tf 40 180 Td (Dify local preview) Tj ET'
+ const objects = [
+ '<< /Type /Catalog /Pages 2 0 R >>',
+ '<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
+ '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 320 240] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>',
+ '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
+ `<< /Length ${content.length} >>\nstream\n${content}\nendstream`,
+ ]
+ let pdf = '%PDF-1.4\n'
+ const offsets = [0]
+ objects.forEach((object, index) => {
+ offsets.push(pdf.length)
+ pdf += `${index + 1} 0 obj\n${object}\nendobj\n`
+ })
+ const xref = pdf.length
+ pdf += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`
+ pdf += offsets
+ .slice(1)
+ .map((offset) => `${String(offset).padStart(10, '0')} 00000 n \n`)
+ .join('')
+ pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`
+ return new File([pdf], name, { type: 'application/pdf' })
+}
+
+export const previewImage = `data:image/svg+xml,${encodeURIComponent(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="80" height="60"><rect width="80" height="60" fill="blue"/></svg>',
+)}`
+
+/** Only locally allocated preview data may reach native fetch; backend traffic is a test failure. */
+export function guardPreviewFetch() {
+ const nativeFetch = globalThis.fetch.bind(globalThis)
+ const unexpected = vi.fn()
+ vi.stubGlobal('fetch', (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : String(input)
+ if (url.startsWith('blob:') || url.startsWith('data:')) return nativeFetch(input, init)
+ unexpected(url)
+ return Promise.reject(new Error(`Unexpected preview request: ${url}`))
+ })
+ return () => {
+ try {
+ expect(unexpected).not.toHaveBeenCalled()
+ } finally {
+ vi.unstubAllGlobals()
+ }
+ }
+}
+
+// PDF.js has no accessible canvas role. Read its public painted output, not SDK classes or state.
+export function hasPaintedPdfText(preview: Element) {
+ const canvas = preview.querySelector('canvas')
+ if (!canvas?.width || !canvas.height) return false
+ const pixels = canvas.getContext('2d')?.getImageData(0, 0, canvas.width, canvas.height).data
+ if (!pixels) return false
+ for (let index = 0; index < pixels.length; index += 4) {
+ if (pixels[index + 3]! > 0 && pixels[index]! < 128) return true
+ }
+ return false
+}