Skip to content

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

✨ feat(local-file): preview remote-device local files on web and mobile (#22647)

Tsuki18430e884f98
diff --git a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.test.tsx b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.test.tsx
new file mode 100644
index 00000000000..ffa2b84ca71
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.test.tsx
@@ -0,0 +1,107 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useChatStore } from '@/store/chat';
+import { useDeviceStore } from '@/store/device';
+import { DEVICE_LIST_KEY } from '@/store/device/projection';
+
+import { LocalFileTag } from './LocalFileTag';
+
+const platform = vi.hoisted(() => ({ isDesktop: false }));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ get isDesktop() {
+ return platform.isDesktop;
+ },
+}));
+
+vi.mock('@/components/FileIcon', () => ({
+ default: () => <span data-testid="file-icon" />,
+}));
+
+const { getLocalFilePreview } = vi.hoisted(() => ({
+ getLocalFilePreview: vi.fn(),
+}));
+
+vi.mock('@/services/projectFile', () => ({
+ projectFileService: { getLocalFilePreview },
+}));
+
+const setTopic = (topicMeta: Record<string, unknown>) =>
+ useChatStore.setState({
+ activeAgentId: 'agent-1',
+ activeTopicId: 'topic-1',
+ topicDataMap: {
+ 'agent_agent-1': {
+ items: [
+ { id: 'topic-1', metadata: { workingDirectory: '/Users/me/project', ...topicMeta } },
+ ],
+ total: 1,
+ },
+ } as any,
+ });
+
+const setDevices = (devices: Array<{ deviceId: string; online: boolean }>) =>
+ useDeviceStore.setState({ deviceListMap: { [DEVICE_LIST_KEY]: devices as any } });
+
+const imageFile = { name: 'shot.png', path: '/Users/me/project/shot.png' };
+
+describe('LocalFileTag remote device preview', () => {
+ beforeEach(() => {
+ globalThis.URL.createObjectURL = vi.fn(() => 'blob:preview');
+ globalThis.URL.revokeObjectURL = vi.fn();
+ getLocalFilePreview.mockResolvedValue({ blob: new Blob(['x']), type: 'image' });
+ });
+
+ afterEach(() => {
+ platform.isDesktop = false;
+ getLocalFilePreview.mockReset();
+ useChatStore.setState(useChatStore.getInitialState());
+ useDeviceStore.setState(useDeviceStore.getInitialState());
+ });
+
+ it('reads the image thumbnail through the online topic device off desktop', async () => {
+ setTopic({ boundDeviceId: 'device-1' });
+ setDevices([{ deviceId: 'device-1', online: true }]);
+
+ render(<LocalFileTag file={imageFile} />);
+
+ await waitFor(() => expect(getLocalFilePreview).toHaveBeenCalledTimes(1));
+ expect(getLocalFilePreview).toHaveBeenCalledWith(
+ expect.objectContaining({
+ accept: 'image',
+ deviceId: 'device-1',
+ path: '/Users/me/project/shot.png',
+ workingDirectory: '/Users/me/project',
+ }),
+ );
+ });
+
+ it('never falls back to the local IPC read off desktop when no device can serve it', async () => {
+ setTopic({ boundDeviceId: 'device-1' });
+ setDevices([{ deviceId: 'device-1', online: false }]);
+
+ const { rerender } = render(<LocalFileTag file={imageFile} />);
+
+ setTopic({});
+ rerender(<LocalFileTag file={imageFile} />);
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(getLocalFilePreview).not.toHaveBeenCalled();
+ });
+
+ it('keeps desktop on local IPC (no deviceId) even when the topic has a device', async () => {
+ platform.isDesktop = true;
+ setTopic({ boundDeviceId: 'device-1' });
+ setDevices([{ deviceId: 'device-1', online: true }]);
+
+ render(<LocalFileTag file={imageFile} />);
+
+ await waitFor(() => expect(getLocalFilePreview).toHaveBeenCalledTimes(1));
+ expect(getLocalFilePreview.mock.calls[0][0].deviceId).toBeUndefined();
+ });
+});
diff --git a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx
index 5e4d14cd0b2..7ad219b87ad 100644
--- a/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx
+++ b/src/features/ChatInput/InputEditor/LocalFileTag/LocalFileTag.tsx
@@ -18,6 +18,7 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
+import { useTopicRemoteDeviceId } from '@/features/LocalFile/useTopicRemoteDeviceId';
import { useClientDataSWR } from '@/libs/swr';
import { localFileKeys } from '@/libs/swr/keys';
import { localFileService } from '@/services/electron/localFileService';
@@ -228,6 +229,9 @@ export const LocalFileTag = memo<LocalFileTagProps>(({ className, editor, file,
const { t } = useTranslation('chat');
const openLocalFile = useChatStore((s) => s.openLocalFile);
const workingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);
+ // Off desktop the file lives on the topic's device and is read over the
+ // device RPC while it is online; desktop keeps local IPC.
+ const remoteDeviceId = useTopicRemoteDeviceId();
const parsed = useMemo(
() => parseLocalFileHref(file.path, { workingDirectory }),
@@ -235,7 +239,8 @@ export const LocalFileTag = memo<LocalFileTagProps>(({ className, editor, file,
);
const allowExternalFilePreview =
!!parsed && (!workingDirectory || parsed.workingDirectory !== workingDirectory);
- const canPreview = isDesktop && !file.isDirectory && !!parsed?.workingDirectory;
+ const canPreview =
+ (isDesktop || !!remoteDeviceId) && !file.isDirectory && !!parsed?.workingDirectory;
const canRenderImagePreview = canPreview && isPreviewableImageFile(file);
const { data: imagePreview } = useClientDataSWR<LocalFilePreview>(
@@ -243,6 +248,7 @@ export const LocalFileTag = memo<LocalFileTagProps>(({ className, editor, file,
? localFileKeys.preview({
accept: 'image',
allowExternalFile: allowExternalFilePreview || undefined,
+ deviceId: remoteDeviceId,
filePath: parsed.filePath,
workingDirectory: parsed.workingDirectory,
})
@@ -251,6 +257,7 @@ export const LocalFileTag = memo<LocalFileTagProps>(({ className, editor, file,
projectFileService.getLocalFilePreview({
accept: 'image',
allowExternalFile: allowExternalFilePreview || undefined,
+ deviceId: remoteDeviceId,
path: parsed!.filePath,
workingDirectory: parsed!.workingDirectory,
}),
@@ -279,11 +286,12 @@ export const LocalFileTag = memo<LocalFileTagProps>(({ className, editor, file,
openLocalFile({
allowExternalFilePreview,
+ deviceId: remoteDeviceId,
filePath: parsed.filePath,
workingDirectory: parsed.workingDirectory,
});
},
- [allowExternalFilePreview, openLocalFile, parsed],
+ [allowExternalFilePreview, openLocalFile, parsed, remoteDeviceId],
);
const handleOpen = useCallback(
@@ -316,19 +324,24 @@ export const LocalFileTag = memo<LocalFileTagProps>(({ className, editor, file,
</div>
)}
<Text className={styles.path}>{file.path}</Text>
- {isDesktop && (
+ {(isDesktop || canPreview) && (
<Flexbox horizontal className={styles.actionBar} gap={6}>
{canPreview && (
<Button icon={<Icon icon={EyeIcon} />} size={'small'} onClick={handlePreview}>
{t('workingPanel.documents.preview')}
</Button>
)}
- <Button icon={<Icon icon={ExternalLink} />} size={'small'} onClick={handleOpen}>
- {t('workingPanel.files.open')}
- </Button>
- <Button icon={<Icon icon={FolderOpen} />} size={'small'} onClick={handleReveal}>
- {t('workingPanel.files.showInSystem')}
- </Button>
+ {/* Open / Show in Folder are Electron IPC: nothing to call off desktop. */}
+ {isDesktop && (
+ <>
+ <Button icon={<Icon icon={ExternalLink} />} size={'small'} onClick={handleOpen}>
+ {t('workingPanel.files.open')}
+ </Button>
+ <Button icon={<Icon icon={FolderOpen} />} size={'small'} onClick={handleReveal}>
+ {t('workingPanel.files.showInSystem')}
+ </Button>
+ </>
+ )}
</Flexbox>
)}
</Flexbox>
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
index 4ba02c2d94e..f96fcacce7d 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
@@ -9,6 +9,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { useChatStore } from '@/store/chat';
import { createLocalFileTabId } from '@/store/chat/slices/portal/helpers';
+import { useDeviceStore } from '@/store/device';
+import { DEVICE_LIST_KEY } from '@/store/device/projection';
import type { MarkdownElementProps } from '../type';
import Render from './Render';
@@ -63,6 +65,7 @@ describe('LocalFileLink Render', () => {
afterEach(() => {
platform.isDesktop = true;
useChatStore.setState(useChatStore.getInitialState());
+ useDeviceStore.setState(useDeviceStore.getInitialState());
});
it.each(['/home/ubuntu/workspace/src/client.ts:391', './src/client.ts:391'])(
@@ -207,4 +210,101 @@ describe('LocalFileLink Render', () => {
},
]);
});
+ describe('on mobile / web with a remote topic device', () => {
+ const setRemoteTopic = (topicMetadata: Record<string, unknown>) =>
+ useChatStore.setState({
+ activeAgentId: 'agent-1',
+ activeTopicId: 'topic-1',
+ topicDataMap: {
+ 'agent_agent-1': {
+ items: [
+ {
+ id: 'topic-1',
+ metadata: { workingDirectory: '/Users/me/project', ...topicMetadata },
+ },
+ ],
+ total: 1,
+ },
+ } as any,
+ });
+
+ const setDevices = (devices: Array<{ deviceId: string; online: boolean }>) =>
+ useDeviceStore.setState({ deviceListMap: { [DEVICE_LIST_KEY]: devices as any } });
+
+ const renderPdfLink = () =>
+ render(
+ <Render
+ {...createRenderProps({
+ linkHref: '/Users/me/project/docs/x.pdf',
+ linkLabel: 'x.pdf',
+ })}
+ />,
+ );
+
+ it('opens the portal through the online topic device', () => {
+ platform.isDesktop = false;
+ setRemoteTopic({ boundDeviceId: 'device-1' });
+ setDevices([{ deviceId: 'device-1', online: true }]);
+
+ renderPdfLink();
+ fireEvent.click(screen.getByRole('link', { name: 'x.pdf' }));
+
+ expect(useChatStore.getState().openLocalFiles).toEqual([
+ {
+ allowExternalFilePreview: false,
+ deviceId: 'device-1',
+ filePath: '/Users/me/project/docs/x.pdf',
+ id: createLocalFileTabId({
+ deviceId: 'device-1',
+ filePath: '/Users/me/project/docs/x.pdf',
+ workingDirectory: '/Users/me/project',
+ }),
+ workingDirectory: '/Users/me/project',
+ },
+ ]);
+ expect(useChatStore.getState().showPortal).toBe(true);
+ });
+
+ it('stays a non-clickable chip when the topic has no device', () => {
+ platform.isDesktop = false;
+ setRemoteTopic({});
+ setDevices([{ deviceId: 'device-1', online: true }]);
+
+ const { container } = renderPdfLink();
+
+ expect(screen.queryByRole('link')).toBeNull();
+ expect(container.querySelector('[href]')).toBeNull();
+ fireEvent.click(screen.getByText('x.pdf'));
+ expect(useChatStore.getState().openLocalFiles).toEqual([]);
+ });
+
+ it('stays a non-clickable chip while the topic device is offline', () => {
+ platform.isDesktop = false;
+ setRemoteTopic({ boundDeviceId: 'device-1' });
+ setDevices([{ deviceId: 'device-1', online: false }]);
+
+ renderPdfLink();
+
+ expect(screen.queryByRole('link')).toBeNull();
+ fireEvent.click(screen.getByText('x.pdf'));
+ expect(useChatStore.getState().openLocalFiles).toEqual([]);
+ });
+
+ it('keeps desktop on local IPC even when the topic has a device', () => {
+ setRemoteTopic({ boundDeviceId: 'device-1' });
+ setDevices([{ deviceId: 'device-1', online: true }]);
+
+ renderPdfLink();
+ fireEvent.click(screen.getByRole('link', { name: 'x.pdf' }));
+
+ const [opened] = useChatStore.getState().openLocalFiles;
+ expect(opened).not.toHaveProperty('deviceId');
+ expect(opened.id).toBe(
+ createLocalFileTabId({
+ filePath: '/Users/me/project/docs/x.pdf',
+ workingDirectory: '/Users/me/project',
+ }),
+ );
+ });
+ });
});
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
index c93aa5b4d9b..d3b8a9ecc09 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.tsx
@@ -7,6 +7,7 @@ import type { MouseEvent } from 'react';
import { memo, useCallback } from 'react';
import FileIcon from '@/components/FileIcon';
+import { useTopicRemoteDeviceId } from '@/features/LocalFile/useTopicRemoteDeviceId';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
@@ -83,8 +84,11 @@ const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) =>
const { linkHref, linkLabel } = node?.properties || {};
const openLocalFile = useChatStore((s) => s.openLocalFile);
const workingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);
+ // Off desktop the file lives on the topic's device: the portal reads it over
+ // the device RPC while that device is online. Desktop keeps local IPC.
+ const remoteDeviceId = useTopicRemoteDeviceId();
const parsed = parseLocalFileHref(linkHref, { workingDirectory });
- const canPreview = isDesktop && !!parsed?.workingDirectory;
+ const canPreview = (isDesktop || !!remoteDeviceId) && !!parsed?.workingDirectory;
const allowExternalFilePreview =
!!parsed && (!workingDirectory || parsed.workingDirectory !== workingDirectory);
const label = linkLabel || parsed?.filePath || linkHref || '';
@@ -99,11 +103,12 @@ const Render = memo<MarkdownElementProps<LocalFileLinkProperties>>(({ node }) =>
event.preventDefault();
openLocalFile({
allowExternalFilePreview,
+ deviceId: remoteDeviceId,
filePath: parsed.filePath,
workingDirectory: parsed.workingDirectory,
});
},
- [allowExternalFilePreview, canPreview, openLocalFile, parsed],
+ [allowExternalFilePreview, canPreview, openLocalFile, parsed, remoteDeviceId],
);
if (!canPreview) {
diff --git a/src/features/LocalFile/useTopicRemoteDeviceId.ts b/src/features/LocalFile/useTopicRemoteDeviceId.ts
new file mode 100644
index 00000000000..baafcd751d2
--- /dev/null
+++ b/src/features/LocalFile/useTopicRemoteDeviceId.ts
@@ -0,0 +1,31 @@
+import { isDesktop } from '@lobechat/const';
+
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { deviceSelectors, useDeviceStore } from '@/store/device';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+/**
+ * The device that can serve local-file reads for the current topic when this
+ * client has no filesystem of its own (web / mobile SPA).
+ *
+ * Returns the topic's device id only while that device is online, so callers
+ * can gate previews on it: a preview without a `deviceId` would fall back to
+ * the Electron IPC transport, which does not exist off desktop and fails
+ * silently.
+ *
+ * Desktop always gets `undefined` and keeps reading through local IPC.
+ */
+export const useTopicRemoteDeviceId = (): string | undefined => {
+ const topicDeviceId = useChatStore(topicSelectors.currentTopicDeviceId);
+ const remoteDeviceId = isDesktop ? undefined : topicDeviceId;
+ const isLogin = useUserStore(authSelectors.isLogin);
+
+ useDeviceStore((s) => s.useFetchDevices)(!!remoteDeviceId && isLogin);
+ const isOnline = useDeviceStore(
+ (s) => !!remoteDeviceId && !!deviceSelectors.getDeviceById(remoteDeviceId)(s)?.online,
+ );
+
+ return isOnline ? remoteDeviceId : undefined;
+};
diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.ts
index df2aa0b2650..e4ae4b5dfae 100644
--- a/src/store/chat/slices/topic/selectors.test.ts
+++ b/src/store/chat/slices/topic/selectors.test.ts
@@ -247,6 +247,44 @@ describe('topicSelectors', () => {
});
});
+ describe('currentTopicDeviceId', () => {
+ const stateWithTopicMetadata = (topicMeta: Record<string, unknown> | undefined) =>
+ merge(initialStore, {
+ ...topicState(
+ topicMapKey({ agentId: 'test' }),
+ [{ id: 'topic-device', metadata: topicMeta }],
+ 1,
+ ),
+ activeTopicId: 'topic-device',
+ }) as ChatStore;
+
+ it('prefers the running operation device over the bound device', () => {
+ const state = stateWithTopicMetadata({
+ boundDeviceId: 'device-bound',
+ runningOperation: { deviceId: 'device-running', operationId: 'op-1' },
+ });
+
+ expect(topicSelectors.currentTopicDeviceId(state)).toBe('device-running');
+ });
+
+ it('falls back to the bound device when no run is in flight', () => {
+ const state = stateWithTopicMetadata({
+ boundDeviceId: 'device-bound',
+ runningOperation: null,
+ });
+
+ expect(topicSelectors.currentTopicDeviceId(state)).toBe('device-bound');
+ });
+
+ it('returns undefined when the topic has neither', () => {
+ expect(topicSelectors.currentTopicDeviceId(stateWithTopicMetadata({}))).toBeUndefined();
+ expect(
+ topicSelectors.currentTopicDeviceId(stateWithTopicMetadata(undefined)),
+ ).toBeUndefined();
+ expect(topicSelectors.currentTopicDeviceId(initialStore)).toBeUndefined();
+ });
+ });
+
describe('currentActiveTopic', () => {
it('should return undefined if there is no active topic', () => {
const topic = topicSelectors.currentActiveTopic(initialStore);
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index 7c446d37ba7..d6c39f20712 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -279,6 +279,21 @@ const getTopicWorkingDirectory =
const currentTopicWorkingDirectory = (s: ChatStoreState): string | undefined =>
extractTopicWorkingDirectory(currentActiveTopic(s));
+/**
+ * Extract the device a topic's local files live on.
+ * `runningOperation.deviceId` wins over the pinned `boundDeviceId`, matching
+ * the server-side `getTopicDeviceId` used for topic listing.
+ */
+const extractTopicDeviceId = (topic: ChatTopic | undefined): string | undefined =>
+ topic?.metadata?.runningOperation?.deviceId ?? topic?.metadata?.boundDeviceId ?? undefined;
+
+/**
+ * Get the device the current topic's local files belong to.
+ * Undefined for a topic that ran on this machine, or never bound one.
+ */
+const currentTopicDeviceId = (s: ChatStoreState): string | undefined =>
+ extractTopicDeviceId(currentActiveTopic(s));
+
const isCreatingTopic = (s: ChatStoreState) => s.creatingTopic;
/**
@@ -540,6 +555,7 @@ export const topicSelectors = {
currentActiveTopicSummary,
currentTopicCount,
currentTopicData,
+ currentTopicDeviceId,
currentTopicLength,
currentTopicMetadata,
currentTopicWorkingDirectory,