π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(desktop): preview workspace HTML files (#17545)
Innei0b5af01ceff4
diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex 8b922b1edfd..34e84e692d6 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -40,6 +40,7 @@"@lobechat/local-file-shell": "workspace:*","@lobechat/tool-runtime": "workspace:*","@lobechat/types": "workspace:*",+ "@lobechat/utils": "workspace:*","@trpc/client": "^11.18.0","@types/node": "^24.13.2","@types/semver": "^7.7.1",diff --git a/apps/cli/pnpm-workspace.yaml b/apps/cli/pnpm-workspace.yamlindex 6b2496a4615..3b888a29f2b 100644--- a/apps/cli/pnpm-workspace.yaml+++ b/apps/cli/pnpm-workspace.yaml@@ -11,8 +11,10 @@ packages:- '../../packages/const'- '../../packages/types'- '../../packages/model-bank'+ - '../../packages/ssrf-safe-fetch'- '../../packages/business/const'- '../../packages/file-loaders'+ - '../../packages/utils'- '.'allowBuilds:esbuild: truediff --git a/apps/cli/src/commands/botMessage.test.ts b/apps/cli/src/commands/botMessage.test.tsindex 85cc4fe9ae1..c02e91e7979 100644--- a/apps/cli/src/commands/botMessage.test.ts+++ b/apps/cli/src/commands/botMessage.test.ts@@ -117,7 +117,7 @@ describe('bot message send --attachment', () => {const call = mockTrpcClient.botMessage.sendMessage.mutate.mock.calls[0][0];expect(call.attachments).toHaveLength(1);expect(call.attachments[0]).toMatchObject({- mimeType: 'text/plain',+ mimeType: 'text/plain; charset=utf-8',name: 'tiny.txt',type: 'file',});diff --git a/apps/cli/src/commands/botMessage.ts b/apps/cli/src/commands/botMessage.tsindex 62aa084b11f..65f4f7767b7 100644--- a/apps/cli/src/commands/botMessage.ts+++ b/apps/cli/src/commands/botMessage.ts@@ -1,7 +1,8 @@import { readFile } from 'node:fs/promises';-import { basename, extname } from 'node:path';+import path from 'node:path';import { DEFAULT_BOT_HISTORY_LIMIT } from '@lobechat/const';+import { getMimeType, resolveMimeType } from '@lobechat/utils/mimeType';import type { Command } from 'commander';import pc from 'picocolors';@@ -17,26 +18,11 @@ type AttachmentInput = {type: 'image' | 'file' | 'video' | 'audio';};-const MIME_EXT_MAP: Record<string, string> = {- '.bmp': 'image/bmp',- '.gif': 'image/gif',- '.jpeg': 'image/jpeg',- '.jpg': 'image/jpeg',- '.m4a': 'audio/mp4',- '.mp3': 'audio/mpeg',- '.mp4': 'video/mp4',- '.ogg': 'audio/ogg',- '.pdf': 'application/pdf',- '.png': 'image/png',- '.svg': 'image/svg+xml',- '.txt': 'text/plain',- '.wav': 'audio/wav',- '.webm': 'video/webm',- '.webp': 'image/webp',+const inferMimeFromUrl = (path: string): string | undefined => {+ const detected = getMimeType(path);+ return detected === 'application/octet-stream' ? undefined : detected;};-const inferMime = (path: string): string | undefined => MIME_EXT_MAP[extname(path).toLowerCase()];-const inferAttachmentType = (mimeType?: string): AttachmentInput['type'] => {if (!mimeType) return 'file';if (mimeType.startsWith('image/')) return 'image';@@ -76,20 +62,20 @@ const resolveAttachmentFlags = async (flags: string[]): Promise<AttachmentInput[const parseAttachmentArg = async (raw: string): Promise<AttachmentInput> => {if (/^https?:\/\//.test(raw)) {const pathname = new URL(raw).pathname;- const mimeType = inferMime(pathname);+ const mimeType = inferMimeFromUrl(pathname);return {fetchUrl: raw,mimeType,- name: basename(pathname) || undefined,+ name: path.basename(pathname) || undefined,type: inferAttachmentType(mimeType),};}const bytes = await readFile(raw);- const mimeType = inferMime(raw);+ const mimeType = await resolveMimeType(raw, bytes);return {data: bytes.toString('base64'),mimeType,- name: basename(raw),+ name: path.basename(raw),type: inferAttachmentType(mimeType),};};diff --git a/apps/cli/src/utils/uploadLocalFile.ts b/apps/cli/src/utils/uploadLocalFile.tsindex 6b576632a76..4789f46ffd8 100644--- a/apps/cli/src/utils/uploadLocalFile.ts+++ b/apps/cli/src/utils/uploadLocalFile.ts@@ -2,45 +2,9 @@ import crypto from 'node:crypto';import fs from 'node:fs';import path from 'node:path';-import type { TrpcClient } from '../api/client';--/**- * Minimal extension β MIME map for files uploaded from the local filesystem.- * Unknown extensions fall back to `application/octet-stream`.- */-const MIME_MAP: Record<string, string> = {- aac: 'audio/aac',- csv: 'text/csv',- doc: 'application/msword',- docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',- flac: 'audio/flac',- gif: 'image/gif',- jpeg: 'image/jpeg',- jpg: 'image/jpeg',- json: 'application/json',- m4a: 'audio/mp4',- md: 'text/markdown',- mp3: 'audio/mpeg',- mp4: 'video/mp4',- ogg: 'audio/ogg',- pdf: 'application/pdf',- png: 'image/png',- pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',- svg: 'image/svg+xml',- txt: 'text/plain',- wav: 'audio/wav',- webm: 'audio/webm',- webp: 'image/webp',- xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',-};+import { resolveMimeType } from '@lobechat/utils/mimeType';-/**- * Detect a MIME type from a file name's extension.- */-export const detectMimeType = (fileName: string): string => {- const ext = path.extname(fileName).toLowerCase().slice(1);- return MIME_MAP[ext] || 'application/octet-stream';-};+import type { TrpcClient } from '../api/client';export interface UploadLocalFileOptions {knowledgeBaseId?: string;@@ -142,9 +106,6 @@ export const uploadLocalFile = async (const fileName = path.basename(resolved);const fileBuffer = fs.readFileSync(resolved);- return uploadFileBuffer(- client,- { buffer: fileBuffer, fileName, fileType: detectMimeType(fileName) },- options,- );+ const fileType = await resolveMimeType(fileName, fileBuffer);+ return uploadFileBuffer(client, { buffer: fileBuffer, fileName, fileType }, options);};diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex f3408783e71..4c4fe038bd5 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -72,6 +72,7 @@"@lobechat/heterogeneous-agents": "workspace:*","@lobechat/local-file-shell": "workspace:*","@lobechat/tool-runtime": "workspace:*",+ "@lobechat/utils": "workspace:*","@lobehub/i18n-cli": "^1.27.0","@modelcontextprotocol/sdk": "^1.29.0","@t3-oss/env-core": "^0.13.11",diff --git a/apps/desktop/pnpm-workspace.yaml b/apps/desktop/pnpm-workspace.yamlindex b0ed3e4b278..89d6a6c45ef 100644--- a/apps/desktop/pnpm-workspace.yaml+++ b/apps/desktop/pnpm-workspace.yaml@@ -15,9 +15,11 @@ packages:- '../../packages/local-file-shell'- '../../packages/tool-runtime'- '../../packages/prompts'+ - '../../packages/ssrf-safe-fetch'- './stubs/business-const'- '../../packages/types'- '../../packages/model-bank'+ - '../../packages/utils'- '.'allowBuilds:electron: set this to true or falsediff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.tsindex 667456d9646..d1720f49860 100644--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts@@ -58,6 +58,7 @@ import {type SearchOptions,writeLocalFile,} from '@lobechat/local-file-shell';+import { resolveMimeType } from '@lobechat/utils/mimeType';import { dialog, shell } from 'electron';import { execa } from 'execa';@@ -354,23 +355,13 @@ export default class LocalFileCtr extends ControllerModule {const filePath = result.filePaths[0];const data = await readFile(filePath);const name = path.basename(filePath);- const ext = path.extname(filePath).toLowerCase().slice(1);-- const MIME_MAP: Record<string, string> = {- avif: 'image/avif',- gif: 'image/gif',- jpeg: 'image/jpeg',- jpg: 'image/jpeg',- png: 'image/png',- svg: 'image/svg+xml',- webp: 'image/webp',- };+ const mimeType = await resolveMimeType(name, data);return {canceled: false,file: {data: new Uint8Array(data),- mimeType: MIME_MAP[ext] || 'application/octet-stream',+ mimeType,name,},};@@ -546,6 +537,7 @@ export default class LocalFileCtr extends ControllerModule {accept,allowExternalFile,path: filePath,+ resourceScope,workingDirectory,}: LocalFilePreviewUrlParams): Promise<LocalFilePreviewUrlResult> {try {@@ -553,6 +545,7 @@ export default class LocalFileCtr extends ControllerModule {accept,allowExternalFile,filePath,+ ...(resourceScope && { resourceScope }),workspaceRoot: workingDirectory,});diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.tsindex 79117b3d26a..6f66d9479a7 100644--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts@@ -273,6 +273,30 @@ describe('LocalFileCtr', () => {});});+ it('should request a workspace-scoped resource session for HTML preview', async () => {+ mockLocalFileProtocolManager.createPreviewUrl.mockResolvedValue(+ 'localfile://preview-session/pages/index.html',+ );++ const result = await localFileCtr.getLocalFilePreviewUrl({+ path: '/workspace/pages/index.html',+ resourceScope: 'workspace',+ workingDirectory: '/workspace',+ });++ expect(mockLocalFileProtocolManager.createPreviewUrl).toHaveBeenCalledWith({+ accept: undefined,+ allowExternalFile: undefined,+ filePath: '/workspace/pages/index.html',+ resourceScope: 'workspace',+ workspaceRoot: '/workspace',+ });+ expect(result).toEqual({+ success: true,+ url: 'localfile://preview-session/pages/index.html',+ });+ });+it('should forward user-approved external preview URL access', async () => {mockLocalFileProtocolManager.createPreviewUrl.mockResolvedValue('localfile://file/tmp/worktree-switcher-demo.html?token=abc',diff --git a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.tsindex 3acc4ee2a0e..66e172752a5 100644--- a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts+++ b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts@@ -2,13 +2,12 @@ import { randomUUID } from 'node:crypto';import { readFile, realpath, stat } from 'node:fs/promises';import path from 'node:path';+import { resolveMimeType } from '@lobechat/utils/mimeType';import { app, protocol } from 'electron';import { LOCAL_FILE_PROTOCOL_HOST, LOCAL_FILE_PROTOCOL_SCHEME } from '@/const/protocol';import { createLogger } from '@/utils/logger';-import { resolveLocalFileMimeType } from '../../utils/mime';-const LOCAL_FILE_PROTOCOL_PRIVILEGES = {allowServiceWorkers: false,bypassCSP: false,@@ -22,6 +21,7 @@ const LOCAL_FILE_PROTOCOL_PRIVILEGES = {const logger = createLogger('core:LocalFileProtocolManager');const PREVIEW_TOKEN_TTL_MS = 5 * 60 * 1000;const EXTERNAL_PREVIEW_APPROVAL_TTL_MS = 10 * 60 * 1000;+const PREVIEW_SESSION_HOST_PREFIX = 'preview-';const normalizeAbsolutePath = (filePath: string): string | null => {const normalized = path.normalize(filePath);@@ -44,11 +44,32 @@ const buildLocalFileUrl = (absolutePath: string, token: string): string => {return url.toString();};+const encodePathSegments = (relativePath: string): string =>+ relativePath.split(path.sep).map(encodeURIComponent).join('/');++const buildWorkspacePreviewUrl = (+ realRoot: string,+ realFilePath: string,+ token: string,+): string | null => {+ const relativePath = path.relative(realRoot, realFilePath);+ if (!relativePath || relativePath.startsWith('..') || path.isAbsolute(relativePath)) return null;++ return new URL(+ `${LOCAL_FILE_PROTOCOL_SCHEME}://${PREVIEW_SESSION_HOST_PREFIX}${token}/${encodePathSegments(relativePath)}`,+ ).toString();+};+interface PreviewTokenRecord {expiresAt: number;realPath: string;}+interface PreviewRootTokenRecord {+ expiresAt: number;+ realRoot: string;+}+export interface PreviewFileReadResult {buffer: Buffer;contentType: string;@@ -60,6 +81,27 @@ type PreviewFileAccept = 'image';const normalizeContentType = (contentType: string): string =>contentType.split(';')[0].trim().toLowerCase();+const CORS_PREVIEW_CONTENT_TYPES = new Set([+ 'application/font-woff',+ 'application/font-woff2',+ 'application/javascript',+ 'application/vnd.ms-fontobject',+ 'application/wasm',+ 'text/css',+ 'text/javascript',+]);++const allowsCorsPreviewContentType = (contentType: string): boolean => {+ const normalizedContentType = normalizeContentType(contentType);+ return (+ normalizedContentType.startsWith('audio/') ||+ normalizedContentType.startsWith('font/') ||+ normalizedContentType.startsWith('image/') ||+ normalizedContentType.startsWith('video/') ||+ CORS_PREVIEW_CONTENT_TYPES.has(normalizedContentType)+ );+};+const isAcceptedPreviewContentType = (contentType: string, accept?: PreviewFileAccept): boolean => {if (!accept) return true;@@ -70,14 +112,18 @@ const isAcceptedPreviewContentType = (contentType: string, accept?: PreviewFileA/*** Custom `localfile://` protocol for project file previews.*- * URL shape: `localfile://file/<percent-encoded-absolute-path>?token=<main-issued-token>`- * - host is fixed to `file` so the scheme behaves as `standard`- * - the absolute path is encoded in the URL pathname- * - every request must carry a short-lived token minted by the main process+ * URL shapes:+ * - single file: `localfile://file/<absolute-path>?token=<token>`+ * - workspace HTML: `localfile://preview-<token>/<workspace-relative-path>`+ *+ * Both forms use a short-lived main-process capability. Workspace sessions+ * additionally verify every requested real path remains within the approved+ * root, including after symlink resolution.** Examples:* localfile://file//Users/alice/project/cat.png?token=...* localfile://file/C:/Users/alice/project/cat.png?token=...+ * localfile://preview-<token>/pages/index.html*/export class LocalFileProtocolManager {private readonly approvedWorkspaceRoots = new Set<string>();@@ -90,6 +136,8 @@ export class LocalFileProtocolManager {private readonly previewTokens = new Map<string, PreviewTokenRecord>();+ private readonly previewRootTokens = new Map<string, PreviewRootTokenRecord>();+get protocolScheme() {return {privileges: LOCAL_FILE_PROTOCOL_PRIVILEGES,@@ -106,29 +154,8 @@ export class LocalFileProtocolManager {protocol.handle(LOCAL_FILE_PROTOCOL_SCHEME, async (request) => {try {const url = new URL(request.url);-- if (url.hostname !== LOCAL_FILE_PROTOCOL_HOST) {- return new Response('Not Found', { status: 404 });- }-- const resolvedPath = this.resolveFilePath(url.pathname);- if (!resolvedPath) {- return new Response('Invalid path', { status: 400 });- }-- const token = url.searchParams.get('token');- if (!token) {- return new Response('Forbidden', { status: 403 });- }-- if (!this.hasPreviewToken(token)) {- return new Response('Forbidden', { status: 403 });- }-- const realResolvedPath = normalizeAbsolutePath(await realpath(resolvedPath));- if (!realResolvedPath || !this.verifyPreviewToken(token, realResolvedPath)) {- return new Response('Forbidden', { status: 403 });- }+ const realResolvedPath = await this.resolveRequestPath(url);+ if (realResolvedPath instanceof Response) return realResolvedPath;const fileStat = await stat(realResolvedPath);if (!fileStat.isFile()) {@@ -137,8 +164,17 @@ export class LocalFileProtocolManager {const buffer = await readFile(realResolvedPath);const headers = new Headers();- headers.set('Content-Type', resolveLocalFileMimeType(realResolvedPath, buffer));+ const contentType = await resolveMimeType(realResolvedPath, buffer);+ headers.set('Content-Type', contentType);headers.set('Content-Length', String(buffer.byteLength));+ // 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.+ if (allowsCorsPreviewContentType(contentType)) {+ headers.set('Access-Control-Allow-Origin', '*');+ }+ headers.set('Cross-Origin-Resource-Policy', 'cross-origin');+ headers.set('X-Content-Type-Options', 'nosniff');// Local files are immutable from the renderer's perspective for a// single preview session; allow short-lived caching to avoid// re-reading large images during scrolling/refresh.@@ -231,11 +267,13 @@ export class LocalFileProtocolManager {accept,allowExternalFile,filePath,+ resourceScope,workspaceRoot,}: {accept?: PreviewFileAccept;allowExternalFile?: boolean;filePath: string;+ resourceScope?: 'workspace';workspaceRoot: string;}): Promise<string | null> {const normalizedFilePath = normalizeAbsolutePath(filePath);@@ -256,6 +294,24 @@ export class LocalFileProtocolManager {this.cleanupExpiredTokens();const token = randomUUID();+ if (resourceScope === 'workspace') {+ const realRoot = await this.resolvePreviewResourceRoot({+ allowExternalFile,+ realFilePath,+ workspaceRoot,+ });+ if (!realRoot) return null;++ const url = buildWorkspacePreviewUrl(realRoot, realFilePath, token);+ if (!url) return null;++ this.previewRootTokens.set(token, {+ expiresAt: Date.now() + PREVIEW_TOKEN_TTL_MS,+ realRoot,+ });+ return url;+ }+this.previewTokens.set(token, {expiresAt: Date.now() + PREVIEW_TOKEN_TTL_MS,realPath: realFilePath,@@ -287,7 +343,7 @@ export class LocalFileProtocolManager {if (!fileStat.isFile()) return null;const buffer = await readFile(realFilePath);- const contentType = resolveLocalFileMimeType(realFilePath, buffer);+ const contentType = await resolveMimeType(realFilePath, buffer);if (!isAcceptedPreviewContentType(contentType, accept)) return null;if (allowExternalFile) {@@ -340,6 +396,94 @@ export class LocalFileProtocolManager {return normalized;}+ private resolvePreviewRelativePath(pathname: string): string | null {+ let decoded: string;+ try {+ decoded = decodeURIComponent(pathname);+ } catch {+ return null;+ }++ const relativePath = decoded.replace(/^\/+/, '');+ if (!relativePath) return null;++ const normalized = path.normalize(relativePath);+ if (normalized.startsWith('..') || path.isAbsolute(normalized)) return null;++ return normalized;+ }++ private async resolveRequestPath(url: URL): Promise<string | Response> {+ if (url.hostname === LOCAL_FILE_PROTOCOL_HOST) {+ const resolvedPath = this.resolveFilePath(url.pathname);+ if (!resolvedPath) return new Response('Invalid path', { status: 400 });++ const token = url.searchParams.get('token');+ if (!token || !this.hasPreviewToken(token)) {+ return new Response('Forbidden', { status: 403 });+ }++ const realResolvedPath = normalizeAbsolutePath(await realpath(resolvedPath));+ if (!realResolvedPath || !this.verifyPreviewToken(token, realResolvedPath)) {+ return new Response('Forbidden', { status: 403 });+ }++ return realResolvedPath;+ }++ if (!url.hostname.startsWith(PREVIEW_SESSION_HOST_PREFIX)) {+ return new Response('Not Found', { status: 404 });+ }++ const token = url.hostname.slice(PREVIEW_SESSION_HOST_PREFIX.length);+ const record = this.getPreviewRootToken(token);+ if (!record) return new Response('Forbidden', { status: 403 });++ const relativePath = this.resolvePreviewRelativePath(url.pathname);+ if (!relativePath) return new Response('Invalid path', { status: 400 });++ const candidatePath = path.resolve(record.realRoot, relativePath);+ if (!isPathWithinRoot(candidatePath, record.realRoot)) {+ return new Response('Forbidden', { status: 403 });+ }++ const realResolvedPath = normalizeAbsolutePath(await realpath(candidatePath));+ if (!realResolvedPath || !isPathWithinRoot(realResolvedPath, record.realRoot)) {+ return new Response('Forbidden', { status: 403 });+ }++ return realResolvedPath;+ }++ private async resolvePreviewResourceRoot({+ allowExternalFile,+ realFilePath,+ workspaceRoot,+ }: {+ allowExternalFile?: boolean;+ realFilePath: string;+ workspaceRoot: string;+ }): Promise<string | null> {+ const normalizedWorkspaceRoot = normalizeAbsolutePath(workspaceRoot);+ if (!normalizedWorkspaceRoot) return null;++ const realWorkspaceRoot = normalizeAbsolutePath(await realpath(normalizedWorkspaceRoot));+ if (!realWorkspaceRoot) return null;++ const workspaceRootApproved =+ this.approvedWorkspaceRoots.has(realWorkspaceRoot) ||+ this.indexedProjectRoots.has(realWorkspaceRoot);+ if (workspaceRootApproved && isPathWithinRoot(realFilePath, realWorkspaceRoot)) {+ return realWorkspaceRoot;+ }++ if (allowExternalFile || this.hasExternalPreviewApproval(realFilePath)) {+ return path.dirname(realFilePath);+ }++ return null;+ }+private async resolveApprovedPreviewPath({allowExternalFile,filePath,@@ -410,6 +554,11 @@ export class LocalFileProtocolManager {this.previewTokens.delete(token);}}+ for (const [token, record] of this.previewRootTokens) {+ if (record.expiresAt <= now) {+ this.previewRootTokens.delete(token);+ }+ }}private cleanupExpiredExternalPreviewApprovals() {@@ -440,6 +589,18 @@ export class LocalFileProtocolManager {return record.realPath === realResolvedPath;}+ private getPreviewRootToken(token: string): PreviewRootTokenRecord | null {+ const record = this.previewRootTokens.get(token);+ if (!record) return null;++ if (record.expiresAt <= Date.now()) {+ this.previewRootTokens.delete(token);+ return null;+ }++ return record;+ }+private hasExternalPreviewApproval(realFilePath: string): boolean {const expiresAt = this.externalPreviewApprovals.get(realFilePath);if (!expiresAt) return false;diff --git a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.tsindex b607c1a5405..425f09d99d9 100644--- a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts+++ b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts@@ -1,13 +1,12 @@import { readFile, stat } from 'node:fs/promises';import path from 'node:path';+import { tryGetMimeType } from '@lobechat/utils/mimeType';import { app, protocol } from 'electron';import { pathExistsSync } from 'fs-extra';import { createLogger } from '@/utils/logger';-import { getExportMimeType } from '../../utils/mime';-type ResolveRendererFilePath = (url: URL) => Promise<string | null>;/**@@ -194,7 +193,7 @@ export class StaticRendererFallback implements RendererFallbackStrategy {const buffer = await readFile(targetPath);const headers = new Headers();- const mimeType = getExportMimeType(targetPath);+ const mimeType = tryGetMimeType(targetPath);if (mimeType) headers.set('Content-Type', mimeType);diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.tsindex 8135f296a57..60d6aa4ffbc 100644--- a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts+++ b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts@@ -71,6 +71,16 @@ describe('LocalFileProtocolManager', () => {});it('serves a POSIX absolute path with the correct mime type', async () => {+ // Real PNG signature + IHDR chunk header so file-type recognises it as+ // an image. Without a binary-looking buffer the mime resolver's+ // downgrade rule would (correctly) reclassify a `.png` with text body+ // as text/plain.+ const pngBytes = Buffer.from([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,+ 0x52,+ ]);+ mockReadFile.mockResolvedValue(pngBytes);+const manager = new LocalFileProtocolManager();manager.registerHandler();await manager.approveWorkspaceRoot('/Users/alice');@@ -93,7 +103,7 @@ describe('LocalFileProtocolManager', () => {expect(mockReadFile).toHaveBeenCalledWith('/Users/alice/Pictures/cat.png');expect(response.status).toBe(200);expect(response.headers.get('Content-Type')).toBe('image/png');- expect(response.headers.get('Content-Length')).toBe('11'); // 'image-bytes'.length+ expect(response.headers.get('Content-Length')).toBe(String(pngBytes.byteLength));});it('serves source files as text through the localfile protocol', async () => {@@ -119,6 +129,119 @@ describe('LocalFileProtocolManager', () => {expect(response.headers.get('Content-Type')).toBe('text/plain; charset=utf-8');});+ it('serves relative HTML resources from a workspace-scoped preview session', async () => {+ const manager = new LocalFileProtocolManager();+ manager.registerHandler();+ await manager.approveWorkspaceRoot('/Users/alice/project');+ const url = await manager.createPreviewUrl({+ filePath: '/Users/alice/project/pages/index.html',+ resourceScope: 'workspace',+ workspaceRoot: '/Users/alice/project',+ });+ if (!url) throw new Error('Expected workspace preview URL');++ expect(url).toMatch(/^localfile:\/\/preview-[^/]+\/pages\/index\.html$/);++ const resourceUrl = new URL('../assets/app.css', new URL('.', url)).toString();+ const response = await protocolHandlerRef.current({+ headers: new Headers(),+ method: 'GET',+ url: resourceUrl,+ });++ expect(mockStat).toHaveBeenCalledWith('/Users/alice/project/assets/app.css');+ expect(mockReadFile).toHaveBeenCalledWith('/Users/alice/project/assets/app.css');+ expect(response.status).toBe(200);+ expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*');+ expect(response.headers.get('Cross-Origin-Resource-Policy')).toBe('cross-origin');+ });++ it('resolves root-relative HTML resources against the workspace root', async () => {+ const manager = new LocalFileProtocolManager();+ manager.registerHandler();+ await manager.approveWorkspaceRoot('/Users/alice/project');+ const url = await manager.createPreviewUrl({+ filePath: '/Users/alice/project/pages/index.html',+ resourceScope: 'workspace',+ workspaceRoot: '/Users/alice/project',+ });+ if (!url) throw new Error('Expected workspace preview URL');++ await protocolHandlerRef.current({+ headers: new Headers(),+ method: 'GET',+ url: new URL('/assets/app.js', url).toString(),+ });++ expect(mockReadFile).toHaveBeenCalledWith('/Users/alice/project/assets/app.js');+ });++ it('rejects workspace preview resources whose symlinks escape the approved root', async () => {+ mockRealpath.mockImplementation(async (filePath: string) =>+ filePath === '/Users/alice/project/assets/private.txt'+ ? '/Users/alice/.ssh/id_rsa'+ : filePath,+ );++ const manager = new LocalFileProtocolManager();+ manager.registerHandler();+ await manager.approveWorkspaceRoot('/Users/alice/project');+ const url = await manager.createPreviewUrl({+ filePath: '/Users/alice/project/index.html',+ resourceScope: 'workspace',+ workspaceRoot: '/Users/alice/project',+ });+ if (!url) throw new Error('Expected workspace preview URL');++ const response = await protocolHandlerRef.current({+ headers: new Headers(),+ method: 'GET',+ url: new URL('/assets/private.txt', url).toString(),+ });++ expect(response.status).toBe(403);+ expect(mockStat).not.toHaveBeenCalledWith('/Users/alice/.ssh/id_rsa');+ expect(mockReadFile).not.toHaveBeenCalledWith('/Users/alice/.ssh/id_rsa');+ });++ it('rejects forged workspace preview sessions before resolving a path', async () => {+ const manager = new LocalFileProtocolManager();+ manager.registerHandler();++ const response = await protocolHandlerRef.current({+ headers: new Headers(),+ method: 'GET',+ url: 'localfile://preview-forged/assets/private.txt',+ });++ expect(response.status).toBe(403);+ expect(mockRealpath).not.toHaveBeenCalled();+ expect(mockStat).not.toHaveBeenCalled();+ expect(mockReadFile).not.toHaveBeenCalled();+ });++ it('does not grant arbitrary workspace text files cross-origin read access', async () => {+ const manager = new LocalFileProtocolManager();+ manager.registerHandler();+ await manager.approveWorkspaceRoot('/Users/alice/project');+ const url = await manager.createPreviewUrl({+ filePath: '/Users/alice/project/index.html',+ resourceScope: 'workspace',+ workspaceRoot: '/Users/alice/project',+ });+ if (!url) throw new Error('Expected workspace preview URL');++ const response = await protocolHandlerRef.current({+ headers: new Headers(),+ method: 'GET',+ url: new URL('/.env', url).toString(),+ });++ expect(response.status).toBe(200);+ expect(response.headers.get('Content-Type')).toBe('text/plain; charset=utf-8');+ expect(response.headers.has('Access-Control-Allow-Origin')).toBe(false);+ });+it('does not mint image-only preview URLs for text files', async () => {const manager = new LocalFileProtocolManager();await manager.approveWorkspaceRoot('/Users/alice/project');diff --git a/apps/desktop/src/main/utils/__tests__/mime.test.ts b/apps/desktop/src/main/utils/__tests__/mime.test.tsdeleted file mode 100644index c4f4f044c4a..00000000000--- a/apps/desktop/src/main/utils/__tests__/mime.test.ts+++ /dev/null@@ -1,83 +0,0 @@-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.tsdeleted file mode 100644index 7c226262838..00000000000--- a/apps/desktop/src/main/utils/mime.ts+++ /dev/null@@ -1,156 +0,0 @@-import path from 'node:path';--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 the renderer Vite build 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 { isBinary } = sniffBinaryBuffer(buffer.subarray(0, SNIFF_BYTES));- return isBinary ? BINARY_FALLBACK_MIME : TEXT_FALLBACK_MIME;-};diff --git a/packages/device-control/package.json b/packages/device-control/package.jsonindex e2a1c5910cf..b41f4bf6891 100644--- a/packages/device-control/package.json+++ b/packages/device-control/package.json@@ -15,6 +15,7 @@},"dependencies": {"@lobechat/local-file-shell": "workspace:*",+ "@lobechat/utils": "workspace:*","fast-glob": "^3.3.3","fflate": "^0.8.3","gray-matter": "^4.0.3"diff --git a/packages/device-control/src/__tests__/filePreview.test.ts b/packages/device-control/src/__tests__/filePreview.test.tsindex 7946838bfd1..8ae312ed715 100644--- a/packages/device-control/src/__tests__/filePreview.test.ts+++ b/packages/device-control/src/__tests__/filePreview.test.ts@@ -13,7 +13,14 @@ beforeAll(async () => {root = await mkdtemp(path.join(tmpdir(), 'dc-preview-'));outside = await mkdtemp(path.join(tmpdir(), 'dc-outside-'));await writeFile(path.join(root, 'note.txt'), 'hello preview\n');- await writeFile(path.join(root, 'pic.png'), Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]));+ // Full PNG signature + IHDR chunk header so file-type recognises the format.+ await writeFile(+ path.join(root, 'pic.png'),+ Buffer.from([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,+ 0x52,+ ]),+ );await writeFile(path.join(outside, 'secret.txt'), 'do not read\n');});diff --git a/packages/device-control/src/filePreview.ts b/packages/device-control/src/filePreview.tsindex 18c4a85ff22..fcfa655e886 100644--- a/packages/device-control/src/filePreview.ts+++ b/packages/device-control/src/filePreview.ts@@ -1,6 +1,8 @@import { readFile, realpath, stat } from 'node:fs/promises';import path from 'node:path';+import { resolveMimeType } from '@lobechat/utils/mimeType';+import type { LocalFilePreview, LocalFilePreviewResult, LocalFilePreviewUrlParams } from './types';const TEXT_PREVIEW_MIME_TYPES = new Set([@@ -16,48 +18,13 @@ const TEXT_PREVIEW_MIME_TYPES = new Set(['text/x-markdown',]);-/** Minimal extension β MIME map for preview content-type inference. */-const EXT_MIME: Record<string, string> = {- avif: 'image/avif',- bmp: 'image/bmp',- css: 'text/css',- csv: 'text/csv',- gif: 'image/gif',- htm: 'text/html',- html: 'text/html',- jpeg: 'image/jpeg',- jpg: 'image/jpeg',- js: 'application/javascript',- json: 'application/json',- jsx: 'text/javascript',- log: 'text/plain',- md: 'text/markdown',- mdx: 'text/mdx',- mjs: 'application/javascript',- mov: 'video/quicktime',- mp4: 'video/mp4',- pdf: 'application/pdf',- png: 'image/png',- svg: 'image/svg+xml',- toml: 'application/toml',- ts: 'text/typescript',- tsx: 'text/typescript',- txt: 'text/plain',- webm: 'video/webm',- webp: 'image/webp',- xml: 'application/xml',- yaml: 'application/yaml',- yml: 'application/yaml',-};+const normalizeContentType = (contentType: string): string => contentType.split(';')[0].trim();-const inferContentType = (filePath: string): string => {- const ext = path.extname(filePath).toLowerCase().slice(1);- return EXT_MIME[ext] || 'application/octet-stream';+const isTextPreviewMimeType = (contentType: string): boolean => {+ const bare = normalizeContentType(contentType);+ return bare.startsWith('text/') || TEXT_PREVIEW_MIME_TYPES.has(bare);};-const isTextPreviewMimeType = (mimeType: string): boolean =>- mimeType.startsWith('text/') || TEXT_PREVIEW_MIME_TYPES.has(mimeType);-const serializePreviewFile = (buffer: Buffer, contentType: string): LocalFilePreview => {if (contentType.startsWith('image/')) {return { base64: buffer.toString('base64'), contentType, type: 'image' };@@ -65,7 +32,7 @@ const serializePreviewFile = (buffer: Buffer, contentType: string): LocalFilePreif (isTextPreviewMimeType(contentType)) {return { content: buffer.toString('utf8'), contentType, type: 'text' };}- if (contentType === 'application/pdf') {+ if (normalizeContentType(contentType) === 'application/pdf') {return { contentType, type: 'pdf' };}if (contentType.startsWith('video/')) {@@ -113,12 +80,12 @@ export const defaultGetLocalFilePreview = async (return { error: 'Path is not a file', success: false };}- const contentType = inferContentType(realFile);+ const buffer = await readFile(realFile);+ const contentType = await resolveMimeType(realFile, buffer);if (accept === 'image' && !contentType.startsWith('image/')) {return { error: 'File is not an image', success: false };}- const buffer = await readFile(realFile);return { preview: serializePreviewFile(buffer, contentType), success: true };} catch (error) {return { error: (error as Error).message, success: false };diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.tsindex 1e9982fa07e..d6b7bc8ea8f 100644--- a/packages/electron-client-ipc/src/types/localSystem.ts+++ b/packages/electron-client-ipc/src/types/localSystem.ts@@ -135,6 +135,13 @@ export interface LocalFilePreviewUrlParams {*/allowExternalFile?: boolean;path: string;+ /**+ * Exposes sibling workspace resources through the same short-lived preview+ * session. Intended for HTML documents whose relative URLs must resolve as+ * they do on disk. User-approved external files are restricted to their+ * containing directory.+ */+ resourceScope?: 'workspace';workingDirectory: string;}diff --git a/packages/utils/src/mimeType.test.ts b/packages/utils/src/mimeType.test.tsindex 1318d597248..080e196f451 100644--- a/packages/utils/src/mimeType.test.ts+++ b/packages/utils/src/mimeType.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { getMimeType } from './mimeType';+import { getMimeType, resolveMimeType, tryGetMimeType } from './mimeType';describe('getMimeType', () => {describe('custom code file MIME types', () => {@@ -161,3 +161,102 @@ describe('getMimeType', () => {});});});++describe('tryGetMimeType', () => {+ it('returns the mime with charset for text responses', () => {+ expect(tryGetMimeType('/abs/path/style.css')).toBe('text/css; charset=utf-8');+ expect(tryGetMimeType('bundle.js')).toBe('text/javascript; charset=utf-8');+ });++ it('returns the mime without charset for binary responses', () => {+ expect(tryGetMimeType('icon.png')).toBe('image/png');+ expect(tryGetMimeType('font.woff2')).toBe('font/woff2');+ });++ it('returns undefined when the extension is unknown', () => {+ expect(tryGetMimeType('foo.unknownext')).toBeUndefined();+ expect(tryGetMimeType('Makefile')).toBeUndefined();+ });+});++describe('resolveMimeType', () => {+ it('resolves common web/data extensions via the extension lookup + charset', async () => {+ await expect(resolveMimeType('/repo/data.json', Buffer.from('{}'))).resolves.toBe(+ 'application/json; charset=utf-8',+ );+ await expect(resolveMimeType('/repo/README.md', Buffer.from('# hi'))).resolves.toBe(+ 'text/markdown; charset=utf-8',+ );+ });++ it('appends charset to custom code-language mimes', async () => {+ // .py β CUSTOM_MIME_TYPES text/x-python β text/ prefix β gains charset.+ const py = Buffer.from('print("hi")\n');+ await expect(resolveMimeType('/repo/script.py', py)).resolves.toBe(+ 'text/x-python; charset=utf-8',+ );+ });++ it('serves preview-only image formats via the extension lookup', async () => {+ // Truly binary buffers so the sniff never asks us to downgrade.+ await expect(+ resolveMimeType('/repo/photo.heic', Buffer.from([0x00, 0xff, 0xd8, 0x00])),+ ).resolves.toBe('image/heic');+ await expect(+ resolveMimeType('/repo/diagram.bmp', Buffer.from([0x42, 0x4d, 0x00, 0x01])),+ ).resolves.toBe('image/bmp');+ });++ it('trusts magic bytes for binary formats even when the extension is unknown', async () => {+ // `.blob` isn't in mime-db, so file-type's magic sniff decides.+ const pngBytes = Buffer.from([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,+ 0x52,+ ]);+ await expect(resolveMimeType('/repo/mystery.blob', pngBytes)).resolves.toBe('image/png');+ });++ it('trusts magic bytes even when mime-db would lie about the extension', async () => {+ // Real MPEG-TS carries the 0x47 sync byte at 188-byte intervals. File-type+ // recognises it and serves video/mp2t regardless of extension.+ const mpegTs = Buffer.alloc(376);+ mpegTs[0] = 0x47;+ mpegTs[188] = 0x47;+ await expect(resolveMimeType('/repo/clip.ts', mpegTs)).resolves.toBe('video/mp2t');+ });++ it('downgrades to text/plain when mime-db claims binary but the buffer is text', async () => {+ // The classic .ts ambiguity: mime-db β video/mp2t, but TypeScript source+ // has no magic bytes and sniffs as text. The downgrade rule catches this+ // without an extension override.+ const tsSource = Buffer.from('export const foo = (x: number): number => x + 1;\n');+ await expect(resolveMimeType('/repo/module.ts', tsSource)).resolves.toBe(+ 'text/plain; charset=utf-8',+ );++ // Same rule saves `.cjs` (mime-db β application/node).+ const cjsSource = Buffer.from(`module.exports = { plugins: ['@semantic-release/npm'] };\n`);+ await expect(resolveMimeType('/repo/.releaserc.cjs', cjsSource)).resolves.toBe(+ 'text/plain; charset=utf-8',+ );+ });++ it('falls back to text/plain for unknown text extensions via the sniff', async () => {+ await expect(resolveMimeType('/repo/App.tsx', Buffer.from(''))).resolves.toBe(+ 'text/plain; charset=utf-8',+ );+ const editorconfig = Buffer.from('root = true\n[*]\nindent_style = space\n');+ await expect(resolveMimeType('/repo/.editorconfig', editorconfig)).resolves.toBe(+ 'text/plain; charset=utf-8',+ );+ });++ it('falls back to application/octet-stream when the sniff detects binary data', async () => {+ // No known extension and no recognisable magic bytes β the sniff sees+ // embedded null bytes and classifies as binary.+ const binary = Buffer.from([0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03]);+ await expect(resolveMimeType('/repo/strange.blob', binary)).resolves.toBe(+ 'application/octet-stream',+ );+ });+});diff --git a/packages/utils/src/mimeType.ts b/packages/utils/src/mimeType.tsindex c2f3998f7b5..cbce71a0220 100644--- a/packages/utils/src/mimeType.ts+++ b/packages/utils/src/mimeType.ts@@ -1,6 +1,10 @@+import path from 'node:path';++import { fileTypeFromBuffer } from 'file-type';import mime from 'mime';-// Custom mime types for common code files not recognized by mime package+// Extensions where mime-db has no entry (or a wrong one) but a specific+// text/x-* mime helps downstream language detection.const CUSTOM_MIME_TYPES: Record<string, string> = {'.clj': 'text/x-clojure','.ex': 'text/x-elixir',@@ -20,12 +24,85 @@ const CUSTOM_MIME_TYPES: Record<string, string> = {'.vue': 'text/x-vue',};+const SNIFF_BYTES = 8192;+const TEXT_FALLBACK_MIME = 'text/plain; charset=utf-8';+const BINARY_FALLBACK_MIME = 'application/octet-stream';++// mime.getType returns bare types (e.g. 'application/json'); text-like+// responses need an explicit charset for the renderer.+const TEXT_MIME_PATTERN =+ /^(?:text\/|application\/(?:ecmascript|graphql|javascript|json|toml|xhtml\+xml|xml|yaml))/;++const withCharset = (mimeType: string): string =>+ TEXT_MIME_PATTERN.test(mimeType) && !mimeType.includes('charset=')+ ? `${mimeType}; charset=utf-8`+ : mimeType;++const lookupExtensionMime = (filePath: string): string | null => {+ const ext = path.extname(filePath).toLowerCase();+ return CUSTOM_MIME_TYPES[ext] ?? mime.getType(filePath);+};++// Trimmed binary sniff: any null byte in the first 8KB β binary. Enough to+// disambiguate text sources from binary payloads for the downgrade rule.+const looksBinary = (buffer: Uint8Array): boolean => {+ const limit = Math.min(buffer.byteLength, SNIFF_BYTES);+ for (let i = 0; i < limit; i++) {+ if (buffer[i] === 0) return true;+ }+ return false;+};++/**+ * Sync extension-only lookup. Falls back to `application/octet-stream` for+ * unknown extensions. Use this when a file buffer isn't available (URL input,+ * TRPC payload, filename-only records).+ */+export const getMimeType = (filePath: string): string => {+ return lookupExtensionMime(filePath) || BINARY_FALLBACK_MIME;+};+/**- * Get MIME type for a file path with fallback for code files- * @param path - File path or filename- * @returns MIME type string+ * Extension-only lookup with charset appended for text mimes. Returns+ * `undefined` for unknown extensions so the caller can leave `Content-Type`+ * unset instead of forcing a download via `application/octet-stream`.+ * Use this for HTTP responses over known-closed asset sets (Vite output,+ * bundled resources, β¦).*/-export const getMimeType = (path: string): string => {- const ext = path.slice(path.lastIndexOf('.')).toLowerCase();- return CUSTOM_MIME_TYPES[ext] || mime.getType(path) || 'application/octet-stream';+export const tryGetMimeType = (filePath: string): string | undefined => {+ const detected = lookupExtensionMime(filePath);+ return detected ? withCharset(detected) : undefined;+};++/**+ * Resolve a MIME type from a file path and its content buffer.+ *+ * Extension alone is ambiguous β `.ts` is `video/mp2t` in mime-db and also a+ * TypeScript source; a `.pdf` header is printable ASCII for the first bytes.+ * Trust magic bytes first, then fall back to the extension, and let a text+ * sniff overrule mime-db when the two disagree.+ *+ * 1. `fileTypeFromBuffer()` β magic-byte detection. Authoritative when it+ * matches: real MPEG-TS media wins here regardless of extension.+ * 2. Extension lookup (custom map + `mime.getType`) β the only signal for+ * text formats file-type can't fingerprint (json/css/md/svg/β¦).+ * - Text mime β use as-is (with charset appended).+ * - Binary mime + non-empty buffer that sniffs as text β downgrade to+ * text/plain. Saves TypeScript source from mime-db's `video/mp2t`.+ * - Otherwise β use the extension mime.+ * 3. No extension mapping β sniff-based fallback.+ */+export const resolveMimeType = async (filePath: string, buffer: Uint8Array): Promise<string> => {+ const detected = await fileTypeFromBuffer(buffer);+ if (detected?.mime) return detected.mime;++ const isBinary = looksBinary(buffer);+ const fromExtension = lookupExtensionMime(filePath);+ if (fromExtension) {+ if (TEXT_MIME_PATTERN.test(fromExtension)) return withCharset(fromExtension);+ if (buffer.byteLength > 0 && !isBinary) return TEXT_FALLBACK_MIME;+ return fromExtension;+ }++ return isBinary ? BINARY_FALLBACK_MIME : TEXT_FALLBACK_MIME;};diff --git a/src/components/HtmlPreview/InlinePreview.tsx b/src/components/HtmlPreview/InlinePreview.tsxindex d067c7a8822..eb1535ab0ac 100644--- a/src/components/HtmlPreview/InlinePreview.tsx+++ b/src/components/HtmlPreview/InlinePreview.tsx@@ -1,11 +1,14 @@import { HtmlPreview } from '@lobehub/ui';import type { CSSProperties } from 'react';-import { memo } from 'react';+import { memo, useMemo } from 'react';++import { applyHtmlPreviewBaseUrl } from './applyBaseUrl';const hideHtmlPreviewActions = () => null;interface InlineHtmlPreviewProps {animated?: boolean;+ baseUrl?: string;className?: string;content: string;height?: CSSProperties['height'];@@ -14,24 +17,31 @@ interface InlineHtmlPreviewProps {}const InlineHtmlPreview = memo<InlineHtmlPreviewProps>(- ({ animated, className, content, height = '100%', style, width = '100%' }) => (- <HtmlPreview- actionsRender={hideHtmlPreviewActions}- animated={animated}- className={className}- copyable={false}- downloadable={false}- shadow={false}- style={{ height, minHeight: 0, overflow: 'hidden', width, ...style }}- variant={'borderless'}- styles={{- content: { height: '100%' },- iframe: { height: '100%' },- }}- >- {content}- </HtmlPreview>- ),+ ({ animated, baseUrl, className, content, height = '100%', style, width = '100%' }) => {+ const previewContent = useMemo(+ () => applyHtmlPreviewBaseUrl(content, baseUrl),+ [baseUrl, content],+ );++ return (+ <HtmlPreview+ actionsRender={hideHtmlPreviewActions}+ animated={animated}+ className={className}+ copyable={false}+ downloadable={false}+ shadow={false}+ style={{ height, minHeight: 0, overflow: 'hidden', width, ...style }}+ variant={'borderless'}+ styles={{+ content: { height: '100%' },+ iframe: { height: '100%' },+ }}+ >+ {previewContent}+ </HtmlPreview>+ );+ },);InlineHtmlPreview.displayName = 'InlineHtmlPreview';diff --git a/src/components/HtmlPreview/applyBaseUrl.test.ts b/src/components/HtmlPreview/applyBaseUrl.test.tsnew file mode 100644index 00000000000..e29eed1beef--- /dev/null+++ b/src/components/HtmlPreview/applyBaseUrl.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';++import { applyHtmlPreviewBaseUrl } from './applyBaseUrl';++describe('applyHtmlPreviewBaseUrl', () => {+ const baseUrl = 'localfile://preview-session/pages/';++ it('injects the filesystem base at the beginning of an existing head', () => {+ const result = applyHtmlPreviewBaseUrl(+ '<!doctype html><html><head><link href="styles.css"></head><body></body></html>',+ baseUrl,+ );++ expect(result).toContain(`<head><base href="${baseUrl}"><link href="styles.css">`);+ });++ it('wraps HTML fragments so their relative resources use the filesystem base', () => {+ const result = applyHtmlPreviewBaseUrl('<img src="images/logo.png">', baseUrl);++ expect(result).toBe(+ `<!doctype html><html><head><base href="${baseUrl}"></head><body><img src="images/logo.png"></body></html>`,+ );+ });++ it('resolves an author-provided relative base against the filesystem base', () => {+ const result = applyHtmlPreviewBaseUrl(+ '<html><head><base href="../shared/"></head></html>',+ baseUrl,+ );++ expect(result).toContain('<base href="localfile://preview-session/shared/">');+ });++ it('preserves an author-provided absolute web base', () => {+ const content = '<html><head><base href="https://cdn.example.com/app/"></head></html>';++ expect(applyHtmlPreviewBaseUrl(content, baseUrl)).toBe(content);+ });+});diff --git a/src/components/HtmlPreview/applyBaseUrl.ts b/src/components/HtmlPreview/applyBaseUrl.tsnew file mode 100644index 00000000000..f288c136675--- /dev/null+++ b/src/components/HtmlPreview/applyBaseUrl.ts@@ -0,0 +1,131 @@+const escapeHtmlAttribute = (value: string): string =>+ value.replaceAll('&', '&').replaceAll('"', '"');++const isTagNameBoundary = (value: string | undefined): boolean =>+ !value || value === '>' || value === '/' || /\s/.test(value);++const findTagEnd = (content: string, start: number): number => {+ let quote: '"' | "'" | undefined;++ for (let index = start + 1; index < content.length; index += 1) {+ const char = content[index];++ if (quote) {+ if (char === quote) quote = undefined;+ continue;+ }++ if (char === '"' || char === "'") {+ quote = char;+ continue;+ }++ if (char === '>') return index + 1;+ }++ return -1;+};++const findOpeningTag = (+ content: string,+ tagName: string,+): { end: number; start: number; text: string } | undefined => {+ const lowerContent = content.toLowerCase();+ const tagPrefix = `<${tagName}`;+ let searchFrom = 0;++ while (searchFrom < content.length) {+ const start = lowerContent.indexOf(tagPrefix, searchFrom);+ if (start === -1) return;++ if (!isTagNameBoundary(content[start + tagPrefix.length])) {+ searchFrom = start + tagPrefix.length;+ continue;+ }++ const end = findTagEnd(content, start);+ if (end === -1) return;++ return { end, start, text: content.slice(start, end) };+ }+};++const findAttribute = (+ tagText: string,+ attributeName: string,+): { end: number; start: number; value: string } | undefined => {+ const lowerAttributeName = attributeName.toLowerCase();+ let index = 1;++ while (index < tagText.length - 1) {+ while (index < tagText.length && /\s/.test(tagText[index])) index += 1;++ const nameStart = index;+ while (index < tagText.length && /[^\s=/>]/.test(tagText[index])) index += 1;++ if (nameStart === index) {+ index += 1;+ continue;+ }++ const name = tagText.slice(nameStart, index).toLowerCase();+ while (index < tagText.length && /\s/.test(tagText[index])) index += 1;++ if (tagText[index] !== '=') continue;+ index += 1;++ while (index < tagText.length && /\s/.test(tagText[index])) index += 1;++ const valueStart = index;+ const quote = tagText[index] === '"' || tagText[index] === "'" ? tagText[index] : undefined;++ if (quote) {+ index += 1;+ const quotedValueStart = index;+ while (index < tagText.length && tagText[index] !== quote) index += 1;++ const value = tagText.slice(quotedValueStart, index);+ if (index < tagText.length) index += 1;++ if (name === lowerAttributeName) return { end: index, start: nameStart, value };+ continue;+ }++ while (index < tagText.length && !/[\s"'=<>`]/.test(tagText[index])) index += 1;++ if (name === lowerAttributeName) {+ return { end: index, start: nameStart, value: tagText.slice(valueStart, index) };+ }+ }+};++export const applyHtmlPreviewBaseUrl = (content: string, baseUrl?: string): string => {+ if (!baseUrl) return content;++ const existingBase = findOpeningTag(content, 'base');+ const existingHref = existingBase && findAttribute(existingBase.text, 'href');+ if (existingBase && existingHref) {+ try {+ const resolvedHref = new URL(existingHref.value, baseUrl).toString();+ const updatedBase = `${existingBase.text.slice(0, existingHref.start)}${`href="${escapeHtmlAttribute(resolvedHref)}"`}${existingBase.text.slice(existingHref.end)}`;+ return `${content.slice(0, existingBase.start)}${updatedBase}${content.slice(existingBase.end)}`;+ } catch {+ // Invalid author-provided base URLs fall back to the filesystem base.+ }+ }++ const baseElement = `<base href="${escapeHtmlAttribute(baseUrl)}">`;+ const headOpen = findOpeningTag(content, 'head');+ if (headOpen) {+ const insertAt = headOpen.end;+ return `${content.slice(0, insertAt)}${baseElement}${content.slice(insertAt)}`;+ }++ const htmlOpen = findOpeningTag(content, 'html');+ if (htmlOpen) {+ const insertAt = htmlOpen.end;+ return `${content.slice(0, insertAt)}<head>${baseElement}</head>${content.slice(insertAt)}`;+ }++ return `<!doctype html><html><head>${baseElement}</head><body>${content}</body></html>`;+};diff --git a/src/features/Portal/LocalFile/Body.test.tsx b/src/features/Portal/LocalFile/Body.test.tsxindex 8c3c69747d2..86b34f69173 100644--- a/src/features/Portal/LocalFile/Body.test.tsx+++ b/src/features/Portal/LocalFile/Body.test.tsx@@ -53,9 +53,13 @@ vi.mock('@/components/CodeEditorPane', () => ({default: () => <textarea data-testid="code-editor" />,}));+const mockIsHtmlFile = vi.hoisted(() => vi.fn(() => false));+vi.mock('@/components/HtmlPreview', () => ({- InlineHtmlPreview: () => <iframe title="html-preview" />,- isHtmlFile: () => false,+ InlineHtmlPreview: ({ baseUrl }: { baseUrl?: string }) => (+ <iframe data-base-url={baseUrl} title="html-preview" />+ ),+ isHtmlFile: mockIsHtmlFile,}));vi.mock('@/components/Loading/CircleLoading', () => ({@@ -139,6 +143,8 @@ vi.mock('@/store/chat/selectors', () => {files[0]);},+ localFileBuffer: (tabId: string) => (state: Record<PropertyKey, unknown>) =>+ (state.localFileBuffers as Record<string, string> | undefined)?.[tabId],openLocalFiles,},};@@ -158,6 +164,8 @@ const createChatState = (activeTopicId: 'topic-a' | 'topic-b') => ({activeLocalFilePath: '/project-a/a.ts',activeTopicId,clearPortalStack: mockClearPortalStack,+ saveLocalFile: vi.fn(),+ setLocalFileBuffer: vi.fn(),openLocalFiles: [{filePath: '/project-a/a.ts',@@ -189,6 +197,8 @@ describe('LocalFile Body', () => {beforeEach(() => {mockClearPortalStack.mockClear();mockProjectFileService.getLocalFilePreview.mockClear();+ mockIsHtmlFile.mockReset();+ mockIsHtmlFile.mockReturnValue(false);mockUseClientDataSWR.mockClear();mockUseClientDataSWR.mockReturnValue({isLoading: true,@@ -257,4 +267,51 @@ describe('LocalFile Body', () => {workingDirectory: '/tmp',});});++ it('requests workspace resources for a desktop HTML file and passes its base URL to preview', () => {+ const htmlFileId = createLocalFileTabId({+ filePath: '/project-a/pages/index.html',+ workingDirectory: '/project-a',+ });+ mockIsHtmlFile.mockReturnValue(true);+ mockChatState.current = {+ ...createChatState('topic-a'),+ activeLocalFileId: htmlFileId,+ activeLocalFilePath: '/project-a/pages/index.html',+ openLocalFiles: [+ {+ filePath: '/project-a/pages/index.html',+ id: htmlFileId,+ workingDirectory: '/project-a',+ },+ ],+ };+ mockUseClientDataSWR.mockReturnValue({+ data: {+ content: '<link rel="stylesheet" href="../assets/app.css">',+ contentType: 'text/html',+ resourceBaseUrl: 'localfile://preview-session/pages/',+ type: 'text',+ },+ isLoading: false,+ isValidating: false,+ mutate: vi.fn(),+ });++ render(<Body />);++ const fetcher = mockUseClientDataSWR.mock.calls.at(-1)?.[1] as () => Promise<unknown>;+ void fetcher();+ expect(mockProjectFileService.getLocalFilePreview).toHaveBeenCalledWith({+ allowExternalFile: undefined,+ deviceId: undefined,+ path: '/project-a/pages/index.html',+ resourceScope: 'workspace',+ workingDirectory: '/project-a',+ });+ expect(screen.getByTitle('html-preview')).toHaveAttribute(+ 'data-base-url',+ 'localfile://preview-session/pages/',+ );+ });});diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsxindex 27c6073c840..ae5083e0f7a 100644--- a/src/features/Portal/LocalFile/Body.tsx+++ b/src/features/Portal/LocalFile/Body.tsx@@ -157,6 +157,7 @@ interface TextPreviewPaneProps {onSaved?: (savedContent: string) => void;readOnly?: boolean;reloading?: boolean;+ resourceBaseUrl?: string;workingDirectory: string;}@@ -172,6 +173,7 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(onSaved,readOnly = false,reloading = false,+ resourceBaseUrl,workingDirectory,}) => {const { t } = useTranslation('chat');@@ -323,7 +325,11 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(</Markdown></>) : showHtmlPreview ? (- <InlineHtmlPreview content={editingValue} key={`${filePath}:${htmlPreviewRevision}`} />+ <InlineHtmlPreview+ baseUrl={resourceBaseUrl}+ content={editingValue}+ key={`${filePath}:${htmlPreviewRevision}`}+ />) : (<CodeEditorPanelanguage={extensionToLanguage(ext)}@@ -358,6 +364,7 @@ const ActiveFileView = memo<ActiveFileViewProps>(const filename = filePath.split('/').at(-1) ?? '';const enabled = Boolean(workingDirectory) && (!!deviceId || isDesktop);+ const resourceScope = !deviceId && isHtmlFile({ path: filePath }) ? 'workspace' : undefined;const {data: preview,error,@@ -370,6 +377,7 @@ const ActiveFileView = memo<ActiveFileViewProps>(allowExternalFile: allowExternalFilePreview,deviceId,filePath,+ ...(resourceScope && { resourceScope }),workingDirectory,}): null,@@ -378,6 +386,7 @@ const ActiveFileView = memo<ActiveFileViewProps>(allowExternalFile: allowExternalFilePreview,deviceId,path: filePath,+ ...(resourceScope && { resourceScope }),workingDirectory,}),{ revalidateOnFocus: false },@@ -430,6 +439,7 @@ const ActiveFileView = memo<ActiveFileViewProps>(// device over RPC (writeProjectFile) just as local files go through IPC.readOnly={false}reloading={isValidating}+ resourceBaseUrl={preview.resourceBaseUrl}workingDirectory={workingDirectory}onReload={handleReload}onSaved={handleSavedContent}diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 9b1637d584a..9c19ab7830a 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -39,6 +39,7 @@ interface LocalFilePreviewKeyParams {allowExternalFile?: boolean;deviceId?: string;filePath: string;+ resourceScope?: 'workspace';workingDirectory: string;}@@ -909,6 +910,7 @@ export const localFileKeys = {allowExternalFile,deviceId,filePath,+ resourceScope,workingDirectory,}: LocalFilePreviewKeyParams) => ['localFile:preview',@@ -917,6 +919,7 @@ export const localFileKeys = {workingDirectory,accept ?? 'any',allowExternalFile ? 'external' : 'workspace',+ resourceScope ?? 'single-file',],),projectIndex: def('localFile:projectIndex', (deviceId: string | undefined, dirPath: string) => [diff --git a/src/services/electron/localFileService.test.ts b/src/services/electron/localFileService.test.tsindex 67dabfdda34..02589d1a94e 100644--- a/src/services/electron/localFileService.test.ts+++ b/src/services/electron/localFileService.test.ts@@ -46,6 +46,45 @@ describe('localFileService', () => {expect(preview).toEqual({content: '<h1>Local</h1>',contentType: 'text/html',+ resourceBaseUrl: undefined,+ type: 'text',+ });+ });++ it('returns the entry directory as the HTML workspace resource base URL', async () => {+ const { localFileService } = await import('./localFileService');++ mockLocalSystem.getLocalFilePreviewUrl.mockResolvedValue({+ success: true,+ url: 'localfile://preview-session/pages/index.html',+ });+ vi.stubGlobal(+ 'fetch',+ vi.fn(+ async () =>+ ({+ headers: { get: vi.fn(() => 'text/html; charset=utf-8') },+ ok: true,+ text: vi.fn(async () => '<link rel="stylesheet" href="../assets/app.css">'),+ }) as unknown as Response,+ ),+ );++ const preview = await localFileService.getLocalFilePreview({+ path: '/repo/pages/index.html',+ resourceScope: 'workspace',+ workingDirectory: '/repo',+ });++ expect(mockLocalSystem.getLocalFilePreviewUrl).toHaveBeenCalledWith({+ path: '/repo/pages/index.html',+ resourceScope: 'workspace',+ workingDirectory: '/repo',+ });+ expect(preview).toEqual({+ content: '<link rel="stylesheet" href="../assets/app.css">',+ contentType: 'text/html',+ resourceBaseUrl: 'localfile://preview-session/pages/',type: 'text',});});diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.tsindex cefaf74cdf4..e387bbb44b5 100644--- a/src/services/electron/localFileService.ts+++ b/src/services/electron/localFileService.ts@@ -69,13 +69,12 @@ export interface ImageLocalFilePreview {export interface TextLocalFilePreview {content: string;contentType: string;+ resourceBaseUrl?: string;type: 'text';}export type LocalFilePreview =- | BinaryLocalFilePreview- | ImageLocalFilePreview- | TextLocalFilePreview;+ BinaryLocalFilePreview | ImageLocalFilePreview | TextLocalFilePreview;const normalizeContentType = (contentType: string | null): string =>contentType?.split(';')[0].trim().toLowerCase() ?? '';@@ -86,6 +85,7 @@ const isTextPreviewMimeType = (mimeType: string): boolean =>const fetchLocalFilePreview = async (url: string,accept?: LocalFilePreviewUrlParams['accept'],+ resourceScope?: LocalFilePreviewUrlParams['resourceScope'],): Promise<LocalFilePreview> => {const response = await fetch(url);@@ -104,7 +104,12 @@ const fetchLocalFilePreview = async (}if (isTextPreviewMimeType(contentType)) {- return { content: await response.text(), contentType, type: 'text' };+ return {+ content: await response.text(),+ contentType,+ resourceBaseUrl: resourceScope === 'workspace' ? new URL('.', url).toString() : undefined,+ type: 'text',+ };}if (contentType === 'application/pdf') {@@ -182,7 +187,7 @@ class LocalFileService {throw new Error(result.error || 'Missing local file preview URL');}- return fetchLocalFilePreview(result.url, params.accept);+ return fetchLocalFilePreview(result.url, params.accept, params.resourceScope);}async prepareSkillDirectory(