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(desktop): preview .cjs/.mjs/no-ext files instead of binary fallback (#15168)

Arvin Xu44e69af6cc84
diff --git a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
index 93733d59480..52b6068d6e8 100644
--- a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
@@ -7,7 +7,7 @@ import { app, protocol } from 'electron';
import { LOCAL_FILE_PROTOCOL_HOST, LOCAL_FILE_PROTOCOL_SCHEME } from '@/const/protocol';
import { createLogger } from '@/utils/logger';
-import { getExportMimeType } from '../../utils/mime';
+import { resolveLocalFileMimeType } from '../../utils/mime';
const LOCAL_FILE_PROTOCOL_PRIVILEGES = {
allowServiceWorkers: false,
@@ -22,20 +22,6 @@ const LOCAL_FILE_PROTOCOL_PRIVILEGES = {
const logger = createLogger('core:LocalFileProtocolManager');
const PREVIEW_TOKEN_TTL_MS = 5 * 60 * 1000;
-const EXTRA_MIME_TYPES: Record<string, string> = {
- '.avif': 'image/avif',
- '.bmp': 'image/bmp',
- '.heic': 'image/heic',
- '.heif': 'image/heif',
- '.tif': 'image/tiff',
- '.tiff': 'image/tiff',
-};
-
-const getMimeType = (filePath: string): string => {
- const ext = path.extname(filePath).toLowerCase();
- return getExportMimeType(filePath) ?? EXTRA_MIME_TYPES[ext] ?? 'application/octet-stream';
-};
-
const normalizeAbsolutePath = (filePath: string): string | null => {
const normalized = path.normalize(filePath);
return path.isAbsolute(normalized) ? normalized : null;
@@ -130,7 +116,7 @@ export class LocalFileProtocolManager {
const buffer = await readFile(realResolvedPath);
const headers = new Headers();
- headers.set('Content-Type', getMimeType(realResolvedPath));
+ headers.set('Content-Type', resolveLocalFileMimeType(realResolvedPath, buffer));
headers.set('Content-Length', String(buffer.byteLength));
// Local files are immutable from the renderer's perspective for a
// single preview session; allow short-lived caching to avoid
diff --git a/apps/desktop/src/main/utils/__tests__/mime.test.ts b/apps/desktop/src/main/utils/__tests__/mime.test.ts
new file mode 100644
index 00000000000..c4f4f044c4a
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/mime.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from 'vitest';
+
+import { getExportMimeType, resolveLocalFileMimeType } from '../mime';
+
+describe('getExportMimeType', () => {
+ it('returns the whitelisted MIME for a known extension', () => {
+ expect(getExportMimeType('/abs/path/App.tsx')).toBe('text/plain; charset=utf-8');
+ expect(getExportMimeType('icon.png')).toBe('image/png');
+ });
+
+ it('returns undefined for unmapped extensions', () => {
+ expect(getExportMimeType('.releaserc.cjs')).toBeUndefined();
+ expect(getExportMimeType('Makefile')).toBeUndefined();
+ });
+});
+
+describe('resolveLocalFileMimeType', () => {
+ it('uses the whitelist for known source extensions', () => {
+ expect(resolveLocalFileMimeType('/repo/App.tsx', Buffer.from(''))).toBe(
+ 'text/plain; charset=utf-8',
+ );
+ expect(resolveLocalFileMimeType('/repo/data.json', Buffer.from('{}'))).toBe(
+ 'application/json; charset=utf-8',
+ );
+ });
+
+ it('serves preview-only image formats with their image MIME', () => {
+ expect(resolveLocalFileMimeType('/repo/photo.heic', Buffer.from([0xff, 0xd8]))).toBe(
+ 'image/heic',
+ );
+ expect(resolveLocalFileMimeType('/repo/diagram.bmp', Buffer.from([0x42, 0x4d]))).toBe(
+ 'image/bmp',
+ );
+ });
+
+ it('treats unmapped text-looking files (.cjs/.mjs) as text via the sniff fallback', () => {
+ const cjsContent = Buffer.from(`module.exports = { plugins: ['@semantic-release/npm'] };\n`);
+ expect(resolveLocalFileMimeType('/repo/.releaserc.cjs', cjsContent)).toBe(
+ 'text/plain; charset=utf-8',
+ );
+
+ const mjsContent = Buffer.from(`export default { settings: ['emoji'] };\n`);
+ expect(resolveLocalFileMimeType('/repo/.remarkrc.mjs', mjsContent)).toBe(
+ 'text/plain; charset=utf-8',
+ );
+ });
+
+ it('treats no-extension config files as text via the sniff fallback', () => {
+ const editorconfig = Buffer.from('root = true\n[*]\nindent_style = space\n');
+ expect(resolveLocalFileMimeType('/repo/.editorconfig', editorconfig)).toBe(
+ 'text/plain; charset=utf-8',
+ );
+ });
+
+ it('falls back to application/octet-stream when the sniff detects binary data', () => {
+ // Embedded null byte β†’ sniff classifies as binary.
+ const binary = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0x01, 0x02, 0x03]);
+ expect(resolveLocalFileMimeType('/repo/strange.blob', binary)).toBe('application/octet-stream');
+ });
+
+ it('forces known-binary extensions to octet-stream even when the prefix sniffs as text', () => {
+ // PDF header + xref + dictionary is pure ASCII for the first few KB β€”
+ // sniff would classify this as text without the extension short-circuit.
+ const pdfPrintablePrefix = Buffer.from(
+ '%PDF-1.7\n%\xC4\xE5\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n',
+ );
+ expect(resolveLocalFileMimeType('/repo/manual.pdf', pdfPrintablePrefix)).toBe(
+ 'application/octet-stream',
+ );
+
+ // No null bytes in the first 8KB; without the short-circuit this would
+ // also be misclassified as text.
+ const fakeZipPrefix = Buffer.from('PK\x03\x04' + 'A'.repeat(64));
+ expect(resolveLocalFileMimeType('/repo/bundle.zip', fakeZipPrefix)).toBe(
+ 'application/octet-stream',
+ );
+
+ const fakeMp3Prefix = Buffer.from('ID3' + 'A'.repeat(64));
+ expect(resolveLocalFileMimeType('/repo/song.mp3', fakeMp3Prefix)).toBe(
+ 'application/octet-stream',
+ );
+ });
+});
diff --git a/apps/desktop/src/main/utils/mime.ts b/apps/desktop/src/main/utils/mime.ts
index cb014cd8fbf..95b94afdfb7 100644
--- a/apps/desktop/src/main/utils/mime.ts
+++ b/apps/desktop/src/main/utils/mime.ts
@@ -1,50 +1,156 @@
import path from 'node:path';
-export const getExportMimeType = (filePath: string) => {
+import { sniffBinaryBuffer } from '@lobechat/file-loaders';
+
+const EXPORT_MIME_MAP: Record<string, string> = {
+ '.bash': 'text/plain; charset=utf-8',
+ '.c': 'text/plain; charset=utf-8',
+ '.cpp': 'text/plain; charset=utf-8',
+ '.css': 'text/css; charset=utf-8',
+ '.csv': 'text/csv; charset=utf-8',
+ '.dockerfile': 'text/plain; charset=utf-8',
+ '.fish': 'text/plain; charset=utf-8',
+ '.gif': 'image/gif',
+ '.go': 'text/plain; charset=utf-8',
+ '.graphql': 'application/graphql; charset=utf-8',
+ '.h': 'text/plain; charset=utf-8',
+ '.hpp': 'text/plain; charset=utf-8',
+ '.html': 'text/html; charset=utf-8',
+ '.ico': 'image/x-icon',
+ '.jpeg': 'image/jpeg',
+ '.jpg': 'image/jpeg',
+ '.js': 'application/javascript; charset=utf-8',
+ '.jsx': 'application/javascript; charset=utf-8',
+ '.json': 'application/json; charset=utf-8',
+ '.log': 'text/plain; charset=utf-8',
+ '.map': 'application/json; charset=utf-8',
+ '.md': 'text/markdown; charset=utf-8',
+ '.mdx': 'text/markdown; charset=utf-8',
+ '.mp4': 'video/mp4',
+ '.png': 'image/png',
+ '.py': 'text/plain; charset=utf-8',
+ '.rs': 'text/plain; charset=utf-8',
+ '.sh': 'text/plain; charset=utf-8',
+ '.svg': 'image/svg+xml; charset=utf-8',
+ '.toml': 'application/toml; charset=utf-8',
+ '.ts': 'text/plain; charset=utf-8',
+ '.tsx': 'text/plain; charset=utf-8',
+ '.txt': 'text/plain; charset=utf-8',
+ '.xml': 'application/xml; charset=utf-8',
+ '.yaml': 'application/yaml; charset=utf-8',
+ '.yml': 'application/yaml; charset=utf-8',
+ '.webp': 'image/webp',
+ '.woff': 'font/woff',
+ '.woff2': 'font/woff2',
+ '.zsh': 'text/plain; charset=utf-8',
+};
+
+/**
+ * Lookup table for renderer-bundled assets. The set of extensions is closed
+ * (whatever `electron-vite` produces under the renderer dir), so a whitelist
+ * is appropriate here.
+ */
+export const getExportMimeType = (filePath: string): string | undefined => {
const ext = path.extname(filePath).toLowerCase();
+ return EXPORT_MIME_MAP[ext];
+};
+
+// Image formats we render natively in the preview pane but don't ship as
+// bundled assets β€” kept separate from EXPORT_MIME_MAP so RendererProtocolManager
+// stays minimal.
+const PREVIEW_IMAGE_MIME_MAP: Record<string, string> = {
+ '.avif': 'image/avif',
+ '.bmp': 'image/bmp',
+ '.heic': 'image/heic',
+ '.heif': 'image/heif',
+ '.tif': 'image/tiff',
+ '.tiff': 'image/tiff',
+};
+
+// Extensions whose contents are binary even when the first 8KB sniffs as
+// printable ASCII. The classic case is PDF: header + xref + dictionary are
+// ASCII and the compressed streams live deeper in the file, so the sniff
+// misses the binary body and would otherwise serve the file as text/plain
+// β€” the renderer then hands it to a text highlighter and shows garbage.
+//
+// Only formats where the printable-prefix problem is realistic need to be
+// listed; truly binary blobs with early null bytes still get caught by the
+// sniff fallback.
+const KNOWN_BINARY_EXTENSIONS = new Set<string>([
+ // Documents
+ '.doc',
+ '.pdf',
+ '.ppt',
+ '.xls',
+ // Archives
+ '.7z',
+ '.bz2',
+ '.gz',
+ '.rar',
+ '.tar',
+ '.tgz',
+ '.zip',
+ // Executables / libraries
+ '.class',
+ '.dll',
+ '.dylib',
+ '.exe',
+ '.jar',
+ '.so',
+ '.war',
+ '.wasm',
+ // Disk / database images
+ '.bin',
+ '.dat',
+ '.db',
+ '.dmg',
+ '.iso',
+ '.sqlite',
+ '.sqlite3',
+ // Audio / video not already mapped above
+ '.aac',
+ '.avi',
+ '.flac',
+ '.m4a',
+ '.mkv',
+ '.mov',
+ '.mp3',
+ '.ogg',
+ '.opus',
+ '.wav',
+ '.webm',
+ // Design files
+ '.ai',
+ '.fig',
+ '.psd',
+ '.sketch',
+]);
+
+const SNIFF_BYTES = 8192;
+const TEXT_FALLBACK_MIME = 'text/plain; charset=utf-8';
+const BINARY_FALLBACK_MIME = 'application/octet-stream';
+
+/**
+ * Resolve the MIME type to serve for a local file preview.
+ *
+ * 1. Known source/image extensions go through the whitelist for a stable,
+ * accurate type (e.g. `.ts` β†’ `text/plain`, not `video/mp2t`).
+ * 2. Known-binary extensions (PDF, archives, executables, media, …)
+ * short-circuit to `application/octet-stream`. Their first 8KB can be
+ * printable ASCII (PDFs are the canonical offender) and we don't want
+ * the sniff to mistakenly route them through the text highlighter.
+ * 3. Anything else β€” no extension, `.cjs` / `.mjs`, `.lock`, `.editorconfig`,
+ * an arbitrary user file β€” falls through to a binary sniff on the first
+ * 8KB. Text β†’ `text/plain`, otherwise `application/octet-stream`. This
+ * removes the need to maintain an exhaustive text-extension allow-list.
+ */
+export const resolveLocalFileMimeType = (filePath: string, buffer: Buffer): string => {
+ const ext = path.extname(filePath).toLowerCase();
+ const fromWhitelist = EXPORT_MIME_MAP[ext] ?? PREVIEW_IMAGE_MIME_MAP[ext];
+ if (fromWhitelist) return fromWhitelist;
+
+ if (KNOWN_BINARY_EXTENSIONS.has(ext)) return BINARY_FALLBACK_MIME;
- const map: Record<string, string> = {
- '.bash': 'text/plain; charset=utf-8',
- '.c': 'text/plain; charset=utf-8',
- '.cpp': 'text/plain; charset=utf-8',
- '.css': 'text/css; charset=utf-8',
- '.csv': 'text/csv; charset=utf-8',
- '.dockerfile': 'text/plain; charset=utf-8',
- '.fish': 'text/plain; charset=utf-8',
- '.gif': 'image/gif',
- '.go': 'text/plain; charset=utf-8',
- '.graphql': 'application/graphql; charset=utf-8',
- '.h': 'text/plain; charset=utf-8',
- '.hpp': 'text/plain; charset=utf-8',
- '.html': 'text/html; charset=utf-8',
- '.ico': 'image/x-icon',
- '.jpeg': 'image/jpeg',
- '.jpg': 'image/jpeg',
- '.js': 'application/javascript; charset=utf-8',
- '.jsx': 'application/javascript; charset=utf-8',
- '.json': 'application/json; charset=utf-8',
- '.log': 'text/plain; charset=utf-8',
- '.map': 'application/json; charset=utf-8',
- '.md': 'text/markdown; charset=utf-8',
- '.mdx': 'text/markdown; charset=utf-8',
- '.mp4': 'video/mp4',
- '.png': 'image/png',
- '.py': 'text/plain; charset=utf-8',
- '.rs': 'text/plain; charset=utf-8',
- '.sh': 'text/plain; charset=utf-8',
- '.svg': 'image/svg+xml; charset=utf-8',
- '.toml': 'application/toml; charset=utf-8',
- '.ts': 'text/plain; charset=utf-8',
- '.tsx': 'text/plain; charset=utf-8',
- '.txt': 'text/plain; charset=utf-8',
- '.xml': 'application/xml; charset=utf-8',
- '.yaml': 'application/yaml; charset=utf-8',
- '.yml': 'application/yaml; charset=utf-8',
- '.webp': 'image/webp',
- '.woff': 'font/woff',
- '.woff2': 'font/woff2',
- '.zsh': 'text/plain; charset=utf-8',
- };
-
- return map[ext];
+ const { isBinary } = sniffBinaryBuffer(buffer.subarray(0, SNIFF_BYTES));
+ return isBinary ? BINARY_FALLBACK_MIME : TEXT_FALLBACK_MIME;
};