Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(file-preview): play local videos in the working panel (#20399)

Arvin Xu097b5f063687
diff --git a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
index e1ae2ef8670..92b40ee53c8 100644
--- a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
@@ -43,6 +43,11 @@ const DOCUMENT_PREVIEW_MIME_TYPES = new Set([
]);
const MAX_DOCUMENT_PREVIEW_BYTES = 20 * 1024 * 1024;
export const PREVIEW_CONTENT_SIZE_HEADER = 'X-Preview-Content-Size';
+/**
+ * The file's mtime in ms. Lets the renderer tell a replaced file from the
+ * previous one at the same path when a preview is refreshed.
+ */
+export const PREVIEW_MODIFIED_AT_HEADER = 'X-Preview-Modified-At';
// Edited-file records can carry `~`-prefixed paths (the file tools expand the
// home directory at write time) — expand them here so previews resolve the
@@ -219,6 +224,9 @@ export class LocalFileProtocolManager {
const contentType = await resolveMimeType(realResolvedPath, buffer);
headers.set('Content-Type', contentType);
headers.set('Content-Length', String(buffer.byteLength));
+ if (Number.isFinite(fileStat.mtimeMs)) {
+ headers.set(PREVIEW_MODIFIED_AT_HEADER, String(fileStat.mtimeMs));
+ }
// Module scripts, styles, media, and fonts require CORS when loaded
// by the opaque sandbox origin. Do not grant arbitrary text files
// (for example .env) readable cross-origin access.
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
index 17e2063ea59..4877c8b881d 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
@@ -115,6 +115,32 @@ describe('LocalFileProtocolManager', () => {
expect(response.headers.get('Content-Length')).toBe(String(pngBytes.byteLength));
});
+ it('exposes the file mtime so refreshed previews can detect a replaced file', async () => {
+ mockStat.mockImplementation(async () => ({
+ isFile: () => true,
+ mtimeMs: 1_700_000_000_123,
+ size: 4,
+ }));
+ mockReadFile.mockResolvedValue(Buffer.from('demo'));
+
+ const manager = new LocalFileProtocolManager();
+ manager.registerHandler();
+ await manager.approveWorkspaceRoot('/Users/alice/project');
+ const url = await manager.createPreviewUrl({
+ filePath: '/Users/alice/project/demo.mp4',
+ workspaceRoot: '/Users/alice/project',
+ });
+ if (!url) throw new Error('Expected local file preview URL');
+
+ const response = await protocolHandlerRef.current({
+ headers: new Headers(),
+ method: 'GET',
+ url,
+ });
+
+ expect(response.headers.get('X-Preview-Modified-At')).toBe('1700000000123');
+ });
+
it('short-circuits oversized documents without reading them', async () => {
const oversized = 20 * 1024 * 1024 + 1;
mockStat.mockImplementation(async () => ({ isFile: () => true, size: oversized }));
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index be7f6a176a8..34ef562111c 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2812,6 +2812,7 @@
"workingPanel.localFile.publish.uploadingProgress": "Uploading {{completed}} / {{total}} · {{percent}}%",
"workingPanel.localFile.publish.version": "Publish this version",
"workingPanel.localFile.sandboxUnavailable": "This file is no longer available — its sandbox environment has been recycled",
+ "workingPanel.localFile.tooLarge": "File too large to preview",
"workingPanel.localFile.truncated": "File preview truncated to {{limit}} characters",
"workingPanel.openMenu.configuration": "Configuration",
"workingPanel.openMenu.terminal": "Terminal",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 9dc3da6c2eb..d00e6917c74 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2812,6 +2812,7 @@
"workingPanel.localFile.publish.uploadingProgress": "正在上传 {{completed}} / {{total}} · {{percent}}%",
"workingPanel.localFile.publish.version": "发布此版本",
"workingPanel.localFile.sandboxUnavailable": "此文件已不可用——所在的沙盒环境已被回收",
+ "workingPanel.localFile.tooLarge": "文件过大,无法预览",
"workingPanel.localFile.truncated": "文件预览被截断至 {{limit}} 个字符",
"workingPanel.openMenu.configuration": "配置",
"workingPanel.openMenu.terminal": "终端",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index f128edeee71..fb0344141fb 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3141,6 +3141,7 @@ export default {
'workingPanel.localFile.publish.unresolvedLocals':
'This page still points at local files that were not packed, so those assets would break after publish.',
'workingPanel.localFile.publish.version': 'Publish this version',
+ 'workingPanel.localFile.tooLarge': 'File too large to preview',
'workingPanel.localFile.truncated': 'File preview truncated to {{limit}} characters',
'workingPanel.skills.actions.comingSoon': 'Coming soon',
'workingPanel.skills.actions.delete': 'Delete',
diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsx
index 87b9437dad0..68a6fab3bc9 100644
--- a/src/features/Portal/LocalFile/Body.tsx
+++ b/src/features/Portal/LocalFile/Body.tsx
@@ -32,6 +32,8 @@ import {
import { getFileExtension } from './Body.helpers';
import MarkdownImage from './MarkdownImage';
import PreviewToolbar, { ToolbarActionButton } from './PreviewToolbar';
+import UnsupportedPreview from './UnsupportedPreview';
+import VideoPreview from './VideoPreview';
// Deferred: pulls in react-pdf, only needed once a binary document is opened.
const DocumentPreview = lazy(() => import('@/features/FileViewer/Renderer/Document'));
@@ -495,6 +497,18 @@ const ActiveFileView = memo<ActiveFileViewProps>(
return <ImagePreview blob={preview.blob} filename={filename} />;
}
+ if (preview.type === 'video') {
+ return (
+ <VideoPreview
+ allowExternalFile={allowExternalFilePreview}
+ filePath={filePath}
+ key={filePath}
+ revision={preview.revision}
+ workingDirectory={workingDirectory}
+ />
+ );
+ }
+
if (preview.type === 'document') {
return (
<Suspense fallback={<Loading />}>
@@ -515,9 +529,11 @@ const ActiveFileView = memo<ActiveFileViewProps>(
if (preview.type !== 'text') {
return (
- <Center height={'100%'} width={'100%'}>
- <Empty description={t('workingPanel.localFile.binary')} />
- </Center>
+ <UnsupportedPreview
+ filePath={filePath}
+ isLocalFile={!sandboxTopicId && !deviceId && isDesktop}
+ oversized={preview.type === 'binary' && preview.oversized}
+ />
);
}
diff --git a/src/features/Portal/LocalFile/UnsupportedPreview.tsx b/src/features/Portal/LocalFile/UnsupportedPreview.tsx
new file mode 100644
index 00000000000..d255414c73d
--- /dev/null
+++ b/src/features/Portal/LocalFile/UnsupportedPreview.tsx
@@ -0,0 +1,52 @@
+import { Center, Flexbox } from '@lobehub/ui';
+import { Button, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import FileIcon from '@/components/FileIcon';
+import { localFileService } from '@/services/electron/localFileService';
+
+const styles = createStaticStyles(({ css }) => ({
+ icon: css`
+ width: 64px;
+ height: 64px;
+ border-radius: 14px;
+ background: ${cssVar.colorFillTertiary};
+ `,
+}));
+
+interface UnsupportedPreviewProps {
+ filePath: string;
+ /** Only a file on this desktop can be handed to the system default app. */
+ isLocalFile: boolean;
+ oversized?: boolean;
+}
+
+const UnsupportedPreview = memo<UnsupportedPreviewProps>(({ filePath, isLocalFile, oversized }) => {
+ const { t } = useTranslation('chat');
+ const filename = filePath.split(/[/\\]/).at(-1) ?? filePath;
+
+ return (
+ <Center gap={16} height={'100%'} width={'100%'}>
+ <Center className={styles.icon}>
+ <FileIcon fileName={filename} size={40} />
+ </Center>
+ <Flexbox align={'center'} gap={4}>
+ <Text style={{ fontWeight: 500 }}>{filename}</Text>
+ <Text type={'secondary'}>
+ {t(oversized ? 'workingPanel.localFile.tooLarge' : 'workingPanel.localFile.binary')}
+ </Text>
+ </Flexbox>
+ {isLocalFile && (
+ <Button onClick={() => localFileService.openLocalFile({ path: filePath })}>
+ {t('workingPanel.localFile.document.openWithDefaultApp')}
+ </Button>
+ )}
+ </Center>
+ );
+});
+
+UnsupportedPreview.displayName = 'UnsupportedPreview';
+
+export default UnsupportedPreview;
diff --git a/src/features/Portal/LocalFile/VideoPreview.tsx b/src/features/Portal/LocalFile/VideoPreview.tsx
new file mode 100644
index 00000000000..e71613bc7e2
--- /dev/null
+++ b/src/features/Portal/LocalFile/VideoPreview.tsx
@@ -0,0 +1,64 @@
+import { Center, Video } from '@lobehub/ui';
+import { memo, useEffect, useRef } from 'react';
+
+import Loading from '@/components/Loading/CircleLoading';
+
+import UnsupportedPreview from './UnsupportedPreview';
+import { useLocalVideo } from './useLocalVideo';
+
+interface VideoPreviewProps {
+ allowExternalFile?: boolean;
+ filePath: string;
+ revision: string;
+ workingDirectory: string;
+}
+
+/** Local desktop video player; see `useLocalVideo` for how the bytes are held. */
+const VideoPreview = memo<VideoPreviewProps>(
+ ({ allowExternalFile, filePath, revision, workingDirectory }) => {
+ const { markUnplayable, state } = useLocalVideo({
+ allowExternalFile,
+ filePath,
+ revision,
+ workingDirectory,
+ });
+ const wrapperRef = useRef<HTMLDivElement>(null);
+ const src = state.status === 'ready' ? state.src : undefined;
+
+ // A `video/*` MIME type does not mean Chromium can decode the container or
+ // codec. <Video> loads through a <source> child, whose `error` event does not
+ // bubble, so listen in the capture phase on the wrapper.
+ useEffect(() => {
+ const wrapper = wrapperRef.current;
+ if (!wrapper) return;
+
+ wrapper.addEventListener('error', markUnplayable, true);
+
+ return () => {
+ wrapper.removeEventListener('error', markUnplayable, true);
+ };
+ }, [markUnplayable, src]);
+
+ if (state.status === 'unplayable')
+ return <UnsupportedPreview isLocalFile filePath={filePath} oversized={state.oversized} />;
+ if (!src) return <Loading />;
+
+ return (
+ <Center height={'100%'} padding={16} width={'100%'}>
+ {/* Keyed by the object URL: <Video> feeds it through a <source> child,
+ which the element only picks up on mount. */}
+ <Video
+ key={src}
+ ref={wrapperRef}
+ src={src}
+ styles={{ video: { maxHeight: '100%', objectFit: 'contain' }, wrapper: { margin: 0 } }}
+ variant={'borderless'}
+ />
+ </Center>
+ );
+ },
+);
+
+VideoPreview.displayName = 'VideoPreview';
+
+export default VideoPreview;
diff --git a/src/features/Portal/LocalFile/useLocalVideo.test.ts b/src/features/Portal/LocalFile/useLocalVideo.test.ts
new file mode 100644
index 00000000000..4bc8d572dcb
--- /dev/null
+++ b/src/features/Portal/LocalFile/useLocalVideo.test.ts
@@ -0,0 +1,79 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useLocalVideo } from './useLocalVideo';
+
+const { readLocalVideo } = vi.hoisted(() => ({ readLocalVideo: vi.fn() }));
+
+vi.mock('@/services/electron/localFileService', () => ({
+ localFileService: { readLocalVideo },
+}));
+
+const params = { filePath: '/repo/demo.mp4', revision: '3:1', workingDirectory: '/repo' };
+
+describe('useLocalVideo', () => {
+ let urlCount = 0;
+ const createObjectURL = vi.fn(() => `blob:video-${++urlCount}`);
+ const revokeObjectURL = vi.fn();
+
+ beforeEach(() => {
+ urlCount = 0;
+ readLocalVideo.mockReset();
+ readLocalVideo.mockResolvedValue({ blob: new Blob(), ok: true });
+ vi.stubGlobal('URL', { ...URL, createObjectURL, revokeObjectURL });
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it('releases the blob when the video turns out to be undecodable', async () => {
+ const { result } = renderHook(() => useLocalVideo(params));
+ await waitFor(() =>
+ expect(result.current.state).toEqual({ src: 'blob:video-1', status: 'ready' }),
+ );
+
+ act(() => result.current.markUnplayable());
+
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:video-1');
+ expect(result.current.state).toEqual({ oversized: false, status: 'unplayable' });
+ });
+
+ it('re-reads the file when the preview revision changes', async () => {
+ const { result, rerender } = renderHook((props) => useLocalVideo(props), {
+ initialProps: params,
+ });
+ await waitFor(() =>
+ expect(result.current.state).toEqual({ src: 'blob:video-1', status: 'ready' }),
+ );
+
+ rerender({ ...params, revision: '4:2' });
+
+ await waitFor(() =>
+ expect(result.current.state).toEqual({ src: 'blob:video-2', status: 'ready' }),
+ );
+ expect(readLocalVideo).toHaveBeenCalledTimes(2);
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:video-1');
+ });
+
+ it('aborts an in-flight read on unmount', () => {
+ readLocalVideo.mockReturnValue(new Promise(() => {}));
+ const { unmount } = renderHook(() => useLocalVideo(params));
+ const signal = readLocalVideo.mock.calls[0][1] as AbortSignal;
+
+ expect(signal.aborted).toBe(false);
+ unmount();
+ expect(signal.aborted).toBe(true);
+ });
+
+ it('reports an oversized video as unplayable', async () => {
+ readLocalVideo.mockResolvedValue({ ok: false, reason: 'oversized' });
+ const { result } = renderHook(() => useLocalVideo(params));
+
+ await waitFor(() =>
+ expect(result.current.state).toEqual({ oversized: true, status: 'unplayable' }),
+ );
+ expect(createObjectURL).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Portal/LocalFile/useLocalVideo.ts b/src/features/Portal/LocalFile/useLocalVideo.ts
new file mode 100644
index 00000000000..b56a71113ef
--- /dev/null
+++ b/src/features/Portal/LocalFile/useLocalVideo.ts
@@ -0,0 +1,71 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { localFileService } from '@/services/electron/localFileService';
+
+export type LocalVideoState =
+ | { status: 'loading' }
+ | { src: string; status: 'ready' }
+ | { oversized: boolean; status: 'unplayable' };
+
+interface UseLocalVideoParams {
+ allowExternalFile?: boolean;
+ filePath: string;
+ /** Changes when the file at `filePath` is replaced; triggers a re-read. */
+ revision: string;
+ workingDirectory: string;
+}
+
+/**
+ * Reads a local video for playback outside the session-long SWR preview cache,
+ * so its bytes (up to 200 MB) live only while they are in use: unmounting or a
+ * new revision aborts an in-flight read and revokes the previous object URL,
+ * and `markUnplayable` releases a blob Chromium could not decode.
+ */
+export const useLocalVideo = ({
+ allowExternalFile,
+ filePath,
+ revision,
+ workingDirectory,
+}: UseLocalVideoParams) => {
+ const [state, setState] = useState<LocalVideoState>({ status: 'loading' });
+ const objectUrlRef = useRef<string>(undefined);
+
+ const releaseObjectUrl = useCallback(() => {
+ if (!objectUrlRef.current) return;
+ URL.revokeObjectURL(objectUrlRef.current);
+ objectUrlRef.current = undefined;
+ }, []);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ setState({ status: 'loading' });
+
+ localFileService
+ .readLocalVideo({ allowExternalFile, path: filePath, workingDirectory }, controller.signal)
+ .then((result) => {
+ if (controller.signal.aborted) return;
+ if (!result.ok) {
+ setState({ oversized: true, status: 'unplayable' });
+ return;
+ }
+ const src = URL.createObjectURL(result.blob);
+ objectUrlRef.current = src;
+ setState({ src, status: 'ready' });
+ })
+ .catch(() => {
+ if (!controller.signal.aborted) setState({ oversized: false, status: 'unplayable' });
+ });
+
+ return () => {
+ controller.abort();
+ releaseObjectUrl();
+ };
+ }, [allowExternalFile, filePath, releaseObjectUrl, revision, workingDirectory]);
+
+ const markUnplayable = useCallback(() => {
+ releaseObjectUrl();
+ setState({ oversized: false, status: 'unplayable' });
+ }, [releaseObjectUrl]);
+
+ return { markUnplayable, state };
+};
diff --git a/src/services/electron/localFileService.test.ts b/src/services/electron/localFileService.test.ts
index ea22cf54091..e4a6f7d15a8 100644
--- a/src/services/electron/localFileService.test.ts
+++ b/src/services/electron/localFileService.test.ts
@@ -160,6 +160,106 @@ describe('localFileService', () => {
expect(textMock).not.toHaveBeenCalled();
});
+ const videoResponse = (size: number, blob = vi.fn()) =>
+ ({
+ blob,
+ body: { cancel: vi.fn(async () => {}) },
+ headers: new Headers({
+ 'content-length': String(size),
+ 'content-type': 'video/mp4',
+ 'x-preview-modified-at': '1700000000123',
+ }),
+ ok: true,
+ }) as unknown as Response;
+
+ it('describes a local video without keeping its bytes in the preview result', async () => {
+ mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
+ success: true,
+ url: 'localfile://preview/demo.mp4',
+ });
+ const blobMock = vi.fn();
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => videoResponse(3, blobMock)),
+ );
+
+ const preview = await localFileService.getLocalFilePreview({
+ path: '/repo/demo.mp4',
+ workingDirectory: '/repo',
+ });
+
+ expect(preview).toEqual({
+ contentType: 'video/mp4',
+ revision: '3:1700000000123',
+ type: 'video',
+ });
+ expect(blobMock).not.toHaveBeenCalled();
+ });
+
+ it('marks an oversized local video as an unpreviewable binary', async () => {
+ mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
+ success: true,
+ url: 'localfile://preview/huge.mp4',
+ });
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => videoResponse(500 * 1024 * 1024)),
+ );
+
+ const preview = await localFileService.getLocalFilePreview({
+ path: '/repo/huge.mp4',
+ workingDirectory: '/repo',
+ });
+
+ expect(preview).toEqual({ contentType: 'video/mp4', oversized: true, type: 'binary' });
+ });
+
+ it('reads a local video for playback with the caller abort signal', async () => {
+ mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
+ success: true,
+ url: 'localfile://preview/demo.mp4',
+ });
+ const blob = new Blob([new Uint8Array([1, 2, 3])], { type: 'video/mp4' });
+ const fetchMock = vi.fn(async () =>
+ videoResponse(
+ 3,
+ vi.fn(async () => blob),
+ ),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const controller = new AbortController();
+
+ const result = await localFileService.readLocalVideo(
+ { path: '/repo/demo.mp4', workingDirectory: '/repo' },
+ controller.signal,
+ );
+
+ expect(result).toEqual({ blob, ok: true });
+ expect(fetchMock).toHaveBeenCalledWith('localfile://preview/demo.mp4', {
+ signal: controller.signal,
+ });
+ });
+
+ it('refuses to read an oversized local video for playback', async () => {
+ mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
+ success: true,
+ url: 'localfile://preview/huge.mp4',
+ });
+ const blobMock = vi.fn();
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => videoResponse(500 * 1024 * 1024, blobMock)),
+ );
+
+ const result = await localFileService.readLocalVideo({
+ path: '/repo/huge.mp4',
+ workingDirectory: '/repo',
+ });
+
+ expect(result).toEqual({ ok: false, reason: 'oversized' });
+ expect(blobMock).not.toHaveBeenCalled();
+ });
+
it('reads local file bytes from the preview URL', async () => {
mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({
success: true,
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index d1b900a1cec..0e70470ef62 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -73,7 +73,9 @@ const TEXT_PREVIEW_MIME_TYPES = new Set([
export interface BinaryLocalFilePreview {
contentType: string;
- type: 'binary' | 'pdf' | 'video';
+ /** The file has a previewable type but exceeds the in-app preview size cap. */
+ oversized?: boolean;
+ type: 'binary' | 'pdf';
}
/**
@@ -99,8 +101,27 @@ export interface TextLocalFilePreview {
type: 'text';
}
+/**
+ * A playable local video. Carries no bytes on purpose: the preview result is
+ * cached by SWR for the whole session, so the player reads the file itself
+ * (`readLocalVideo`) and releases it when it unmounts.
+ */
+export interface VideoLocalFilePreview {
+ contentType: string;
+ /**
+ * Identity of the file contents (size + mtime). Changes when the file at the
+ * same path is replaced, so a refreshed preview tells the player to re-read.
+ */
+ revision: string;
+ type: 'video';
+}
+
export type LocalFilePreview =
- BinaryLocalFilePreview | DocumentLocalFilePreview | ImageLocalFilePreview | TextLocalFilePreview;
+ | BinaryLocalFilePreview
+ | DocumentLocalFilePreview
+ | ImageLocalFilePreview
+ | TextLocalFilePreview
+ | VideoLocalFilePreview;
/** Binary documents the in-app portal can preview (or offer to download). */
const DOCUMENT_PREVIEW_MIME_TYPES = new Set([
@@ -120,6 +141,20 @@ const DOCUMENT_PREVIEW_MIME_TYPES = new Set([
*/
const MAX_DOCUMENT_PREVIEW_BYTES = 20 * 1024 * 1024;
+/**
+ * Videos above this size fall back to the `binary` placeholder: the desktop
+ * protocol serves the whole file in one response, so the blob lives in renderer
+ * memory for as long as the preview is open.
+ */
+const MAX_VIDEO_PREVIEW_BYTES = 200 * 1024 * 1024;
+
+const isOversizedVideo = (response: Response): boolean => {
+ const contentLength = Number(response.headers.get('content-length'));
+ return Number.isFinite(contentLength) && contentLength > MAX_VIDEO_PREVIEW_BYTES;
+};
+
+export type ReadLocalVideoResult = { blob: Blob; ok: true } | { ok: false; reason: 'oversized' };
+
const normalizeContentType = (contentType: string | null): string =>
contentType?.split(';')[0].trim().toLowerCase() ?? '';
@@ -183,7 +218,19 @@ const fetchLocalFilePreview = async (
}
if (contentType.startsWith('video/')) {
- return { contentType, type: 'video' };
+ // The player reads the bytes on its own; don't hold them here.
+ void response.body?.cancel().catch(() => {});
+
+ return isOversizedVideo(response)
+ ? { contentType, oversized: true, type: 'binary' }
+ : {
+ contentType,
+ revision: [
+ response.headers.get('content-length') ?? '',
+ response.headers.get('x-preview-modified-at') ?? '',
+ ].join(':'),
+ type: 'video',
+ };
}
return { contentType, type: 'binary' };
@@ -313,6 +360,33 @@ class LocalFileService {
return fetchLocalFileBytes(result.url);
}
+ /**
+ * Read a local video for playback. Pass the player's abort signal so closing
+ * the preview mid-read drops the bytes instead of finishing the download.
+ */
+ async readLocalVideo(
+ params: LocalFilePreviewUrlParams,
+ signal?: AbortSignal,
+ ): Promise<ReadLocalVideoResult> {
+ const result = await ensureElectronIpc().localSystem.getLocalFilePreviewUrl(params);
+
+ if (!result.success || !result.url) {
+ throw new Error(result.error || 'Missing local file preview URL');
+ }
+
+ const response = await fetch(result.url, { signal });
+ if (!response.ok) throw new Error(`Failed to load local file: ${response.status}`);
+ if (isOversizedVideo(response)) {
+ void response.body?.cancel().catch(() => {});
+ return { ok: false, reason: 'oversized' };
+ }
+
+ const blob = await response.blob();
+ return blob.size > MAX_VIDEO_PREVIEW_BYTES
+ ? { ok: false, reason: 'oversized' }
+ : { blob, ok: true };
+ }
+
async readExternalAssetForPublish(params: {
path: string;
workingDirectory: string;
diff --git a/src/services/projectFile.test.ts b/src/services/projectFile.test.ts
index 71f498b3802..9e595fe6316 100644
--- a/src/services/projectFile.test.ts
+++ b/src/services/projectFile.test.ts
@@ -89,6 +89,21 @@ describe('projectFileService', () => {
});
});
+ it('maps a content-less remote video preview to the binary placeholder', async () => {
+ mockDeviceClient.getLocalFilePreview.query.mockResolvedValue({
+ preview: { contentType: 'video/mp4', type: 'video' },
+ success: true,
+ });
+
+ const preview = await projectFileService.getLocalFilePreview({
+ deviceId: 'device-1',
+ path: '/repo/demo.mp4',
+ workingDirectory: '/repo',
+ });
+
+ expect(preview).toEqual({ contentType: 'video/mp4', type: 'binary' });
+ });
+
it('forwards image-only preview constraints to remote device RPC', async () => {
mockDeviceClient.getLocalFilePreview.query.mockResolvedValue({
preview: {
diff --git a/src/services/projectFile.ts b/src/services/projectFile.ts
index f07946ec2bc..e760386732f 100644
--- a/src/services/projectFile.ts
+++ b/src/services/projectFile.ts
@@ -54,7 +54,11 @@ const deserializeLocalFilePreview = (preview: DeviceLocalFilePreview): LocalFile
}
default: {
- return preview;
+ // Remote devices never ship video bytes over RPC, so there is nothing to play.
+ return {
+ contentType: preview.contentType,
+ type: preview.type === 'video' ? 'binary' : preview.type,
+ };
}
}
};