From 9bdbd3c45ff9b3353758e8a201f3eb00a344ca08 Mon Sep 17 00:00:00 2001 From: Tong Chen Date: Mon, 14 Sep 2026 23:48:09 +0800 Subject: [PATCH] fix: batch workspace file previews safely (#1917) --- electron/main/fileReader.ts | 13 + electron/main/index.ts | 3 +- .../sections/buildProjectSessionPanelData.ts | 17 +- .../sections/useProjectOutputFiles.ts | 164 ++++-- src/shared/filePreviewContract.ts | 7 + .../components/Folder/FilePreview.test.tsx | 48 +- .../Folder/FileViewerPanel.test.tsx | 98 +++- .../components/Session/ActivityPanel.test.tsx | 95 ++++ .../useProjectOutputFiles.test.tsx | 475 ++++++++++++++++++ .../buildProjectSessionPanelData.test.ts | 85 ++++ test/unit/electron/fileReaderPreview.test.ts | 166 +++++- test/unit/lib/filePreviewContract.test.ts | 14 + test/unit/lib/filePreviewLoader.test.ts | 50 ++ 13 files changed, 1188 insertions(+), 47 deletions(-) diff --git a/electron/main/fileReader.ts b/electron/main/fileReader.ts index db0341fa5..b5f19daf4 100644 --- a/electron/main/fileReader.ts +++ b/electron/main/fileReader.ts @@ -23,6 +23,7 @@ import path from 'node:path'; import { URL } from 'node:url'; import * as unzipper from 'unzipper'; import { parseStringPromise } from 'xml2js'; +import { normalizeWorkspaceRelativePath } from '../../src/lib/workspaceRelativePath'; import { decideFilePreview, FILE_PREVIEW_LIMITS, @@ -1375,6 +1376,9 @@ export class FileReader { const files: FileInfo[] = []; for (const relativePath of new Set(requestedRelativePaths)) { if (!relativePath || path.isAbsolute(relativePath)) continue; + const requestedIdentity = + normalizeWorkspaceRelativePath(relativePath); + if (!requestedIdentity) continue; const candidatePath = path.resolve(rootRealPath, relativePath); const relativeToRoot = path.relative(rootRealPath, candidatePath); if ( @@ -1395,6 +1399,15 @@ export class FileReader { ) { continue; } + // A directory symlink can point at a different in-root identity. + // Omit that alias instead of returning an unrequested real path + // that would invalidate the renderer's entire batch. + if ( + normalizeWorkspaceRelativePath(realRelativePath) !== + requestedIdentity + ) { + continue; + } const name = path.basename(realPath); files.push({ path: realPath, diff --git a/electron/main/index.ts b/electron/main/index.ts index 6e37b524c..4168ba59d 100644 --- a/electron/main/index.ts +++ b/electron/main/index.ts @@ -2680,7 +2680,8 @@ function registerIpcHandlers() { if ( typeof workspaceRoot !== 'string' || !Array.isArray(requestedRelativePaths) || - requestedRelativePaths.length > 500 || + requestedRelativePaths.length > + FILE_PREVIEW_LIMITS.workspaceResolverPaths || requestedRelativePaths.some((value) => typeof value !== 'string') ) { throw new Error('Invalid workspace file resolver request'); diff --git a/src/components/Session/SidePanel/sections/buildProjectSessionPanelData.ts b/src/components/Session/SidePanel/sections/buildProjectSessionPanelData.ts index a122e6754..8ebb019f9 100644 --- a/src/components/Session/SidePanel/sections/buildProjectSessionPanelData.ts +++ b/src/components/Session/SidePanel/sections/buildProjectSessionPanelData.ts @@ -927,7 +927,17 @@ export function mergeProjectFiles( if (idMatch && pathMatch && idMatch.path !== pathMatch.path) return item; const match = idMatch || pathMatch; - if (!match) return item; + if (!match?.path.trim()) return item; + const matchRelativePath = normalizeWorkspaceRelativePath( + match.relativePath + ); + if ( + (match.relativePath !== undefined && !matchRelativePath) || + (relativePath && matchRelativePath && relativePath !== matchRelativePath) + ) { + // An artifact id must not relabel a moved file as its old relative path. + return item; + } if ( artifactId && match.artifactId && @@ -945,10 +955,7 @@ export function mergeProjectFiles( name: item.file.name || match.name, type: item.file.type || match.type, path: match.path || item.file.path, - relativePath: - relativePath || - normalizeWorkspaceRelativePath(match.relativePath) || - undefined, + relativePath: relativePath || matchRelativePath || undefined, artifactId: artifactId || match.artifactId, artifactChange: item.file.artifactChange, mimeType: item.file.mimeType || match.mimeType, diff --git a/src/components/Session/SidePanel/sections/useProjectOutputFiles.ts b/src/components/Session/SidePanel/sections/useProjectOutputFiles.ts index 9839effb7..5187f8116 100644 --- a/src/components/Session/SidePanel/sections/useProjectOutputFiles.ts +++ b/src/components/Session/SidePanel/sections/useProjectOutputFiles.ts @@ -15,6 +15,8 @@ import { fetchGet, getBaseURL } from '@/api/http'; import { useHost } from '@/host'; import { filterVisibleAgentFiles } from '@/lib/agentFileFilters'; +import { normalizeWorkspaceRelativePath } from '@/lib/workspaceRelativePath'; +import { FILE_PREVIEW_LIMITS } from '@/shared/filePreviewContract'; import { useAuthStore } from '@/store/authStore'; import { ChatTaskStatus } from '@/types/constants'; import { useEffect, useState } from 'react'; @@ -25,6 +27,48 @@ type SidePanelTask = { taskAssigning?: Agent[]; }; +const EMPTY_FILES: FileInfo[] = []; + +function mergeWorkspaceFileBatch( + files: Map, + batch: unknown, + requestedPaths: string[] +): void { + if ( + !Array.isArray(batch) || + batch.length > FILE_PREVIEW_LIMITS.workspaceResolverPaths + ) { + throw new Error('Invalid workspace file resolver batch'); + } + const requested = new Set(requestedPaths.map(normalizeWorkspaceRelativePath)); + for (const file of batch) { + if ( + !file || + typeof file.relativePath !== 'string' || + typeof file.path !== 'string' || + typeof file.name !== 'string' || + typeof file.type !== 'string' || + file.isRemote || + file.isFolder || + file.path.includes('\0') || + !/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(file.path) + ) { + throw new Error('Invalid workspace file resolver entry'); + } + const relativePath = normalizeWorkspaceRelativePath(file.relativePath); + if (!relativePath || !requested.has(relativePath)) { + throw new Error('Unrequested workspace file resolver identity'); + } + // Absolute paths are supplied by the main-process realpath/authorization + // boundary. Never derive one from a basename or substitute another asset. + const existing = files.get(relativePath); + if (existing && !sameFileList([existing], [file])) { + throw new Error('Conflicting workspace file resolver identity'); + } + files.set(relativePath, file); + } +} + function normalizeRemoteFiles(items: any[], baseURL: string): FileInfo[] { return items.map((item: any) => { const filename = item.filename || ''; @@ -60,7 +104,10 @@ function sameFileList(left: FileInfo[], right: FileInfo[]): boolean { file.artifactId === other?.artifactId && file.name === other?.name && file.type === other?.type && - file.isRemote === other?.isRemote + file.isRemote === other?.isRemote && + file.size === other?.size && + file.modifiedAt === other?.modifiedAt && + file.mimeType === other?.mimeType ); }); } @@ -79,44 +126,92 @@ export function useProjectOutputFiles( const host = useHost(); const email = useAuthStore((s) => s.email); const userId = useAuthStore((s) => s.user_id); - const [files, setFiles] = useState([]); + const ipcRenderer = host?.ipcRenderer; + const [resolved, setResolved] = useState<{ + requestKey: string; + ipcRenderer: typeof ipcRenderer; + files: FileInfo[]; + } | null>(null); const outputFilesRevision = getSidePanelOutputFilesRevision(activeTask); const taskFinished = activeTask?.status === ChatTaskStatus.FINISHED; - const workspaceRelativePathsKey = workspaceRelativePaths.join('\0'); + // JSON preserves path boundaries, including invalid embedded NULs. A NUL + // delimiter would silently turn one invalid identity into two valid ones. + const workspaceRelativePathsKey = JSON.stringify([ + ...new Set(workspaceRelativePaths), + ]); + const requestKey = JSON.stringify([ + email, + userId, + projectId, + taskId, + workspaceRoot, + workspaceRelativePathsKey, + outputFilesRevision, + taskFinished, + ]); useEffect(() => { let cancelled = false; + // Discard the previous snapshot even if this request never finishes. + // Otherwise A -> B (pending) -> A could revive A's old result by key. + setResolved(null); const loadFiles = async () => { if (!projectId || !email) { - if (!cancelled) setFiles([]); + if (!cancelled) setResolved(null); return; } let nextFiles: FileInfo[] = []; let localLookupSucceeded = false; - const ipcRenderer = host?.ipcRenderer; + const usesWorkspaceResolver = Boolean( + workspaceRoot && ipcRenderer?.invoke + ); if (ipcRenderer?.invoke) { if (workspaceRoot) { try { - // Keep registration and enumeration ordered so switching between - // Spaces cannot race Layout's root-registration effect. - await ipcRenderer.invoke('set-local-file-preview-roots', [ - workspaceRoot, - ]); - const workspaceFiles = await ipcRenderer.invoke( - 'get-workspace-file-list', - workspaceRoot, - workspaceRelativePathsKey - ? workspaceRelativePathsKey.split('\0') - : [] - ); - if (Array.isArray(workspaceFiles)) { - localLookupSucceeded = true; - nextFiles = workspaceFiles; + const paths: string[] = JSON.parse(workspaceRelativePathsKey); + if (paths.some((path) => !normalizeWorkspaceRelativePath(path))) { + throw new Error('Invalid workspace-relative file identity'); } + // Keep registration and enumeration ordered so switching between + // Spaces does not issue new lookups from a cancelled request. + // Main still authorizes every batch against the current root set. + const registration = await ipcRenderer.invoke( + 'set-local-file-preview-roots', + [workspaceRoot] + ); + if (cancelled) return; + if (registration?.success !== true || registration.roots !== 1) { + throw new Error('Workspace preview root registration failed'); + } + const workspaceFiles = new Map(); + for ( + let index = 0; + index < paths.length; + index += FILE_PREVIEW_LIMITS.workspaceResolverPaths + ) { + const requested = paths.slice( + index, + index + FILE_PREVIEW_LIMITS.workspaceResolverPaths + ); + const batch: unknown = await ipcRenderer.invoke( + 'get-workspace-file-list', + workspaceRoot, + requested + ); + if (cancelled) return; + mergeWorkspaceFileBatch(workspaceFiles, batch, requested); + } + // Publish once, after every batch has passed. An empty manifest + // must not cause a filesystem scan or invent durable file rows. + nextFiles = [...workspaceFiles.values()].sort((left, right) => + left.path.localeCompare(right.path) + ); + localLookupSucceeded = true; } catch (error) { + if (cancelled) return; console.warn( '[SidePanel] Failed to resolve Space workspace files:', error @@ -124,9 +219,9 @@ export function useProjectOutputFiles( } } - // Compatibility fallback for Projects that still use the legacy - // ~/eigent//project_ storage layout. - if (!localLookupSucceeded) { + // Compatibility only for Projects without an owning workspace root. + // Workspace failures must not escape into legacy or HTTP resolution. + if (!workspaceRoot) { try { const localFiles = await ipcRenderer.invoke( 'get-project-file-list', @@ -134,11 +229,13 @@ export function useProjectOutputFiles( projectId, userId ); + if (cancelled) return; if (Array.isArray(localFiles)) { localLookupSucceeded = true; nextFiles = localFiles; } } catch (error) { + if (cancelled) return; console.warn( '[SidePanel] Failed to fetch local project files:', error @@ -150,9 +247,10 @@ export function useProjectOutputFiles( // Electron already has the authoritative local file list. Local-proxy // mode only changes where Brain HTTP points; it must not force a second, // identical /files request after IPC succeeded. - if (!localLookupSucceeded) { + if (!localLookupSucceeded && !usesWorkspaceResolver) { try { const baseURL = await getBaseURL(); + if (cancelled) return; if (baseURL) { const listRes = await fetchGet('/files', { project_id: projectId, @@ -173,8 +271,12 @@ export function useProjectOutputFiles( if (!cancelled) { const visibleFiles = filterVisibleAgentFiles(nextFiles); - setFiles((current) => - sameFileList(current, visibleFiles) ? current : visibleFiles + setResolved((current) => + current?.requestKey === requestKey && + current.ipcRenderer === ipcRenderer && + sameFileList(current.files, visibleFiles) + ? current + : { requestKey, ipcRenderer, files: visibleFiles } ); } }; @@ -186,9 +288,10 @@ export function useProjectOutputFiles( }; }, [ email, - host?.ipcRenderer, + ipcRenderer, outputFilesRevision, projectId, + requestKey, taskFinished, taskId, userId, @@ -196,5 +299,10 @@ export function useProjectOutputFiles( workspaceRoot, ]); - return files; + // Do not expose the previous Space/Session/scope snapshot even for the + // render before the next effect starts. Late responses cannot republish it. + return resolved?.requestKey === requestKey && + resolved.ipcRenderer === ipcRenderer + ? resolved.files + : EMPTY_FILES; } diff --git a/src/shared/filePreviewContract.ts b/src/shared/filePreviewContract.ts index 0498eab9c..363a6316a 100644 --- a/src/shared/filePreviewContract.ts +++ b/src/shared/filePreviewContract.ts @@ -15,6 +15,7 @@ import i18next from 'i18next'; export const FILE_PREVIEW_LIMITS = { + workspaceResolverPaths: 500, csvScanBytes: 2 * 1024 * 1024, csvRows: 500, csvColumns: 50, @@ -155,6 +156,12 @@ export function decideFilePreview( const normalized = normalizePreviewFileType(type); const size = metadata.size; + // Native Blender projects are binary assets, not text or browser media. + // Keep the existing external-open action without decoding them as text. + if (normalized === 'blend') { + return { mode: 'blocked', limit: null, reason: 'unsupported' }; + } + if (normalized === 'csv' || normalized === 'tsv') { return { mode: 'bounded-csv', limit: FILE_PREVIEW_LIMITS.csvScanBytes }; } diff --git a/test/unit/components/Folder/FilePreview.test.tsx b/test/unit/components/Folder/FilePreview.test.tsx index a06f75618..abc053ad9 100644 --- a/test/unit/components/Folder/FilePreview.test.tsx +++ b/test/unit/components/Folder/FilePreview.test.tsx @@ -55,13 +55,22 @@ vi.mock('@/components/Folder/index', () => ({ FileViewerPanel: ({ selectedFile, onRevealFile, + onOpenExternalFile, }: { selectedFile: FileInfo | null; onRevealFile: () => void; + onOpenExternalFile: () => void; }) => ( - + <> + + {selectedFile?.preview?.kind === 'blocked' && ( + + )} + ), })); @@ -100,4 +109,37 @@ describe('FilePreview', () => { ) ); }); + + it('opens an unsupported local Blender file only through the existing workspace action on a user click', async () => { + loadFilePreviewMock.mockImplementation(async (file) => ({ + ...file, + content: undefined, + preview: { + kind: 'blocked', + reason: 'unsupported', + size: 2048, + limit: null, + }, + })); + render( + + ); + const openButton = await screen.findByRole('button', { + name: 'Open externally', + }); + expect(invokeMock).not.toHaveBeenCalled(); + fireEvent.click(openButton); + expect(invokeMock).toHaveBeenCalledWith( + 'open-local-file', + '/workspace/scene.blend' + ); + expect(invokeMock).toHaveBeenCalledTimes(1); + }); }); diff --git a/test/unit/components/Folder/FileViewerPanel.test.tsx b/test/unit/components/Folder/FileViewerPanel.test.tsx index bf1df1f3d..2e4d79693 100644 --- a/test/unit/components/Folder/FileViewerPanel.test.tsx +++ b/test/unit/components/Folder/FileViewerPanel.test.tsx @@ -286,10 +286,59 @@ describe('FileViewerPanel toolbar', () => { expect(screen.queryByRole('button', { name: 'Download file' })).toBeNull(); }); + it('explains unsupported Blender preview and preserves the existing external-open action', async () => { + renderViewer( + textFile({ + name: 'scene.blend', + type: 'blend', + path: '/workspace/scene.blend', + relativePath: 'scene.blend', + content: undefined, + preview: { + kind: 'blocked', + reason: 'unsupported', + size: 2048, + limit: null, + }, + }) + ); + expect(screen.getByText('Preview not loaded')).toBeInTheDocument(); + expect( + screen.getByText( + 'This file type cannot be safely previewed in this environment.' + ) + ).toBeInTheDocument(); + expect(screen.queryByTestId('source-code-viewer')).toBeNull(); + expect(screen.queryByRole('button', { name: 'Download' })).toBeNull(); + await userEvent + .setup() + .click(screen.getByRole('button', { name: 'Open externally' })); + expect(callbacks.onOpenExternalFile).toHaveBeenCalledTimes(1); + }); + + it('renders an authorized MP4 with the existing native video controls', () => { + const { container } = renderViewer( + textFile({ + name: 'final.mp4', + type: 'mp4', + path: '/workspace/final.mp4', + relativePath: 'final.mp4', + content: 'localfile://preview/?path=%2Fworkspace%2Ffinal.mp4', + }) + ); + const video = container.querySelector('video'); + expect(video).toHaveAttribute('controls'); + expect(video).toHaveAttribute( + 'src', + 'localfile://preview/?path=%2Fworkspace%2Ffinal.mp4' + ); + expect(screen.queryByText('Preview not loaded')).toBeNull(); + }); + it('keeps folder destinations available while hiding file-only actions', async () => { const user = userEvent.setup(); const openFolder = vi.fn(); - renderViewer( + const { unmount } = renderViewer( textFile({ name: 'src', path: 'src', type: '', isFolder: true }), { openInActions: [ @@ -311,10 +360,47 @@ describe('FileViewerPanel toolbar', () => { expect(screen.queryByRole('button', { name: 'Preview' })).toBeNull(); expect(screen.queryByRole('button', { name: 'Download file' })).toBeNull(); - await user.click(screen.getByRole('button', { name: 'Open in' })); - await user.click( - await screen.findByRole('menuitem', { name: 'Open in Finder' }) - ); - expect(openFolder).toHaveBeenCalledTimes(1); + const assertNoNativeTopLayer = () => { + expect(document.querySelector('dialog, [popover]')).toBeNull(); + expect(document.fullscreenElement ?? null).toBeNull(); + }; + assertNoNativeTopLayer(); + + // Floating UI's exact :modal query recurses through jsdom/nwsapi. This + // Radix menu uses ordinary DOM, so isolate only that query for this case. + // Keep preconditions outside matches: Floating UI catches selector errors. + const originalMatches = Element.prototype.matches; + const matchesSpy = vi + .spyOn(Element.prototype, 'matches') + .mockImplementation(function (this: Element, selector: string) { + return selector === ':modal' + ? false + : originalMatches.call(this, selector); + }); + try { + const openInButton = screen.getByRole('button', { name: 'Open in' }); + expect(openInButton).toBeVisible(); + expect(openInButton.matches('button')).toBe(true); + expect(openInButton.matches('dialog')).toBe(false); + expect(() => openInButton.matches('[')).toThrow(); + expect(openFolder).not.toHaveBeenCalled(); + + await user.click(openInButton); + const destination = await screen.findByRole('menuitem', { + name: 'Open in Finder', + }); + assertNoNativeTopLayer(); + expect(destination).toBeVisible(); + expect(openFolder).not.toHaveBeenCalled(); + await user.click(destination); + expect(openFolder).toHaveBeenCalledTimes(1); + } finally { + try { + unmount(); + } finally { + matchesSpy.mockRestore(); + expect(Element.prototype.matches).toBe(originalMatches); + } + } }); }); diff --git a/test/unit/components/Session/ActivityPanel.test.tsx b/test/unit/components/Session/ActivityPanel.test.tsx index ffefb7080..dff1e9ae4 100644 --- a/test/unit/components/Session/ActivityPanel.test.tsx +++ b/test/unit/components/Session/ActivityPanel.test.tsx @@ -349,6 +349,101 @@ describe('SessionActivityPanel project scope', () => { ); }); + it('keeps Latest empty without registered output and shows only durable historical files in All', async () => { + const scopedOverview = overview('run-current'); + const historical = { + ...overview('run-old').currentRun, + isCurrent: false, + createdAt: 500, + nodes: [ + 'output/final.mp4', + 'output/scene.blend', + 'output/frames/frame.png', + ].map((relativePath, index): ChatProjectionNode => ({ + id: `artifact-${index}`, + eventId: `artifact-${index}`, + eventType: 'artifact.created', + projectId: 'project-1', + runId: 'run-old', + runSequence: index + 1, + cloudCursor: index + 1, + createdAt: new Date(500).toISOString(), + legacyStep: null, + kind: 'artifact', + operation: 'created', + artifactId: `artifact-${index}`, + path: relativePath, + relativePath, + name: relativePath.split('/').at(-1), + })), + }; + mocks.overviews['project-1'] = { + ...scopedOverview, + historicalRuns: [historical], + runs: [scopedOverview.currentRun, historical], + }; + // The replacement frame has the same basename, but no durable identity + // authorizes it to replace the historical frame or create a new row. + mocks.projectFiles = [ + 'output/final.mp4', + 'output/scene.blend', + 'output/resume_frames/frame.png', + 'unregistered.txt', + ].map((relativePath) => ({ + name: relativePath.split('/').at(-1), + type: relativePath.split('.').at(-1), + relativePath, + path: `/workspace/space-one/${relativePath}`, + })); + const snapshot = JSON.stringify(mocks.overviews); + const { rerender } = render(); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 40)); + }); + expect(screen.getByText('No output files yet.')).toBeInTheDocument(); + expect(screen.queryByText('unregistered.txt')).toBeNull(); + expect(mocks.projectOutputResolver).toHaveBeenLastCalledWith( + 'project-1', + undefined, + null, + '/workspace/space-one', + [] + ); + + rerender(); + const video = await screen.findByRole('button', { name: 'final.mp4' }); + fireEvent.click(video); + expect(mocks.openFilePreview).toHaveBeenLastCalledWith( + expect.objectContaining({ + path: '/workspace/space-one/output/final.mp4', + artifactId: 'artifact-0', + }) + ); + fireEvent.click(screen.getByRole('button', { name: 'scene.blend' })); + expect(mocks.openFilePreview).toHaveBeenLastCalledWith( + expect.objectContaining({ type: 'blend', artifactId: 'artifact-1' }) + ); + expect(screen.getByText('Preview unavailable')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /frame.png/ })).toBeNull(); + expect(screen.queryByText('unregistered.txt')).toBeNull(); + expect(mocks.projectOutputResolver).toHaveBeenLastCalledWith( + 'project-1', + undefined, + null, + '/workspace/space-one', + expect.arrayContaining([ + 'output/final.mp4', + 'output/scene.blend', + 'output/frames/frame.png', + ]) + ); + + rerender(); + await waitFor(() => expect(screen.queryByText('final.mp4')).toBeNull()); + expect(screen.getByText('No output files yet.')).toBeInTheDocument(); + expect(JSON.stringify(mocks.overviews)).toBe(snapshot); + }); + it('shows durable subagent tool calls in their own panel category', async () => { mocks.chatStore = chatStore('run-1'); const scopedOverview = overview('run-1'); diff --git a/test/unit/components/Session/SidePanelSections/useProjectOutputFiles.test.tsx b/test/unit/components/Session/SidePanelSections/useProjectOutputFiles.test.tsx index 0c83cd90f..1cee9fde0 100644 --- a/test/unit/components/Session/SidePanelSections/useProjectOutputFiles.test.tsx +++ b/test/unit/components/Session/SidePanelSections/useProjectOutputFiles.test.tsx @@ -12,13 +12,33 @@ // limitations under the License. // ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. ========= +import { + mergeProjectFiles, + type SessionFileItem, +} from '@/components/Session/SidePanel/sections/buildProjectSessionPanelData'; import { useProjectOutputFiles } from '@/components/Session/SidePanel/sections/useProjectOutputFiles'; import { HostProvider } from '@/host'; import { useAuthStore } from '@/store/authStore'; import { ChatTaskStatus } from '@/types/constants'; import { act, renderHook, waitFor } from '@testing-library/react'; +import { + mkdir, + mkdtemp, + realpath, + rm, + symlink, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; import type { ReactNode } from 'react'; import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { FileReader } from '../../../../../electron/main/fileReader'; + +vi.mock('electron', () => ({ + app: { getPath: vi.fn(() => '') }, + BrowserWindow: class BrowserWindow {}, +})); const { fetchGetMock, getBaseURLMock, invokeMock } = vi.hoisted(() => ({ fetchGetMock: vi.fn(), @@ -162,6 +182,87 @@ describe('useProjectOutputFiles', () => { expect(fetchGetMock).not.toHaveBeenCalled(); }); + it('keeps a normal artifact previewable when the real resolver omits a directory symlink alias', async () => { + const workspace = await realpath( + await mkdtemp(path.join(tmpdir(), 'eigent-resolver-boundary-')) + ); + let unmount = () => {}; + try { + await mkdir(path.join(workspace, 'archive')); + await writeFile( + path.join(workspace, 'archive/frame.txt'), + 'synthetic archived frame' + ); + await writeFile( + path.join(workspace, 'final.mp4'), + 'resolver metadata fixture, not playable media' + ); + await symlink( + path.join(workspace, 'archive'), + path.join(workspace, 'frames'), + 'junction' + ); + const requested = ['final.mp4', 'frames/frame.txt']; + const reader = new FileReader(null as never); + invokeMock.mockImplementation(async (channel, root, paths) => { + if (channel === 'set-local-file-preview-roots') { + return { success: true, roots: 1 }; + } + if (channel === 'get-workspace-file-list') { + return reader.getWorkspaceFileList(root, paths); + } + throw new Error(`Unexpected IPC channel: ${channel}`); + }); + const items: SessionFileItem[] = requested.map((relativePath, index) => ({ + id: `artifact-${index}`, + file: { + name: relativePath.split('/').at(-1) || '', + path: relativePath, + relativePath, + type: index === 0 ? 'mp4' : 'txt', + artifactId: `artifact-${index}`, + }, + previewable: false, + taskId: 'run-fixture', + historical: false, + createdAt: 1, + updatedAt: 1, + })); + const originalItems = JSON.stringify(items); + const view = renderHook( + () => + useProjectOutputFiles( + 'project_one', + { status: ChatTaskStatus.FINISHED, taskAssigning: [] }, + 'run-fixture', + workspace, + requested + ), + { wrapper } + ); + unmount = view.unmount; + await act(async () => {}); + + const merged = mergeProjectFiles(items, view.result.current); + expect(merged[0]).toMatchObject({ + previewable: true, + file: { + relativePath: 'final.mp4', + path: path.join(workspace, 'final.mp4'), + }, + }); + expect(merged[1]).toEqual(items[1]); + expect(view.result.current.map((file) => file.relativePath)).toEqual([ + 'final.mp4', + ]); + expect(JSON.stringify(items)).toBe(originalItems); + expectNoFallback(); + } finally { + unmount(); + await rm(workspace, { recursive: true, force: true }); + } + }); + it('does not reload files for agent-only live status changes', async () => { const { rerender } = renderHook( ({ agentStatus }) => @@ -193,6 +294,380 @@ describe('useProjectOutputFiles', () => { expect(fetchGetMock).not.toHaveBeenCalled(); }); + function outputPaths(count: number) { + return Array.from( + { length: count }, + (_, index) => `output/frame-${String(index).padStart(4, '0')}.png` + ); + } + + function resolvedFiles( + paths: readonly string[], + root = '/workspace/space-one' + ) { + return paths.map((relativePath) => ({ + name: relativePath.split('/').at(-1) || '', + type: 'png', + path: `${root}/${relativePath}`, + relativePath, + })); + } + + function mockWorkspaceResolver() { + invokeMock.mockImplementation(async (channel, root, paths: string[]) => { + if (channel === 'set-local-file-preview-roots') { + return { success: true, roots: 1 }; + } + if (channel === 'get-workspace-file-list') { + // Model the existing Electron contract, independently of the renderer. + if (!Array.isArray(paths) || paths.length > 500) { + throw new Error('Invalid workspace file resolver request'); + } + return resolvedFiles(paths, root).reverse(); + } + throw new Error(`Unexpected IPC channel: ${channel}`); + }); + } + + function renderWorkspace(paths: readonly string[]) { + return renderHook( + (props) => + useProjectOutputFiles( + props.projectId, + { status: ChatTaskStatus.RUNNING, taskAssigning: [] }, + 'task_one', + props.root, + props.paths + ), + { + wrapper, + initialProps: { + projectId: 'project_one', + root: '/workspace/space-one', + paths, + }, + } + ); + } + + function expectNoFallback() { + expect( + invokeMock.mock.calls.some( + ([channel]) => channel === 'get-project-file-list' + ) + ).toBe(false); + expect(getBaseURLMock).not.toHaveBeenCalled(); + expect(fetchGetMock).not.toHaveBeenCalled(); + } + + it.each([0, 1, 499, 500, 501, 1001])( + 'resolves %i paths in ordered batches of at most 500', + async (count) => { + mockWorkspaceResolver(); + const paths = outputPaths(count); + const { result } = renderWorkspace(paths); + await act(async () => {}); + + expect(result.current.map((file) => file.relativePath)).toEqual(paths); + const calls = invokeMock.mock.calls.filter( + ([channel]) => channel === 'get-workspace-file-list' + ); + expect(calls).toHaveLength(Math.ceil(count / 500)); + expect(calls.flatMap((call) => call[2])).toEqual(paths); + expect(calls.every((call) => call[2].length <= 500)).toBe(true); + expectNoFallback(); + } + ); + + it('deduplicates before batching and keeps a stable sorted result', async () => { + mockWorkspaceResolver(); + const paths = outputPaths(501).reverse(); + const requested = [...paths, ...paths, paths[0]]; + const { result } = renderWorkspace(requested); + await act(async () => {}); + + expect(result.current.map((file) => file.relativePath)).toEqual( + outputPaths(501) + ); + const calls = invokeMock.mock.calls.filter( + ([channel]) => channel === 'get-workspace-file-list' + ); + expect(calls.map((call) => call[2].length)).toEqual([500, 1]); + expect(calls.flatMap((call) => call[2])).toEqual(paths); + expect(requested).toEqual([...paths, ...paths, paths[0]]); + expectNoFallback(); + }); + + it('discards a successful first batch when the second batch fails, without fallback', async () => { + mockWorkspaceResolver(); + const resolver = invokeMock.getMockImplementation()!; + let batches = 0; + invokeMock.mockImplementation(async (...args) => { + if (args[0] === 'get-workspace-file-list' && ++batches === 2) { + throw new Error('Preview file is outside the active workspace'); + } + return resolver(...args); + }); + const { result } = renderWorkspace(outputPaths(1001)); + await act(async () => {}); + + expect(result.current).toEqual([]); + expect(batches).toBe(2); + expectNoFallback(); + }); + + it('never splits a NUL-containing path into valid file identities', async () => { + mockWorkspaceResolver(); + const { result } = renderWorkspace(['report.md\0secret.md']); + await act(async () => {}); + + expect(result.current).toEqual([]); + expect( + invokeMock.mock.calls.filter( + ([channel]) => channel === 'get-workspace-file-list' + ) + ).toEqual([]); + expectNoFallback(); + }); + + it.each([ + '../secret.txt', + '/outside/report.md', + 'C:\\outside\\report.md', + '%2e%2e/secret.txt', + 'https://example.test/report.md', + ])('fails closed for invalid workspace identity %s', async (path) => { + mockWorkspaceResolver(); + const { result } = renderWorkspace(['report.md', path]); + await act(async () => {}); + expect(result.current).toEqual([]); + expect( + invokeMock.mock.calls.filter( + ([channel]) => channel === 'get-workspace-file-list' + ) + ).toEqual([]); + expectNoFallback(); + }); + + it.each([undefined, { success: false }, { success: true, roots: 0 }])( + 'requires successful workspace root registration (%j)', + async (registration) => { + invokeMock.mockResolvedValue(registration); + const { result } = renderWorkspace(['report.md']); + await act(async () => {}); + expect(result.current).toEqual([]); + expect(invokeMock).toHaveBeenCalledTimes(1); + expectNoFallback(); + } + ); + + it.each([ + null, + { files: [] }, + [null], + [{ name: 'report.md', type: 'md', path: '/workspace/space-one/report.md' }], + [ + { + name: 'unrequested.md', + type: 'md', + path: '/workspace/space-one/unrequested.md', + relativePath: 'unrequested.md', + }, + ], + [ + { + name: 'report.md', + type: 'md', + path: 'https://files.example/report.md', + relativePath: 'report.md', + isRemote: true, + }, + ], + [ + { + name: 'report.md', + type: 'md', + path: 'report.md', + relativePath: 'report.md', + }, + ], + ])( + 'rejects malformed or unrequested resolver results (%j)', + async (batch) => { + invokeMock.mockImplementation(async (channel) => + channel === 'set-local-file-preview-roots' + ? { success: true, roots: 1 } + : batch + ); + const { result } = renderWorkspace(['report.md']); + await act(async () => {}); + expect(result.current).toEqual([]); + expectNoFallback(); + } + ); + + it('deduplicates identical results but rejects conflicting identities', async () => { + const file = resolvedFiles(['report.md'])[0]; + invokeMock.mockImplementation(async (channel) => + channel === 'set-local-file-preview-roots' + ? { success: true, roots: 1 } + : [file, { ...file }] + ); + const { result, rerender } = renderWorkspace(['report.md']); + await act(async () => {}); + expect(result.current).toEqual([file]); + + invokeMock.mockImplementation(async (channel) => + channel === 'set-local-file-preview-roots' + ? { success: true, roots: 1 } + : [file, { ...file, path: '/workspace/space-one/other.md' }] + ); + rerender({ + projectId: 'project_one', + root: '/workspace/space-one', + paths: ['report.md', 'other.md'], + }); + await act(async () => {}); + expect(result.current).toEqual([]); + expectNoFallback(); + }); + + it('publishes all batches together and clears earlier results when a refresh fails', async () => { + mockWorkspaceResolver(); + const { result, rerender } = renderWorkspace(outputPaths(1)); + await act(async () => {}); + expect(result.current).toHaveLength(1); + + const resolver = invokeMock.getMockImplementation()!; + let rejectBatch: (reason: Error) => void = () => {}; + let batches = 0; + invokeMock.mockImplementation(async (...args) => { + if (args[0] === 'get-workspace-file-list' && ++batches === 2) { + return new Promise((_, reject) => { + rejectBatch = reject; + }); + } + return resolver(...args); + }); + rerender({ + projectId: 'project_one', + root: '/workspace/space-one', + paths: outputPaths(501), + }); + expect(result.current).toEqual([]); + await act(async () => {}); + expect(batches).toBe(2); + expect(result.current).toEqual([]); + await act(async () => { + rejectBatch(new Error('batch failed')); + }); + expect(result.current).toEqual([]); + expectNoFallback(); + }); + + it.each(['registration', 'batch'])( + 'stops obsolete requests after pending %s when switching Spaces', + async (pendingStage) => { + mockWorkspaceResolver(); + const resolver = invokeMock.getMockImplementation()!; + let completeOld: (value: unknown) => void = () => {}; + invokeMock.mockImplementation(async (...args) => { + const oldRegistration = + pendingStage === 'registration' && + args[0] === 'set-local-file-preview-roots' && + args[1][0] === '/workspace/space-one'; + const oldBatch = + pendingStage === 'batch' && + args[0] === 'get-workspace-file-list' && + args[1] === '/workspace/space-one'; + if (oldRegistration || oldBatch) { + return new Promise((resolve) => { + completeOld = resolve; + }); + } + return resolver(...args); + }); + const { result, rerender } = renderWorkspace(outputPaths(1001)); + await act(async () => {}); + rerender({ + projectId: 'project_two', + root: '/workspace/space-two', + paths: ['report.md'], + }); + expect(result.current).toEqual([]); + await act(async () => {}); + expect(result.current).toEqual( + resolvedFiles(['report.md'], '/workspace/space-two') + ); + const calls = invokeMock.mock.calls.length; + await act(async () => { + completeOld( + pendingStage === 'registration' + ? { success: true, roots: 1 } + : resolvedFiles(outputPaths(500)) + ); + }); + expect(invokeMock).toHaveBeenCalledTimes(calls); + expect(result.current).toEqual( + resolvedFiles(['report.md'], '/workspace/space-two') + ); + expectNoFallback(); + } + ); + + it('stops after unmount even if root registration rejects', async () => { + let rejectRegistration: (reason: Error) => void = () => {}; + invokeMock.mockImplementation( + () => + new Promise((_, reject) => { + rejectRegistration = reject; + }) + ); + const { unmount } = renderWorkspace(['report.md']); + unmount(); + await act(async () => { + rejectRegistration(new Error('registration rejected')); + }); + expect(invokeMock).toHaveBeenCalledTimes(1); + expectNoFallback(); + }); + + it('does not revive a previous snapshot when returning to a Space before another lookup finishes', async () => { + mockWorkspaceResolver(); + const paths = ['report.md']; + const { result, rerender } = renderWorkspace(paths); + await act(async () => {}); + expect(result.current).toHaveLength(1); + + const pending = new Map void>(); + invokeMock.mockImplementation(async (channel, root) => { + if (channel === 'set-local-file-preview-roots') { + return { success: true, roots: 1 }; + } + return new Promise((resolve) => pending.set(root, resolve)); + }); + rerender({ projectId: 'project_two', root: '/workspace/space-two', paths }); + await act(async () => {}); + expect(result.current).toEqual([]); + + rerender({ projectId: 'project_one', root: '/workspace/space-one', paths }); + expect(result.current).toEqual([]); + await act(async () => {}); + expect(result.current).toEqual([]); + + await act(async () => { + pending.get('/workspace/space-two')?.( + resolvedFiles(paths, '/workspace/space-two') + ); + }); + expect(result.current).toEqual([]); + await act(async () => { + pending.get('/workspace/space-one')?.(resolvedFiles(paths)); + }); + expect(result.current).toEqual(resolvedFiles(paths)); + expectNoFallback(); + }); + it('treats an empty Electron file list as authoritative', async () => { invokeMock.mockResolvedValue([]); diff --git a/test/unit/components/buildProjectSessionPanelData.test.ts b/test/unit/components/buildProjectSessionPanelData.test.ts index f3e5e518c..9f86dc087 100644 --- a/test/unit/components/buildProjectSessionPanelData.test.ts +++ b/test/unit/components/buildProjectSessionPanelData.test.ts @@ -670,6 +670,91 @@ describe('buildProjectSessionPanelData', () => { ).toEqual([]); }); + it.each([ + { + relativePath: 'output/resume_frames/frame.png', + path: '/workspace/output/resume_frames/frame.png', + }, + { relativePath: '../frame.png', path: '/outside/frame.png' }, + { relativePath: 'output/frames/frame.png', path: '' }, + ])( + 'does not revive a stale artifact using conflicting resolver identity %j', + (location) => { + const runs = [ + makeRun('run-old', false, [ + { + ...baseNode('run-old', 'artifact-old', 1), + kind: 'artifact', + operation: 'created', + artifactId: 'artifact-frame', + relativePath: 'output/frames/frame.png', + path: 'output/frames/frame.png', + name: 'frame.png', + }, + ]), + ]; + const snapshot = JSON.stringify(runs); + const items = buildProjectSessionPanelData(runs, []).files; + const merged = mergeProjectFiles(items, [ + { + name: 'frame.png', + type: 'png', + artifactId: 'artifact-frame', + ...location, + }, + ]); + expect(merged).toEqual(items); + expect(merged[0].previewable).toBe(false); + expect(JSON.stringify(runs)).toBe(snapshot); + } + ); + + it('leaves ambiguous resolver matches unavailable without changing artifact rows', () => { + const items = buildProjectSessionPanelData( + [ + makeRun('run-current', true, [ + { + ...baseNode('run-current', 'artifact', 1), + kind: 'artifact', + operation: 'created', + artifactId: 'artifact-report', + relativePath: 'report.md', + path: 'report.md', + name: 'report.md', + }, + ]), + ], + [] + ).files; + expect( + mergeProjectFiles(items, [ + { + name: 'report.md', + type: 'md', + path: '/workspace/report.md', + relativePath: 'report.md', + }, + { + name: 'report.md', + type: 'md', + path: '/other/report.md', + relativePath: 'report.md', + }, + ]) + ).toEqual(items); + expect( + mergeProjectFiles(items, [ + { + name: 'report.md', + type: 'md', + path: '/workspace/report.md', + relativePath: 'report.md', + artifactId: 'another-artifact', + }, + ]) + ).toEqual(items); + }); + it('shows a trusted realtime write and converges on its terminal artifact', () => { const liveDecision = adaptChatProjectionEvent( normalizeLegacyChatStep( diff --git a/test/unit/electron/fileReaderPreview.test.ts b/test/unit/electron/fileReaderPreview.test.ts index 85c3cb903..0c32fd672 100644 --- a/test/unit/electron/fileReaderPreview.test.ts +++ b/test/unit/electron/fileReaderPreview.test.ts @@ -13,7 +13,17 @@ // ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. ========= import { FILE_PREVIEW_LIMITS } from '@/shared/filePreviewContract'; -import { mkdir, mkdtemp, rm, truncate, writeFile } from 'node:fs/promises'; +import { + mkdir, + mkdtemp, + readFile, + realpath, + rename, + rm, + symlink, + truncate, + writeFile, +} from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; @@ -88,9 +98,11 @@ describe('FileReader bounded preview', () => { }); it('resolves only requested files and rejects traversal', async () => { - const directory = await mkdtemp(path.join(tmpdir(), 'eigent-workspace-')); - temporaryDirectories.push(directory); - const outsideFile = path.join(path.dirname(directory), 'outside.txt'); + const fixture = await mkdtemp(path.join(tmpdir(), 'eigent-workspace-')); + temporaryDirectories.push(fixture); + const directory = path.join(fixture, 'workspace'); + await mkdir(directory); + const outsideFile = path.join(fixture, 'outside.txt'); await writeFile(path.join(directory, 'preview.png'), 'image'); await writeFile(outsideFile, 'secret'); @@ -112,6 +124,152 @@ describe('FileReader bounded preview', () => { } }); + it('keeps an empty manifest empty and excludes escapes and symlinks from requested resolution', async () => { + const fixture = await mkdtemp(path.join(tmpdir(), 'eigent-workspace-')); + temporaryDirectories.push(fixture); + const workspace = path.join(fixture, 'workspace'); + const outside = path.join(fixture, 'outside'); + await mkdir(workspace); + await mkdir(outside); + await writeFile( + path.join(workspace, 'final.mp4'), + 'resolver-only media fixture' + ); + await writeFile(path.join(workspace, 'scene.blend'), 'BLENDER-v300'); + await writeFile( + path.join(workspace, 'unregistered.txt'), + 'not an artifact' + ); + await writeFile( + path.join(outside, 'secret.txt'), + 'isolated secret fixture' + ); + await symlink( + path.join(outside, 'secret.txt'), + path.join(workspace, 'link.txt') + ); + await symlink(outside, path.join(workspace, 'linked-directory')); + await symlink( + path.join(workspace, 'final.mp4'), + path.join(workspace, 'alias.mp4') + ); + + const reader = new FileReader(null as never); + expect(reader.getWorkspaceFileList(workspace, [])).toEqual([]); + const files = reader.getWorkspaceFileList(workspace, [ + 'final.mp4', + 'final.mp4', + 'scene.blend', + 'missing.mp4', + '../outside/secret.txt', + path.join(outside, 'secret.txt'), + 'link.txt', + 'linked-directory/secret.txt', + 'alias.mp4', + 'final.mp4\0scene.blend', + '%2e%2e/outside/secret.txt', + 'https://example.test/final.mp4', + ]); + expect(files.map((file) => file.relativePath)).toEqual([ + 'final.mp4', + 'scene.blend', + ]); + expect(files[0]).toMatchObject({ + path: await realpath(path.join(workspace, 'final.mp4')), + type: 'mp4', + mimeType: 'video/mp4', + }); + expect(files[1]).toMatchObject({ + path: await realpath(path.join(workspace, 'scene.blend')), + type: 'blend', + }); + }); + + it('does not recover moved paths, discover replacements, or rewrite a manifest', async () => { + const workspace = await mkdtemp(path.join(tmpdir(), 'eigent-workspace-')); + temporaryDirectories.push(workspace); + await mkdir(path.join(workspace, 'frames')); + await mkdir(path.join(workspace, 'resume_frames')); + await writeFile(path.join(workspace, 'frames/frame.png'), 'fixture frame'); + const manifest = JSON.stringify({ + artifacts: [ + { artifact_id: 'old-frame', relative_path: 'frames/frame.png' }, + ], + }); + const manifestPath = path.join(workspace, 'manifest.json'); + await writeFile(manifestPath, manifest); + const reader = new FileReader(null as never); + expect( + reader.getWorkspaceFileList(workspace, ['frames/frame.png']) + ).toHaveLength(1); + await rename( + path.join(workspace, 'frames/frame.png'), + path.join(workspace, 'resume_frames/frame.png') + ); + expect( + reader.getWorkspaceFileList(workspace, ['frames/frame.png']) + ).toEqual([]); + expect(await readFile(manifestPath, 'utf8')).toBe(manifest); + expect( + reader.getWorkspaceFileList(workspace, ['resume_frames/frame.png'])[0] + .relativePath + ).toBe(path.join('resume_frames', 'frame.png')); + }); + + it('omits directory aliases whose real identity differs and retains explicitly requested canonical files', async () => { + const workspace = await mkdtemp(path.join(tmpdir(), 'eigent-workspace-')); + temporaryDirectories.push(workspace); + await mkdir(path.join(workspace, 'archive')); + await writeFile(path.join(workspace, 'archive/frame.txt'), 'fixture frame'); + await writeFile(path.join(workspace, 'final.mp4'), 'resolver-only fixture'); + await symlink( + path.join(workspace, 'archive'), + path.join(workspace, 'frames'), + 'junction' + ); + const reader = new FileReader(null as never); + + expect( + reader.getWorkspaceFileList(workspace, ['frames/frame.txt']) + ).toEqual([]); + const files = reader.getWorkspaceFileList(workspace, [ + 'frames/frame.txt', + 'archive/frame.txt', + 'final.mp4', + ]); + expect(files.map((file) => file.relativePath)).toEqual([ + path.join('archive', 'frame.txt'), + 'final.mp4', + ]); + expect(files[0].path).toBe( + await realpath(path.join(workspace, 'archive/frame.txt')) + ); + }); + + it('compares normalized identities while preserving native canonical paths', async () => { + const workspace = await mkdtemp(path.join(tmpdir(), 'eigent-workspace-')); + temporaryDirectories.push(workspace); + await mkdir(path.join(workspace, 'nested')); + await writeFile( + path.join(workspace, 'nested/report.txt'), + 'fixture report' + ); + const reader = new FileReader(null as never); + + for (const relativePath of [ + 'nested/report.txt', + './nested//./report.txt', + path.join('nested', 'report.txt'), + ]) { + const files = reader.getWorkspaceFileList(workspace, [relativePath]); + expect(files).toHaveLength(1); + expect(files[0]).toMatchObject({ + relativePath: path.join('nested', 'report.txt'), + path: await realpath(path.join(workspace, 'nested/report.txt')), + }); + } + }); + it('fails closed before fully reading oversized rich text', async () => { const filePath = await temporaryFile('large.md', ''); await truncate(filePath, FILE_PREVIEW_LIMITS.textBytes + 1); diff --git a/test/unit/lib/filePreviewContract.test.ts b/test/unit/lib/filePreviewContract.test.ts index c41a84024..240b6378a 100644 --- a/test/unit/lib/filePreviewContract.test.ts +++ b/test/unit/lib/filePreviewContract.test.ts @@ -19,6 +19,20 @@ import { import { describe, expect, it } from 'vitest'; describe('file preview policy', () => { + it('streams MP4 media but blocks native Blender projects as unsupported', () => { + expect(decideFilePreview('mp4', { size: 30_000_000 })).toEqual({ + mode: 'stream-media', + limit: null, + }); + for (const type of ['blend', '.BLEND']) { + expect(decideFilePreview(type, { size: 30_000_000 })).toEqual({ + mode: 'blocked', + reason: 'unsupported', + limit: null, + }); + } + }); + it('always routes CSV through the bounded reader', () => { expect(decideFilePreview('csv', { size: 2_000_000_000 })).toMatchObject({ mode: 'bounded-csv', diff --git a/test/unit/lib/filePreviewLoader.test.ts b/test/unit/lib/filePreviewLoader.test.ts index a8195ac98..66f433d06 100644 --- a/test/unit/lib/filePreviewLoader.test.ts +++ b/test/unit/lib/filePreviewLoader.test.ts @@ -50,6 +50,56 @@ describe('parseBoundedCsvPreview', () => { }); describe('loadFilePreview', () => { + it.each([ + { type: 'mp4', mimeType: 'video/mp4' }, + { type: 'blend', mimeType: 'application/octet-stream' }, + ])( + 'authorizes $type metadata without reading it as text or fetching HTTP', + async ({ type, mimeType }) => { + const invoke = vi.fn().mockResolvedValue({ size: 2048, mimeType }); + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + const result = await loadFilePreview( + { name: `final.${type}`, path: `/workspace/final.${type}`, type }, + { ipcRenderer: { invoke } } + ); + expect(invoke).toHaveBeenCalledTimes(1); + expect(invoke).toHaveBeenCalledWith( + 'get-file-preview-metadata', + `/workspace/final.${type}` + ); + expect(fetchMock).not.toHaveBeenCalled(); + if (type === 'blend') { + expect(result.content).toBeUndefined(); + expect(result.preview).toMatchObject({ + kind: 'blocked', + reason: 'unsupported', + }); + } else { + expect(result.content).toBe(toLocalPreviewUrl('/workspace/final.mp4')); + expect(result.preview).toBeUndefined(); + } + } + ); + + it('does not use HTTP after local metadata authorization fails', async () => { + const invoke = vi + .fn() + .mockRejectedValue( + new Error('Preview file is outside the active workspace') + ); + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + await expect( + loadFilePreview( + { name: 'final.mp4', path: '/outside/final.mp4', type: 'mp4' }, + { ipcRenderer: { invoke } } + ) + ).rejects.toThrow('outside the active workspace'); + expect(invoke).toHaveBeenCalledTimes(1); + expect(fetchMock).not.toHaveBeenCalled(); + }); + it('keeps an absolute local path out of the custom URL hostname', () => { expect(toLocalPreviewUrl('/Users/Example User/report.pdf')).toBe( 'localfile://preview/?path=%2FUsers%2FExample%20User%2Freport.pdf'