🤯 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): support approved external local file previews (#15895)
Arvin Xu906e385e8a9e
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.tsindex 20b8325b36c..23367220fb9 100644--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts@@ -438,12 +438,14 @@ export default class LocalFileCtr extends ControllerModule {@IpcMethod()async getLocalFilePreviewUrl({accept,+ allowExternalFile,path: filePath,workingDirectory,}: LocalFilePreviewUrlParams): Promise<LocalFilePreviewUrlResult> {try {const url = await this.app.localFileProtocolManager.createPreviewUrl({accept,+ allowExternalFile,filePath,workspaceRoot: workingDirectory,});@@ -462,12 +464,14 @@ export default class LocalFileCtr extends ControllerModule {@IpcMethod()async getLocalFilePreview({accept,+ allowExternalFile,path: filePath,workingDirectory,}: LocalFilePreviewUrlParams): Promise<LocalFilePreviewResult> {try {const preview = await this.app.localFileProtocolManager.readPreviewFile({accept,+ allowExternalFile,filePath,workspaceRoot: workingDirectory,});diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.tsindex 3e117e701fe..25fc770f741 100644--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts@@ -226,6 +226,7 @@ describe('LocalFileCtr', () => {expect(mockLocalFileProtocolManager.createPreviewUrl).toHaveBeenCalledWith({accept: undefined,+ allowExternalFile: undefined,filePath: '/workspace/app.ts',workspaceRoot: '/workspace',});@@ -262,6 +263,7 @@ describe('LocalFileCtr', () => {expect(mockLocalFileProtocolManager.createPreviewUrl).toHaveBeenCalledWith({accept: 'image',+ allowExternalFile: undefined,filePath: '/workspace/image.png',workspaceRoot: '/workspace',});@@ -270,6 +272,29 @@ describe('LocalFileCtr', () => {url: 'localfile://file/workspace/image.png?token=abc',});});++ it('should forward user-approved external preview URL access', async () => {+ mockLocalFileProtocolManager.createPreviewUrl.mockResolvedValue(+ 'localfile://file/tmp/worktree-switcher-demo.html?token=abc',+ );++ const result = await localFileCtr.getLocalFilePreviewUrl({+ allowExternalFile: true,+ path: '/tmp/worktree-switcher-demo.html',+ workingDirectory: '/tmp',+ });++ expect(mockLocalFileProtocolManager.createPreviewUrl).toHaveBeenCalledWith({+ allowExternalFile: true,+ accept: undefined,+ filePath: '/tmp/worktree-switcher-demo.html',+ workspaceRoot: '/tmp',+ });+ expect(result).toEqual({+ success: true,+ url: 'localfile://file/tmp/worktree-switcher-demo.html?token=abc',+ });+ });});describe('getLocalFilePreview', () => {@@ -287,6 +312,7 @@ describe('LocalFileCtr', () => {expect(mockLocalFileProtocolManager.readPreviewFile).toHaveBeenCalledWith({accept: undefined,+ allowExternalFile: undefined,filePath: '/workspace/app.ts',workspaceRoot: '/workspace',});@@ -329,6 +355,7 @@ describe('LocalFileCtr', () => {expect(mockLocalFileProtocolManager.readPreviewFile).toHaveBeenCalledWith({accept: 'image',+ allowExternalFile: undefined,filePath: '/workspace/image.png',workspaceRoot: '/workspace',});@@ -341,6 +368,35 @@ describe('LocalFileCtr', () => {success: true,});});++ it('should forward user-approved external preview reads', async () => {+ mockLocalFileProtocolManager.readPreviewFile.mockResolvedValue({+ buffer: Buffer.from('<h1>Demo</h1>'),+ contentType: 'text/html',+ realPath: '/tmp/worktree-switcher-demo.html',+ });++ const result = await localFileCtr.getLocalFilePreview({+ allowExternalFile: true,+ path: '/tmp/worktree-switcher-demo.html',+ workingDirectory: '/tmp',+ });++ expect(mockLocalFileProtocolManager.readPreviewFile).toHaveBeenCalledWith({+ allowExternalFile: true,+ accept: undefined,+ filePath: '/tmp/worktree-switcher-demo.html',+ workspaceRoot: '/tmp',+ });+ expect(result).toEqual({+ preview: {+ content: '<h1>Demo</h1>',+ contentType: 'text/html',+ type: 'text',+ },+ success: true,+ });+ });});describe('handleWriteFile', () => {diff --git a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.tsindex 293fdf22956..3acc4ee2a0e 100644--- a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts+++ b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts@@ -21,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 normalizeAbsolutePath = (filePath: string): string | null => {const normalized = path.normalize(filePath);@@ -59,10 +60,7 @@ type PreviewFileAccept = 'image';const normalizeContentType = (contentType: string): string =>contentType.split(';')[0].trim().toLowerCase();-const isAcceptedPreviewContentType = (- contentType: string,- accept?: PreviewFileAccept,-): boolean => {+const isAcceptedPreviewContentType = (contentType: string, accept?: PreviewFileAccept): boolean => {if (!accept) return true;const normalizedContentType = normalizeContentType(contentType);@@ -84,6 +82,8 @@ const isAcceptedPreviewContentType = (export class LocalFileProtocolManager {private readonly approvedWorkspaceRoots = new Set<string>();+ private readonly externalPreviewApprovals = new Map<string, number>();+private readonly indexedProjectRoots = new Set<string>();private handlerRegistered = false;@@ -229,10 +229,12 @@ export class LocalFileProtocolManager {async createPreviewUrl({accept,+ allowExternalFile,filePath,workspaceRoot,}: {accept?: PreviewFileAccept;+ allowExternalFile?: boolean;filePath: string;workspaceRoot: string;}): Promise<string | null> {@@ -243,11 +245,12 @@ export class LocalFileProtocolManager {? (await this.readPreviewFile({accept,+ allowExternalFile,filePath,workspaceRoot,}))?.realPath- : await this.resolveApprovedPreviewPath({ filePath, workspaceRoot });+ : await this.resolveApprovedPreviewPath({ allowExternalFile, filePath, workspaceRoot });if (!realFilePath) return null;this.cleanupExpiredTokens();@@ -263,14 +266,21 @@ export class LocalFileProtocolManager {async readPreviewFile({accept,+ allowExternalFile,filePath,workspaceRoot,}: {accept?: PreviewFileAccept;+ allowExternalFile?: boolean;filePath: string;workspaceRoot: string;}): Promise<PreviewFileReadResult | null> {- const realFilePath = await this.resolveApprovedPreviewPath({ filePath, workspaceRoot });+ const realFilePath = await this.resolveApprovedPreviewPath({+ allowExternalFile,+ filePath,+ persistExternalApproval: false,+ workspaceRoot,+ });if (!realFilePath) return null;const fileStat = await stat(realFilePath);@@ -280,6 +290,10 @@ export class LocalFileProtocolManager {const contentType = resolveLocalFileMimeType(realFilePath, buffer);if (!isAcceptedPreviewContentType(contentType, accept)) return null;+ if (allowExternalFile) {+ this.grantExternalPreviewApproval(realFilePath);+ }+return {buffer,contentType,@@ -327,10 +341,14 @@ export class LocalFileProtocolManager {}private async resolveApprovedPreviewPath({+ allowExternalFile,filePath,+ persistExternalApproval = true,workspaceRoot,}: {+ allowExternalFile?: boolean;filePath: string;+ persistExternalApproval?: boolean;workspaceRoot: string;}): Promise<string | null> {const normalizedFilePath = normalizeAbsolutePath(filePath);@@ -345,15 +363,44 @@ export class LocalFileProtocolManager {const normalizedRealWorkspaceRoot = normalizeAbsolutePath(realWorkspaceRoot);if (!normalizedRealFilePath || !normalizedRealWorkspaceRoot) return null;+ const workspaceRootApproved =+ this.approvedWorkspaceRoots.has(normalizedRealWorkspaceRoot) ||+ this.indexedProjectRoots.has(normalizedRealWorkspaceRoot);if (- !this.approvedWorkspaceRoots.has(normalizedRealWorkspaceRoot) &&- !this.indexedProjectRoots.has(normalizedRealWorkspaceRoot)+ workspaceRootApproved &&+ isPathWithinRoot(normalizedRealFilePath, normalizedRealWorkspaceRoot)) {- return null;+ return normalizedRealFilePath;+ }++ if (this.hasExternalPreviewApproval(normalizedRealFilePath)) return normalizedRealFilePath;++ if (allowExternalFile) {+ return this.approveExternalPreviewFile(normalizedRealFilePath, {+ persist: persistExternalApproval,+ });+ }++ return null;+ }++ private async approveExternalPreviewFile(+ realFilePath: string,+ { persist = true }: { persist?: boolean } = {},+ ): Promise<string | null> {+ const fileStat = await stat(realFilePath);+ if (!fileStat.isFile()) return null;++ if (persist) {+ this.grantExternalPreviewApproval(realFilePath);}- if (!isPathWithinRoot(normalizedRealFilePath, normalizedRealWorkspaceRoot)) return null;- return normalizedRealFilePath;+ return realFilePath;+ }++ private grantExternalPreviewApproval(realFilePath: string) {+ this.cleanupExpiredExternalPreviewApprovals();+ this.externalPreviewApprovals.set(realFilePath, Date.now() + EXTERNAL_PREVIEW_APPROVAL_TTL_MS);}private cleanupExpiredTokens() {@@ -365,6 +412,15 @@ export class LocalFileProtocolManager {}}+ private cleanupExpiredExternalPreviewApprovals() {+ const now = Date.now();+ for (const [realPath, expiresAt] of this.externalPreviewApprovals) {+ if (expiresAt <= now) {+ this.externalPreviewApprovals.delete(realPath);+ }+ }+ }+private hasPreviewToken(token: string): boolean {const record = this.previewTokens.get(token);if (!record) return false;@@ -383,4 +439,16 @@ export class LocalFileProtocolManager {return record.realPath === realResolvedPath;}++ private hasExternalPreviewApproval(realFilePath: string): boolean {+ const expiresAt = this.externalPreviewApprovals.get(realFilePath);+ if (!expiresAt) return false;++ if (expiresAt <= Date.now()) {+ this.externalPreviewApprovals.delete(realFilePath);+ return false;+ }++ return true;+ }}diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.tsindex 328df39f8a8..8135f296a57 100644--- a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts+++ b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts@@ -263,6 +263,31 @@ describe('LocalFileProtocolManager', () => {expect(url).toBeNull();});+ it('mints preview URLs for user-approved external files only', async () => {+ const manager = new LocalFileProtocolManager();++ const url = await manager.createPreviewUrl({+ allowExternalFile: true,+ filePath: '/tmp/worktree-switcher-demo.html',+ workspaceRoot: '/tmp',+ });+ if (!url) throw new Error('Expected external local file preview URL');++ expect(url).toContain('token=');++ const repeatedUrl = await manager.createPreviewUrl({+ filePath: '/tmp/worktree-switcher-demo.html',+ workspaceRoot: '/tmp',+ });+ expect(repeatedUrl).toContain('token=');++ const neighborUrl = await manager.createPreviewUrl({+ filePath: '/tmp/other.html',+ workspaceRoot: '/tmp',+ });+ expect(neighborUrl).toBeNull();+ });+it('can approve a project root derived from an already approved nested scope', async () => {const manager = new LocalFileProtocolManager();await manager.approveWorkspaceRoot('/Users/alice/project/packages/app');@@ -326,6 +351,26 @@ describe('LocalFileProtocolManager', () => {expect(mockReadFile).toHaveBeenCalledWith('/Users/alice/project/.env');});+ it('does not keep external approval when an image-only external preview rejects text', async () => {+ const manager = new LocalFileProtocolManager();+ mockReadFile.mockResolvedValue(Buffer.from('SECRET=value'));++ const result = await manager.readPreviewFile({+ accept: 'image',+ allowExternalFile: true,+ filePath: '/tmp/secret.txt',+ workspaceRoot: '/tmp',+ });++ expect(result).toBeNull();++ const repeatedUrl = await manager.createPreviewUrl({+ filePath: '/tmp/secret.txt',+ workspaceRoot: '/tmp',+ });+ expect(repeatedUrl).toBeNull();+ });+it('does not read preview payloads outside the approved workspace root', async () => {const manager = new LocalFileProtocolManager();await manager.approveIndexedProjectRoot('/Users/alice/project');diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.tsindex 88dcc450af1..8162d3150a2 100644--- a/packages/electron-client-ipc/src/types/localSystem.ts+++ b/packages/electron-client-ipc/src/types/localSystem.ts@@ -115,6 +115,11 @@ export type LocalFilePreviewAccept = 'image';export interface LocalFilePreviewUrlParams {accept?: LocalFilePreviewAccept;+ /**+ * Allows previewing one user-selected file outside approved workspace roots.+ * This is only for renderer previews and must not expand agent file access.+ */+ allowExternalFile?: boolean;path: string;workingDirectory: string;}diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsxindex 680142afe6e..977f1513a77 100644--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx@@ -112,6 +112,7 @@ describe('LocalFileLink Render', () => {expect(screen.getByTestId('file-icon')).toHaveAttribute('data-size', '16');expect(useChatStore.getState().openLocalFiles).toEqual([{+ allowExternalFilePreview: false,filePath: '/Users/me/project/src/Group.tsx',id: createLocalFileTabId({filePath: '/Users/me/project/src/Group.tsx',@@ -122,4 +123,45 @@ describe('LocalFileLink Render', () => {]);expect(useChatStore.getState().showPortal).toBe(true);});++ it('marks links outside the current workspace as user-approved external previews', () => {+ useChatStore.setState({+ activeAgentId: 'agent-1',+ activeTopicId: 'topic-1',+ topicDataMap: {+ 'agent_agent-1': {+ items: [+ {+ id: 'topic-1',+ metadata: { workingDirectory: '/Users/me/project' },+ },+ ],+ total: 1,+ },+ } as any,+ });++ render(+ <Render+ {...createRenderProps({+ linkHref: '/tmp/worktree-switcher-demo.html',+ linkLabel: 'worktree-switcher-demo.html',+ })}+ />,+ );++ fireEvent.click(screen.getByRole('link', { name: 'worktree-switcher-demo.html' }));++ expect(useChatStore.getState().openLocalFiles).toEqual([+ {+ allowExternalFilePreview: true,+ filePath: '/tmp/worktree-switcher-demo.html',+ id: createLocalFileTabId({+ filePath: '/tmp/worktree-switcher-demo.html',+ workingDirectory: '/tmp',+ }),+ workingDirectory: '/tmp',+ },+ ]);+ });});diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsxindex a9acdb9aa96..ea07d95509b 100644--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx@@ -78,6 +78,8 @@ const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) =>const openLocalFile = useChatStore((s) => s.openLocalFile);const workingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);const parsed = isDesktop ? parseLocalFileHref(linkHref, { workingDirectory }) : null;+ const allowExternalFilePreview =+ !!parsed && (!workingDirectory || parsed.workingDirectory !== workingDirectory);const label = linkLabel || parsed?.filePath || linkHref || '';const iconFileName = parsed ? getFileName(parsed.filePath) : label;const title = parsed ? formatLocalFileTitle(parsed) : linkHref;@@ -91,11 +93,12 @@ const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) =>event.preventDefault();openLocalFile({+ allowExternalFilePreview,filePath: parsed.filePath,workingDirectory: parsed.workingDirectory,});},- [openLocalFile, parsed],+ [allowExternalFilePreview, openLocalFile, parsed],);return (diff --git a/src/features/Portal/LocalFile/Body.test.tsx b/src/features/Portal/LocalFile/Body.test.tsxindex 942e4d9e7ba..229ea57ae20 100644--- a/src/features/Portal/LocalFile/Body.test.tsx+++ b/src/features/Portal/LocalFile/Body.test.tsx@@ -2,11 +2,17 @@ import { render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { localFileKeys } from '@/libs/swr/keys';import { createLocalFileScopeKey, createLocalFileTabId } from '@/store/chat/slices/portal/helpers';import { topicMapKey } from '@/store/chat/utils/topicMapKey';import Body from './Body';+vi.mock('@lobechat/const', async (importOriginal) => ({+ ...((await importOriginal()) as Record<string, unknown>),+ isDesktop: true,+}));+vi.mock('antd-style', () => ({createStaticStyles: () => ({card: 'card',@@ -54,15 +60,16 @@ vi.mock('@/components/Loading/CircleLoading', () => ({}));const mockUseClientDataSWR = vi.hoisted(() => vi.fn());+const mockProjectFileService = vi.hoisted(() => ({+ getLocalFilePreview: vi.fn(),+}));vi.mock('@/libs/swr', () => ({useClientDataSWR: mockUseClientDataSWR,}));vi.mock('@/services/projectFile', () => ({- projectFileService: {- getLocalFilePreview: vi.fn(),- },+ projectFileService: mockProjectFileService,}));vi.mock('@/utils/skillMarkdown', () => ({@@ -101,12 +108,19 @@ vi.mock('@/store/chat/selectors', () => {const openLocalFiles = (state: Record<PropertyKey, unknown>) => {const files =(state.openLocalFiles as- | Array<{ filePath: string; id?: string; workingDirectory: string }>+ | Array<{+ allowExternalFilePreview?: boolean;+ filePath: string;+ id?: string;+ workingDirectory: string;+ }>| undefined) ?? [];const workingDirectory = getCurrentWorkingDirectory(state);return workingDirectory- ? files.filter((file) => file.workingDirectory === workingDirectory)+ ? files.filter(+ (file) => file.allowExternalFilePreview || file.workingDirectory === workingDirectory,+ ): files;};@@ -172,6 +186,8 @@ const createChatState = (activeTopicId: 'topic-a' | 'topic-b') => ({describe('LocalFile Body', () => {beforeEach(() => {mockClearPortalStack.mockClear();+ mockProjectFileService.getLocalFilePreview.mockClear();+ mockUseClientDataSWR.mockClear();mockUseClientDataSWR.mockReturnValue({isLoading: true,mutate: vi.fn(),@@ -196,4 +212,47 @@ describe('LocalFile Body', () => {expect(screen.getByTestId('loading')).toBeInTheDocument();expect(mockClearPortalStack).not.toHaveBeenCalled();});++ it('keeps user-approved external preview tabs visible outside the current project scope', () => {+ const externalFileId = createLocalFileTabId({+ filePath: '/tmp/worktree-switcher-demo.html',+ workingDirectory: '/tmp',+ });+ mockChatState.current = {+ ...createChatState('topic-a'),+ activeLocalFileId: externalFileId,+ activeLocalFilePath: '/tmp/worktree-switcher-demo.html',+ openLocalFiles: [+ {+ allowExternalFilePreview: true,+ filePath: '/tmp/worktree-switcher-demo.html',+ id: externalFileId,+ workingDirectory: '/tmp',+ },+ ],+ };++ render(<Body />);++ expect(screen.getByTestId('loading')).toBeInTheDocument();+ expect(mockClearPortalStack).not.toHaveBeenCalled();+ expect(mockUseClientDataSWR).toHaveBeenCalledWith(+ localFileKeys.preview({+ allowExternalFile: true,+ filePath: '/tmp/worktree-switcher-demo.html',+ workingDirectory: '/tmp',+ }),+ expect.any(Function),+ { revalidateOnFocus: false },+ );++ const fetcher = mockUseClientDataSWR.mock.calls.at(-1)?.[1] as () => Promise<unknown>;+ void fetcher();+ expect(mockProjectFileService.getLocalFilePreview).toHaveBeenCalledWith({+ allowExternalFile: true,+ deviceId: undefined,+ path: '/tmp/worktree-switcher-demo.html',+ workingDirectory: '/tmp',+ });+ });});diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsxindex 23831703420..5d1542ff482 100644--- a/src/features/Portal/LocalFile/Body.tsx+++ b/src/features/Portal/LocalFile/Body.tsx@@ -20,6 +20,7 @@ import CodeEditorPane from '@/components/CodeEditorPane';import { InlineHtmlPreview, isHtmlFile } from '@/components/HtmlPreview';import Loading from '@/components/Loading/CircleLoading';import { useClientDataSWR } from '@/libs/swr';+import { localFileKeys } from '@/libs/swr/keys';import { type LocalFilePreview, projectFileService } from '@/services/projectFile';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';@@ -326,13 +327,14 @@ TextPreviewPane.displayName = 'TextPreviewPane';interface ActiveFileViewProps {activeTopicId?: string | null;+ allowExternalFilePreview?: boolean;deviceId?: string;filePath: string;workingDirectory: string;}const ActiveFileView = memo<ActiveFileViewProps>(- ({ activeTopicId, deviceId, filePath, workingDirectory }) => {+ ({ activeTopicId, allowExternalFilePreview, deviceId, filePath, workingDirectory }) => {const { t } = useTranslation('chat');const filename = filePath.split('/').at(-1) ?? '';@@ -344,9 +346,17 @@ const ActiveFileView = memo<ActiveFileViewProps>(isValidating,mutate,} = useClientDataSWR<LocalFilePreview>(- enabled ? ['local-file-preview', deviceId ?? 'local', filePath, workingDirectory] : null,+ enabled+ ? localFileKeys.preview({+ allowExternalFile: allowExternalFilePreview,+ deviceId,+ filePath,+ workingDirectory,+ })+ : null,() =>projectFileService.getLocalFilePreview({+ allowExternalFile: allowExternalFilePreview,deviceId,path: filePath,workingDirectory,@@ -430,6 +440,7 @@ const Body = memo(() => {<Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}><ActiveFileViewactiveTopicId={activeTopicId}+ allowExternalFilePreview={activeFile.allowExternalFilePreview}deviceId={activeFile.deviceId}filePath={activeFile.filePath}workingDirectory={activeFile.workingDirectory}diff --git a/src/features/Portal/LocalFile/MarkdownImage.test.tsx b/src/features/Portal/LocalFile/MarkdownImage.test.tsxindex 7f0fdab9945..41d6d96c666 100644--- a/src/features/Portal/LocalFile/MarkdownImage.test.tsx+++ b/src/features/Portal/LocalFile/MarkdownImage.test.tsx@@ -2,6 +2,8 @@ import { render, screen } from '@testing-library/react';import type { CSSProperties } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { localFileKeys } from '@/libs/swr/keys';+import MarkdownImage from './MarkdownImage';const mockImage = vi.hoisted(() => vi.fn());@@ -115,7 +117,12 @@ describe('MarkdownImage', () => {expect(screen.getByTestId('lobe-image')).toHaveAttribute('src', 'blob:markdown-image');expect(mockUseClientDataSWR).toHaveBeenCalledWith(- ['local-markdown-image-preview', 'device-1', '/repo/.records/assets/screenshot.png', '/repo'],+ localFileKeys.preview({+ accept: 'image',+ deviceId: 'device-1',+ filePath: '/repo/.records/assets/screenshot.png',+ workingDirectory: '/repo',+ }),expect.any(Function),{ revalidateOnFocus: false },);diff --git a/src/features/Portal/LocalFile/MarkdownImage.tsx b/src/features/Portal/LocalFile/MarkdownImage.tsxindex 20fb5ef96b7..54ab51e42d2 100644--- a/src/features/Portal/LocalFile/MarkdownImage.tsx+++ b/src/features/Portal/LocalFile/MarkdownImage.tsx@@ -4,6 +4,7 @@ import type { ComponentProps } from 'react';import { memo, useEffect, useMemo, useState } from 'react';import { useClientDataSWR } from '@/libs/swr';+import { localFileKeys } from '@/libs/swr/keys';import { type LocalFilePreview, projectFileService } from '@/services/projectFile';import { resolveMarkdownRelativeAssetPath } from './Body.helpers';@@ -27,7 +28,12 @@ const MarkdownImage = memo<MarkdownImageProps>(const { data: preview } = useClientDataSWR<LocalFilePreview>(resolvedPath- ? ['local-markdown-image-preview', deviceId ?? 'local', resolvedPath, workingDirectory]+ ? localFileKeys.preview({+ accept: 'image',+ deviceId,+ filePath: resolvedPath,+ workingDirectory,+ }): null,() =>projectFileService.getLocalFilePreview({diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex f99ecad05f1..b244623a21c 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -32,6 +32,14 @@ const def = <A extends unknown[]>(build: (...args: A) => readonly unknown[],): KeyFactory<A> => Object.assign(build, { root });+interface LocalFilePreviewKeyParams {+ accept?: 'image';+ allowExternalFile?: boolean;+ deviceId?: string;+ filePath: string;+ workingDirectory: string;+}+// ---- message ------------------------------------------------------------/*** Message cache schema version. Baked into the message list key so a bump@@ -627,6 +635,40 @@ export const portalKeys = {]),};+// ---- local file ---------------------------------------------------------+export const localFileKeys = {+ gitWorkingTreeFiles: def(+ 'localFile:gitWorkingTreeFiles',+ (deviceId: string | undefined, dirPath: string) => [+ 'localFile:gitWorkingTreeFiles',+ deviceId ?? 'local',+ dirPath,+ ],+ ),+ preview: def(+ 'localFile:preview',+ ({+ accept,+ allowExternalFile,+ deviceId,+ filePath,+ workingDirectory,+ }: LocalFilePreviewKeyParams) => [+ 'localFile:preview',+ deviceId ?? 'local',+ filePath,+ workingDirectory,+ accept ?? 'any',+ allowExternalFile ? 'external' : 'workspace',+ ],+ ),+ projectIndex: def('localFile:projectIndex', (deviceId: string | undefined, dirPath: string) => [+ 'localFile:projectIndex',+ deviceId ?? 'local',+ dirPath,+ ]),+};+// ---- favorite status (marketplace detail headers) -----------------------export const favoriteKeys = {status: def('favorite:status', (targetType: string, identifier: string) => [@@ -789,6 +831,7 @@ export const swrKeys = {imessage: imessageKeys,inbox: inboxKeys,knowledgeBase: knowledgeBaseKeys,+ localFile: localFileKeys,message: messageKeys,messenger: messengerKeys,notebook: notebookSWRKeys,diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/useGitWorkingTreeFiles.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/useGitWorkingTreeFiles.tsindex 720236dfa07..46a728c98e9 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/useGitWorkingTreeFiles.ts+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/useGitWorkingTreeFiles.ts@@ -3,6 +3,7 @@ import type { GitWorkingTreeFiles } from '@lobechat/electron-client-ipc';import type { GitStatusEntry } from '@pierre/trees';import { useClientDataSWR } from '@/libs/swr';+import { localFileKeys } from '@/libs/swr/keys';import { gitService } from '@/services/git';export const buildGitStatusEntries = (files: GitWorkingTreeFiles | undefined): GitStatusEntry[] => {@@ -26,7 +27,7 @@ export const useGitWorkingTreeFiles = (enabled: boolean,) => {const active = (!!deviceId || isDesktop) && !!dirPath && enabled;- const key = active ? ['git-working-tree-files', deviceId ?? 'local', dirPath] : null;+ const key = active ? localFileKeys.gitWorkingTreeFiles(deviceId, dirPath!) : null;return useClientDataSWR<GitWorkingTreeFiles | undefined>(key,diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/useProjectFiles.ts b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/useProjectFiles.tsindex 1ead6c3c45a..5babfca0939 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/useProjectFiles.ts+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Files/useProjectFiles.ts@@ -2,6 +2,7 @@ import { isDesktop } from '@lobechat/const';import type { ProjectFileIndexResult } from '@lobechat/electron-client-ipc';import { useClientDataSWR } from '@/libs/swr';+import { localFileKeys } from '@/libs/swr/keys';import { projectFileService } from '@/services/projectFile';/**@@ -12,7 +13,7 @@ import { projectFileService } from '@/services/projectFile';*/export const useProjectFiles = (deviceId: string | undefined, dirPath: string | undefined) => {const enabled = Boolean(dirPath) && (!!deviceId || isDesktop);- const key = enabled ? ['project-file-index', deviceId ?? 'local', dirPath] : null;+ const key = enabled ? localFileKeys.projectIndex(deviceId, dirPath!) : null;return useClientDataSWR<ProjectFileIndexResult | undefined>(key,diff --git a/src/store/chat/slices/portal/action.test.ts b/src/store/chat/slices/portal/action.test.tsindex edb1ddcb327..7a6a76eff7f 100644--- a/src/store/chat/slices/portal/action.test.ts+++ b/src/store/chat/slices/portal/action.test.ts@@ -408,6 +408,31 @@ describe('chatDockSlice', () => {expect(result.current.activeLocalFilePath).toBe('/path/a.ts');});+ it('should keep user-approved external preview context when opening a local file', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ result.current.openLocalFile({+ allowExternalFilePreview: true,+ filePath: '/tmp/worktree-switcher-demo.html',+ workingDirectory: '/tmp',+ });+ });++ expect(result.current.openLocalFiles).toEqual([+ {+ allowExternalFilePreview: true,+ filePath: '/tmp/worktree-switcher-demo.html',+ id: localFileTabId({+ filePath: '/tmp/worktree-switcher-demo.html',+ workingDirectory: '/tmp',+ }),+ workingDirectory: '/tmp',+ },+ ]);+ expect(result.current.activeLocalFilePath).toBe('/tmp/worktree-switcher-demo.html');+ });+it('should keep same file path from different device context as separate tabs', () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.tsindex d1d639c761b..385a0362109 100644--- a/src/store/chat/slices/portal/action.ts+++ b/src/store/chat/slices/portal/action.ts@@ -3,6 +3,7 @@ import { type ChatStore } from '@/store/chat/store';import { type StoreSetter } from '@/store/types';import { type PortalArtifact } from '@/types/artifact';+import { topicSelectors } from '../topic/selectors';import { createLocalFileScopeKey, createLocalFileTabId, getLocalFileTabId } from './helpers';import { type OpenLocalFileParams, type PortalFile, type PortalViewData } from './initialState';import { PortalViewType } from './initialState';@@ -33,11 +34,55 @@ const findLocalFileById = <T extends OpenLocalFileParams & { id?: string }>(const getLocalFileEntryScopeKey = (file: OpenLocalFileParams): string =>createLocalFileScopeKey(file.workingDirectory);-const getLocalFilesInScope = <T extends OpenLocalFileParams & { id?: string }>(+const getLocalFilesInEntryScope = <T extends OpenLocalFileParams & { id?: string }>(openLocalFiles: T[],scopeKey: string,) => openLocalFiles.filter((file) => getLocalFileEntryScopeKey(file) === scopeKey);+const getCurrentLocalFileScopeKey = (state: ChatStore): string | undefined => {+ const workingDirectory = topicSelectors.currentTopicWorkingDirectory(state);++ return workingDirectory ? createLocalFileScopeKey(workingDirectory) : undefined;+};++const getLocalFileCloseScope = <T extends OpenLocalFileParams & { id?: string }>({+ openLocalFiles,+ state,+ target,+}: {+ openLocalFiles: T[];+ state: ChatStore;+ target: T;+}): { files: T[]; scopeKey: string } => {+ const currentScopeKey = getCurrentLocalFileScopeKey(state);+ const targetEntryScopeKey = getLocalFileEntryScopeKey(target);+ const targetIsVisibleInCurrentScope =+ !!currentScopeKey &&+ (target.allowExternalFilePreview || targetEntryScopeKey === currentScopeKey);++ if (!currentScopeKey || !targetIsVisibleInCurrentScope) {+ return {+ files: getLocalFilesInEntryScope(openLocalFiles, targetEntryScopeKey),+ scopeKey: targetEntryScopeKey,+ };+ }++ return {+ files: openLocalFiles.filter(+ (file) =>+ file.allowExternalFilePreview || getLocalFileEntryScopeKey(file) === currentScopeKey,+ ),+ scopeKey: currentScopeKey,+ };+};++const getLocalFileActivationScopeKey = (state: ChatStore, file: OpenLocalFileParams): string => {+ const entryScopeKey = getLocalFileEntryScopeKey(file);+ const currentScopeKey = getCurrentLocalFileScopeKey(state);++ return file.allowExternalFilePreview && currentScopeKey ? currentScopeKey : entryScopeKey;+};+const resolveActiveLocalFile = <T extends OpenLocalFileParams & { id?: string }>(openLocalFiles: T[],activeLocalFileId: string | undefined,@@ -74,16 +119,18 @@ const setActiveLocalFileForScope = (return next;};-const keepScopedLocalFiles = <T extends OpenLocalFileParams & { id?: string }>(+const keepCloseScopedLocalFiles = <T extends OpenLocalFileParams & { id?: string }>(openLocalFiles: T[],- scopeKey: string,- scopedFilesToKeep: T[],+ closeScopeFiles: T[],+ closeScopeFilesToKeep: T[],) => {- const keepIds = new Set(scopedFilesToKeep.map(getLocalFileTabId));+ const closeScopeIds = new Set(closeScopeFiles.map(getLocalFileTabId));+ const keepIds = new Set(closeScopeFilesToKeep.map(getLocalFileTabId));- return openLocalFiles.filter(- (file) => getLocalFileEntryScopeKey(file) !== scopeKey || keepIds.has(getLocalFileTabId(file)),- );+ return openLocalFiles.filter((file) => {+ const id = getLocalFileTabId(file);+ return !closeScopeIds.has(id) || keepIds.has(id);+ });};const resolveLegacyActiveAfterClose = ({@@ -173,8 +220,11 @@ export class ChatPortalActionImpl {const target = openLocalFiles[idx];const targetId = getLocalFileTabId(target);- const scopeKey = getLocalFileEntryScopeKey(target);- const scopedFiles = getLocalFilesInScope(openLocalFiles, scopeKey);+ const { files: scopedFiles, scopeKey } = getLocalFileCloseScope({+ openLocalFiles,+ state: this.#get(),+ target,+ });const scopedIdx = findLocalFileIndexById(scopedFiles, targetId);const nextFiles = openLocalFiles.filter((_, i) => i !== idx);const nextScopedFiles = scopedFiles.filter((_, i) => i !== scopedIdx);@@ -235,13 +285,16 @@ export class ChatPortalActionImpl {if (idx < 0) return;const target = openLocalFiles[idx];- const scopeKey = getLocalFileEntryScopeKey(target);- const scopedFiles = getLocalFilesInScope(openLocalFiles, scopeKey);+ const { files: scopedFiles, scopeKey } = getLocalFileCloseScope({+ openLocalFiles,+ state: this.#get(),+ target,+ });const scopedIdx = findLocalFileIndexById(scopedFiles, getLocalFileTabId(target));if (scopedIdx <= 0) return;const nextScopedFiles = scopedFiles.slice(scopedIdx);- const nextFiles = keepScopedLocalFiles(openLocalFiles, scopeKey, nextScopedFiles);+ const nextFiles = keepCloseScopedLocalFiles(openLocalFiles, scopedFiles, nextScopedFiles);const scopedActiveFile = resolveActiveLocalFileInScope(scopedFiles,scopeKey,@@ -285,10 +338,14 @@ export class ChatPortalActionImpl {const { activeLocalFileIdsByScope, openLocalFiles } = this.#get();const target = findLocalFileById(openLocalFiles, id);if (!target) return;- const scopeKey = getLocalFileEntryScopeKey(target);+ const { files: scopedFiles, scopeKey } = getLocalFileCloseScope({+ openLocalFiles,+ state: this.#get(),+ target,+ });const targetId = getLocalFileTabId(target);const targetFile = { ...target, id: targetId };- const nextFiles = keepScopedLocalFiles(openLocalFiles, scopeKey, [targetFile]);+ const nextFiles = keepCloseScopedLocalFiles(openLocalFiles, scopedFiles, [targetFile]);this.#set({@@ -313,13 +370,16 @@ export class ChatPortalActionImpl {if (idx < 0) return;const target = openLocalFiles[idx];- const scopeKey = getLocalFileEntryScopeKey(target);- const scopedFiles = getLocalFilesInScope(openLocalFiles, scopeKey);+ const { files: scopedFiles, scopeKey } = getLocalFileCloseScope({+ openLocalFiles,+ state: this.#get(),+ target,+ });const scopedIdx = findLocalFileIndexById(scopedFiles, getLocalFileTabId(target));if (scopedIdx < 0 || scopedIdx >= scopedFiles.length - 1) return;const nextScopedFiles = scopedFiles.slice(0, scopedIdx + 1);- const nextFiles = keepScopedLocalFiles(openLocalFiles, scopeKey, nextScopedFiles);+ const nextFiles = keepCloseScopedLocalFiles(openLocalFiles, scopedFiles, nextScopedFiles);const scopedActiveFile = resolveActiveLocalFileInScope(scopedFiles,scopeKey,@@ -407,14 +467,23 @@ export class ChatPortalActionImpl {this.#get().pushPortalView({ file, type: PortalViewType.FilePreview });};- openLocalFile = ({ deviceId, filePath, workingDirectory }: OpenLocalFileParams): void => {+ openLocalFile = ({+ allowExternalFilePreview,+ deviceId,+ filePath,+ workingDirectory,+ }: OpenLocalFileParams): void => {const { activeLocalFileIdsByScope, openLocalFiles } = this.#get();const id = createLocalFileTabId({ deviceId, filePath, workingDirectory });- const scopeKey = createLocalFileScopeKey(workingDirectory);const exists = openLocalFiles.some((f) => getLocalFileTabId(f) === id);- const nextFile = deviceId- ? { deviceId, filePath, id, workingDirectory }- : { filePath, id, workingDirectory };+ const nextFile = {+ ...(allowExternalFilePreview === undefined ? {} : { allowExternalFilePreview }),+ ...(deviceId ? { deviceId } : {}),+ filePath,+ id,+ workingDirectory,+ };+ const scopeKey = getLocalFileActivationScopeKey(this.#get(), nextFile);const nextFiles = exists? openLocalFiles.map((file) => (getLocalFileTabId(file) === id ? nextFile : file)): [...openLocalFiles, nextFile];@@ -438,7 +507,9 @@ export class ChatPortalActionImpl {setActiveLocalFile = (id: string): void => {const { activeLocalFileIdsByScope, openLocalFiles } = this.#get();const activeFile = findLocalFileById(openLocalFiles, id);- const scopeKey = activeFile ? getLocalFileEntryScopeKey(activeFile) : undefined;+ const scopeKey = activeFile+ ? getLocalFileActivationScopeKey(this.#get(), activeFile)+ : undefined;this.#set({activeLocalFileId: activeFile ? getLocalFileTabId(activeFile) : id,diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.tsindex 09d9aa6e128..d1a8e69cd76 100644--- a/src/store/chat/slices/portal/initialState.ts+++ b/src/store/chat/slices/portal/initialState.ts@@ -28,6 +28,7 @@ export interface PortalFile {}export interface OpenLocalFileParams {+ allowExternalFilePreview?: boolean;deviceId?: string;filePath: string;workingDirectory: string;diff --git a/src/store/chat/slices/portal/selectors.test.ts b/src/store/chat/slices/portal/selectors.test.tsindex 916764e9a3d..14cc4a1b44f 100644--- a/src/store/chat/slices/portal/selectors.test.ts+++ b/src/store/chat/slices/portal/selectors.test.ts@@ -425,6 +425,30 @@ describe('chatDockSelectors', () => {{ filePath: '/project-b/b.ts', workingDirectory: '/project-b' },]);});++ it('should keep user-approved external preview files visible across topic scopes', () => {+ const externalFile = {+ allowExternalFilePreview: true,+ filePath: '/tmp/worktree-switcher-demo.html',+ workingDirectory: '/tmp',+ };+ const state = createState({+ ...createTopicState('topic-b', {+ 'topic-a': '/project-a',+ 'topic-b': '/project-b',+ }),+ openLocalFiles: [+ { filePath: '/project-a/a.ts', workingDirectory: '/project-a' },+ { filePath: '/project-b/b.ts', workingDirectory: '/project-b' },+ externalFile,+ ],+ } as Partial<ChatStoreState>);++ expect(chatPortalSelectors.openLocalFiles(state)).toEqual([+ { filePath: '/project-b/b.ts', workingDirectory: '/project-b' },+ externalFile,+ ]);+ });});describe('activeLocalFilePath', () => {diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.tsindex d2a16a1411d..6e506ea299d 100644--- a/src/store/chat/slices/portal/selectors.ts+++ b/src/store/chat/slices/portal/selectors.ts@@ -143,6 +143,8 @@ const currentLocalFileScopeKey = (s: ChatStoreState): string | undefined => {};const isLocalFileInCurrentScope = (s: ChatStoreState, file: OpenLocalFileEntry): boolean => {+ if (file.allowExternalFilePreview) return true;+const workingDirectory = currentLocalFileScopeWorkingDirectory(s);return workingDirectory ? file.workingDirectory === workingDirectory : true;};