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(device): browse remote working directories on web (#19243)

Tsuki8ec25fc5da45
diff --git a/locales/en-US/device.json b/locales/en-US/device.json
index 0a82ccda789..c123310b94a 100644
--- a/locales/en-US/device.json
+++ b/locales/en-US/device.json
@@ -1,6 +1,7 @@
{
"workingDirectory.addFolder": "Add folder…",
"workingDirectory.addFolderDesc": "Enter an absolute path on the target device, e.g. /Users/name/projects",
+ "workingDirectory.addFolderFailed": "Could not add this folder. Please try again.",
"workingDirectory.addFolderTitle": "Add working directory",
"workingDirectory.agentDescription": "Default working directory for all conversations with this Agent",
"workingDirectory.agentLevel": "Agent Working Directory",
@@ -12,6 +13,8 @@
"workingDirectory.branchesLoadFailed": "Failed to load branches",
"workingDirectory.branchesLoading": "Loading branches…",
"workingDirectory.branchesNoMatch": "No matching branches",
+ "workingDirectory.browseDescription": "Choose a folder on the connected device.",
+ "workingDirectory.browseFolders": "Browse folders",
"workingDirectory.cancel": "Cancel",
"workingDirectory.checkoutAction": "Checkout",
"workingDirectory.checkoutFailed": "Checkout failed",
@@ -38,18 +41,27 @@
"workingDirectory.detachedWorktree": "detached",
"workingDirectory.diffLineStatTooltip": "Added lines {{added}} · Deleted lines {{deleted}} · Changed files {{files}}",
"workingDirectory.diffStatTooltip": "Added {{added}} · Modified {{modified}} · Deleted {{deleted}}",
+ "workingDirectory.enterPathManually": "Enter path manually",
"workingDirectory.filesAdded": "Added",
"workingDirectory.filesDeleted": "Deleted",
"workingDirectory.filesEmpty": "No uncommitted changes",
"workingDirectory.filesLoading": "Loading changes…",
"workingDirectory.filesModified": "Modified",
+ "workingDirectory.folderUnreadable": "No permission to open this folder",
+ "workingDirectory.foldersEmpty": "No subfolders. You can select this folder.",
+ "workingDirectory.foldersLoadFailed": "Could not load folders. Check the device connection and folder permissions, then retry or enter a path manually.",
+ "workingDirectory.foldersLoading": "Loading folders…",
"workingDirectory.ghMissing": "Install and log in to the GitHub CLI (`gh`) to see linked pull requests",
+ "workingDirectory.home": "Home folder",
+ "workingDirectory.loadMoreFolders": "Load more folders",
"workingDirectory.lockedWorktree": "locked",
"workingDirectory.newBranchPlaceholder": "feature/new-branch-name",
"workingDirectory.newWorktreeLocation": "Will be created at {{path}}",
"workingDirectory.noMatch": "No matching directories",
"workingDirectory.noRecent": "No directories yet",
"workingDirectory.notSet": "Click to set working directory",
+ "workingDirectory.openPath": "Open",
+ "workingDirectory.parentFolder": "Parent folder",
"workingDirectory.pathNotDirectory": "This path is not a directory",
"workingDirectory.pathNotExist": "This path doesn't exist on the device",
"workingDirectory.placeholder": "Enter directory path, e.g. /Users/name/projects",
@@ -92,6 +104,7 @@
"workingDirectory.uncommittedChanges_one": "Uncommitted changes: {{count}} file",
"workingDirectory.uncommittedChanges_other": "Uncommitted changes: {{count}} files",
"workingDirectory.undo": "Undo",
+ "workingDirectory.useFolder": "Use this folder",
"workingDirectory.worktreeSearchPlaceholder": "Search worktrees",
"workingDirectory.worktreeUnavailable": "unavailable",
"workingDirectory.worktreesEmpty": "No worktrees found",
diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.json
index 3682fc8d485..8ae2dc9d042 100644
--- a/locales/zh-CN/device.json
+++ b/locales/zh-CN/device.json
@@ -1,6 +1,7 @@
{
"workingDirectory.addFolder": "添加目录…",
"workingDirectory.addFolderDesc": "输入目标设备上的绝对路径,如 /Users/name/projects",
+ "workingDirectory.addFolderFailed": "无法添加此文件夹,请重试。",
"workingDirectory.addFolderTitle": "添加工作目录",
"workingDirectory.agentDescription": "该助手下所有对话的默认工作目录",
"workingDirectory.agentLevel": "代理工作目录",
@@ -12,6 +13,8 @@
"workingDirectory.branchesLoadFailed": "分支加载失败",
"workingDirectory.branchesLoading": "加载分支中…",
"workingDirectory.branchesNoMatch": "没有匹配的分支",
+ "workingDirectory.browseDescription": "选择已连接设备上的文件夹。",
+ "workingDirectory.browseFolders": "浏览文件夹",
"workingDirectory.cancel": "取消",
"workingDirectory.checkoutAction": "切换分支",
"workingDirectory.checkoutFailed": "切换分支失败",
@@ -38,18 +41,27 @@
"workingDirectory.detachedWorktree": "detached",
"workingDirectory.diffLineStatTooltip": "新增行 {{added}} · 删除行 {{deleted}} · 变更文件 {{files}}",
"workingDirectory.diffStatTooltip": "新增 {{added}} · 修改 {{modified}} · 删除 {{deleted}}",
+ "workingDirectory.enterPathManually": "手动输入路径",
"workingDirectory.filesAdded": "新增",
"workingDirectory.filesDeleted": "删除",
"workingDirectory.filesEmpty": "没有未提交的变更",
"workingDirectory.filesLoading": "加载中…",
"workingDirectory.filesModified": "修改",
+ "workingDirectory.folderUnreadable": "没有权限打开此文件夹",
+ "workingDirectory.foldersEmpty": "没有子文件夹,可以选择当前文件夹。",
+ "workingDirectory.foldersLoadFailed": "无法加载文件夹,请检查设备连接和目录权限后重试,或手动输入路径。",
+ "workingDirectory.foldersLoading": "正在加载文件夹…",
"workingDirectory.ghMissing": "安装并登录 GitHub CLI(gh)即可显示关联的 Pull Request",
+ "workingDirectory.home": "主目录",
+ "workingDirectory.loadMoreFolders": "加载更多文件夹",
"workingDirectory.lockedWorktree": "locked",
"workingDirectory.newBranchPlaceholder": "feature/新分支名称",
"workingDirectory.newWorktreeLocation": "将创建于 {{path}}",
"workingDirectory.noMatch": "没有匹配的目录",
"workingDirectory.noRecent": "暂无工作目录",
"workingDirectory.notSet": "点击设置工作目录",
+ "workingDirectory.openPath": "打开",
+ "workingDirectory.parentFolder": "上一级",
"workingDirectory.pathNotDirectory": "该路径不是一个目录",
"workingDirectory.pathNotExist": "该设备上不存在此路径",
"workingDirectory.placeholder": "输入目录路径,如 /Users/name/projects",
@@ -92,6 +104,7 @@
"workingDirectory.uncommittedChanges_one": "未提交的更改:{{count}} 个文件",
"workingDirectory.uncommittedChanges_other": "未提交的更改:{{count}} 个文件",
"workingDirectory.undo": "撤销",
+ "workingDirectory.useFolder": "选择此文件夹",
"workingDirectory.worktreeSearchPlaceholder": "搜索 worktree",
"workingDirectory.worktreeUnavailable": "不可用",
"workingDirectory.worktreesEmpty": "未发现 worktree",
diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.ts
index 3daa4e63652..76eb64a06f5 100644
--- a/packages/locales/src/default/device.ts
+++ b/packages/locales/src/default/device.ts
@@ -1,4 +1,18 @@
export default {
+ 'workingDirectory.addFolderFailed': 'Could not add this folder. Please try again.',
+ 'workingDirectory.browseDescription': 'Choose a folder on the connected device.',
+ 'workingDirectory.browseFolders': 'Browse folders',
+ 'workingDirectory.enterPathManually': 'Enter path manually',
+ 'workingDirectory.folderUnreadable': 'No permission to open this folder',
+ 'workingDirectory.foldersEmpty': 'No subfolders. You can select this folder.',
+ 'workingDirectory.foldersLoadFailed':
+ 'Could not load folders. Check the device connection and folder permissions, then retry or enter a path manually.',
+ 'workingDirectory.foldersLoading': 'Loading folders…',
+ 'workingDirectory.home': 'Home folder',
+ 'workingDirectory.loadMoreFolders': 'Load more folders',
+ 'workingDirectory.openPath': 'Open',
+ 'workingDirectory.parentFolder': 'Parent folder',
+ 'workingDirectory.useFolder': 'Use this folder',
'workingDirectory.addFolder': 'Add folder…',
'workingDirectory.addFolderDesc':
'Enter an absolute path on the target device, e.g. /Users/name/projects',
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
index cc0869e0109..e01dc22e628 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
@@ -225,7 +225,7 @@ const ChooseLocalFolderRow = memo<{ defaultPath?: string; onPick: (entry: Folder
);
ChooseLocalFolderRow.displayName = 'ChooseLocalFolderRow';
-/** Web / remote device: filesystem isn't browsable here — enter an absolute path. */
+/** Browse the target device through its directory RPC. */
const AddRemoteFolderRow = memo<{
defaultCwd?: string;
deviceId?: string;
@@ -234,7 +234,7 @@ const AddRemoteFolderRow = memo<{
}>(({ defaultCwd, deviceId, onBeforeOpen, onPick }) => {
const { t } = useTranslation('device');
- // Stat the entered path on the target device (it can't be browsed here): block
+ // Validate the selected or manually entered path on the target device: block
// on a definitive negative, otherwise commit with the detected repoType so the
// recent entry shows the right (git / github) icon. An unreachable device
// (null) is treated as "can't verify" and allowed through without a repoType.
@@ -250,7 +250,11 @@ const AddRemoteFolderRow = memo<{
const handleClick = () => {
onBeforeOpen();
- openAddWorkingDirModal({ onSubmit: handleSubmit, placeholder: defaultCwd || undefined });
+ openAddWorkingDirModal({
+ defaultPath: defaultCwd || undefined,
+ deviceId,
+ onSubmit: handleSubmit,
+ });
};
return (
<Flexbox
diff --git a/src/features/DeviceManager/DeviceDetailPanel.tsx b/src/features/DeviceManager/DeviceDetailPanel.tsx
index cd307ebb311..d78e0feb3b5 100644
--- a/src/features/DeviceManager/DeviceDetailPanel.tsx
+++ b/src/features/DeviceManager/DeviceDetailPanel.tsx
@@ -156,9 +156,7 @@ const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onC
};
const handleAddRecent = async () => {
- // This machine: browse natively. A remote / non-current device isn't
- // browsable from here, so fall back to manual absolute-path entry (the same
- // modal the chat control bar uses), statting the path on the target device.
+ // Browse this machine natively; other devices use the shared remote browser.
if (canBrowse) {
const result = await electronSystemService.selectFolder({
title: t('devices.detail.addDir'),
@@ -168,6 +166,8 @@ const DeviceDetailPanel = memo<DeviceDetailPanelProps>(({ device, isCurrent, onC
}
openAddWorkingDirModal({
+ defaultPath: device.defaultCwd || undefined,
+ deviceId: device.deviceId,
onSubmit: async (path) => {
const result = await deviceService.statPath(device.deviceId, path);
if (result) {
diff --git a/src/features/WorkingDirectory/AddWorkingDirModal.tsx b/src/features/WorkingDirectory/AddWorkingDirModal.tsx
index 7398e82a421..a663b1fe596 100644
--- a/src/features/WorkingDirectory/AddWorkingDirModal.tsx
+++ b/src/features/WorkingDirectory/AddWorkingDirModal.tsx
@@ -1,20 +1,19 @@
'use client';
import { Flexbox, Input } from '@lobehub/ui';
-import {
- Button,
- createModal,
- type ModalInstance,
- Text,
- useModalContext,
-} from '@lobehub/ui/base-ui';
-import { type InputRef } from 'antd';
+import type { ModalInstance } from '@lobehub/ui/base-ui';
+import { Button, createModal, Text, useModalContext } from '@lobehub/ui/base-ui';
+import type { InputRef } from 'antd';
import { cssVar } from 'antd-style';
import { t } from 'i18next';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { RemoteDirectoryBrowser } from './RemoteDirectoryBrowser';
+
interface AddWorkingDirContentProps {
+ defaultPath?: string;
+ deviceId?: string;
/**
* Submit the entered path. Return an error message to show inline and keep the
* modal open; return undefined on success (the modal closes). Lets the caller
@@ -24,26 +23,30 @@ interface AddWorkingDirContentProps {
placeholder?: string;
}
-const AddWorkingDirContent = memo<AddWorkingDirContentProps>(({ onSubmit, placeholder }) => {
+const AddWorkingDirContent = ({
+ defaultPath,
+ deviceId,
+ onSubmit,
+ placeholder,
+}: AddWorkingDirContentProps) => {
const { t: tPlugin } = useTranslation('device');
const { t: tCommon } = useTranslation('common');
const { close } = useModalContext();
- const [value, setValue] = useState('');
+ const [manual, setManual] = useState(!deviceId);
+ const [value, setValue] = useState(defaultPath ?? '');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
const inputRef = useRef<InputRef>(null);
useEffect(() => {
queueMicrotask(() => inputRef.current?.focus());
- }, []);
+ }, [manual]);
- const handleSubmit = useCallback(async () => {
+ const handleSubmit = async (path: string) => {
if (loading) return;
- const next = value.trim();
- if (!next) {
- close();
- return;
- }
+ const next = path.trim();
+ if (!next) return;
+ setError(undefined);
setLoading(true);
try {
const message = await onSubmit(next);
@@ -52,22 +55,43 @@ const AddWorkingDirContent = memo<AddWorkingDirContentProps>(({ onSubmit, placeh
return;
}
close();
+ } catch (cause) {
+ console.error('Failed to add working directory', cause);
+ setError(tPlugin('workingDirectory.addFolderFailed'));
} finally {
setLoading(false);
}
- }, [close, loading, onSubmit, value]);
+ };
+
+ if (!manual && deviceId) {
+ return (
+ <RemoteDirectoryBrowser
+ defaultPath={value.trim() || undefined}
+ deviceId={deviceId}
+ error={error}
+ loading={loading}
+ onCancel={close}
+ onSelect={handleSubmit}
+ onManual={(path) => {
+ setValue(path);
+ setError(undefined);
+ setManual(true);
+ }}
+ />
+ );
+ }
return (
<Flexbox gap={16}>
- <Text style={{ marginTop: -8 }} type={'secondary'}>
- {tPlugin('workingDirectory.addFolderDesc')}
- </Text>
- <Flexbox gap={6}>
+ <Text type={'secondary'}>{tPlugin('workingDirectory.addFolderDesc')}</Text>
+ <Flexbox gap={8}>
<Input
+ aria-label={tPlugin('workingDirectory.current')}
+ disabled={loading}
placeholder={placeholder || tPlugin('workingDirectory.placeholder')}
ref={inputRef}
value={value}
- onPressEnter={handleSubmit}
+ onPressEnter={() => handleSubmit(value)}
onChange={(e) => {
setValue(e.target.value);
setError(undefined);
@@ -75,34 +99,41 @@ const AddWorkingDirContent = memo<AddWorkingDirContentProps>(({ onSubmit, placeh
/>
{error ? <Text style={{ color: cssVar.colorError, fontSize: 12 }}>{error}</Text> : null}
</Flexbox>
- <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Flexbox horizontal gap={8} justify={'flex-end'} wrap={'wrap'}>
+ {deviceId && (
+ <Button
+ disabled={loading}
+ onClick={() => {
+ setError(undefined);
+ setManual(false);
+ }}
+ >
+ {tPlugin('workingDirectory.browseFolders')}
+ </Button>
+ )}
<Button disabled={loading} onClick={close}>
{tCommon('cancel')}
</Button>
- <Button loading={loading} type={'primary'} onClick={handleSubmit}>
- {tCommon('confirm')}
+ <Button
+ disabled={!value.trim()}
+ loading={loading}
+ type={'primary'}
+ onClick={() => handleSubmit(value)}
+ >
+ {tPlugin('workingDirectory.useFolder')}
</Button>
</Flexbox>
</Flexbox>
);
-});
+};
-AddWorkingDirContent.displayName = 'AddWorkingDirContent';
-
-/**
- * Manual absolute-path entry for the working directory. Used when the target
- * filesystem isn't browsable from here (web, or a remote device) — the browser
- * has no way to resolve an absolute path from its sandboxed folder picker.
- */
-export const openAddWorkingDirModal = (options: {
- onSubmit: (path: string) => Promise<string | undefined>;
- placeholder?: string;
-}): ModalInstance =>
+/** Browse a connected device, with manual entry available as a fallback. */
+export const openAddWorkingDirModal = (options: AddWorkingDirContentProps): ModalInstance =>
createModal({
- content: <AddWorkingDirContent placeholder={options.placeholder} onSubmit={options.onSubmit} />,
+ content: <AddWorkingDirContent {...options} />,
footer: null,
maskClosable: true,
styles: { header: { borderBottom: 'none' } },
title: t('workingDirectory.addFolderTitle', { ns: 'device' }),
- width: 'min(90vw, 480px)',
+ width: 'min(90vw, 560px)',
});
diff --git a/src/features/WorkingDirectory/RemoteDirectoryBrowser.tsx b/src/features/WorkingDirectory/RemoteDirectoryBrowser.tsx
new file mode 100644
index 00000000000..69d0a014a49
--- /dev/null
+++ b/src/features/WorkingDirectory/RemoteDirectoryBrowser.tsx
@@ -0,0 +1,174 @@
+'use client';
+
+import { Flexbox, Input } from '@lobehub/ui';
+import { ActionIcon, Button, Text } from '@lobehub/ui/base-ui';
+import { cssVar } from 'antd-style';
+import { ArrowUpIcon, FolderIcon, HouseIcon } from 'lucide-react';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import NavItem from '@/features/NavPanel/components/NavItem';
+import { useFetchDeviceDirectory } from '@/store/device/directoryHooks';
+
+interface RemoteDirectoryBrowserProps {
+ defaultPath?: string;
+ deviceId: string;
+ error?: string;
+ loading: boolean;
+ onCancel: () => void;
+ onManual: (path: string) => void;
+ onSelect: (path: string) => void;
+}
+
+export const RemoteDirectoryBrowser = ({
+ defaultPath,
+ deviceId,
+ error: submitError,
+ loading,
+ onCancel,
+ onManual,
+ onSelect,
+}: RemoteDirectoryBrowserProps) => {
+ const { t } = useTranslation('device');
+ const { t: tCommon } = useTranslation('common');
+ const [path, setPath] = useState(defaultPath);
+ const [draft, setDraft] = useState<string>();
+ const { directory, entries, error, hasMore, isLoading, isLoadingMore, loadMore, retry } =
+ useFetchDeviceDirectory(deviceId, path);
+ const displayedPath = draft ?? directory?.path ?? path ?? '';
+
+ const navigate = (nextPath?: string) => {
+ setDraft(undefined);
+ if (nextPath === path) void retry();
+ else setPath(nextPath);
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Text type={'secondary'}>{t('workingDirectory.browseDescription')}</Text>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <ActionIcon
+ aria-label={t('workingDirectory.home')}
+ disabled={loading}
+ icon={HouseIcon}
+ title={t('workingDirectory.home')}
+ onClick={() => navigate()}
+ />
+ <ActionIcon
+ aria-label={t('workingDirectory.parentFolder')}
+ disabled={loading || !directory?.parentPath}
+ icon={ArrowUpIcon}
+ title={t('workingDirectory.parentFolder')}
+ onClick={() => directory?.parentPath && navigate(directory.parentPath)}
+ />
+ <Input
+ aria-label={t('workingDirectory.current')}
+ disabled={loading}
+ placeholder={t('workingDirectory.placeholder')}
+ style={{ flex: 1, minWidth: 0 }}
+ value={displayedPath}
+ onChange={(event) => setDraft(event.target.value)}
+ onPressEnter={() => navigate(displayedPath.trim() || undefined)}
+ />
+ <Button disabled={loading} onClick={() => navigate(displayedPath.trim() || undefined)}>
+ {t('workingDirectory.openPath')}
+ </Button>
+ </Flexbox>
+ {directory && directory.roots.length > 1 && (
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ {directory.roots.map((root) => (
+ <Button disabled={loading} key={root} size={'small'} onClick={() => navigate(root)}>
+ {root}
+ </Button>
+ ))}
+ </Flexbox>
+ )}
+ <Flexbox
+ aria-busy={isLoading}
+ gap={4}
+ key={directory?.path ?? path ?? 'home'}
+ style={{ height: 'min(320px, 40vh)', overflow: 'auto' }}
+ >
+ {isLoading ? (
+ <Flexbox align={'center'} flex={1} gap={8} justify={'center'}>
+ <NeuralNetworkLoading />
+ <Text type={'secondary'}>{t('workingDirectory.foldersLoading')}</Text>
+ </Flexbox>
+ ) : (
+ <>
+ {entries.map((entry) => (
+ <NavItem
+ aria-disabled={loading || !entry.readable}
+ disabled={loading || !entry.readable}
+ flex={'none'}
+ icon={FolderIcon}
+ key={entry.path + entry.name}
+ role={'button'}
+ tabIndex={loading || !entry.readable ? -1 : 0}
+ title={entry.name}
+ titleColor={cssVar.colorText}
+ description={
+ entry.readable ? undefined : (
+ <Text type={'secondary'}>{t('workingDirectory.folderUnreadable')}</Text>
+ )
+ }
+ onClick={() => navigate(entry.path)}
+ onKeyDown={(event) => {
+ if (!loading && entry.readable && (event.key === 'Enter' || event.key === ' ')) {
+ event.preventDefault();
+ navigate(entry.path);
+ }
+ }}
+ />
+ ))}
+ {error ? (
+ <Flexbox align={'center'} gap={8} padding={16} role={'alert'}>
+ <Text style={{ textAlign: 'center', whiteSpace: 'normal' }} type={'secondary'}>
+ {t('workingDirectory.foldersLoadFailed')}
+ </Text>
+ <Button disabled={loading} onClick={() => void retry()}>
+ {tCommon('retry')}
+ </Button>
+ </Flexbox>
+ ) : directory && entries.length === 0 ? (
+ <Flexbox align={'center'} flex={1} justify={'center'}>
+ <Text type={'secondary'}>{t('workingDirectory.foldersEmpty')}</Text>
+ </Flexbox>
+ ) : null}
+ {hasMore && !error && (
+ <Button disabled={loading} loading={isLoadingMore} onClick={() => void loadMore()}>
+ {t('workingDirectory.loadMoreFolders')}
+ </Button>
+ )}
+ </>
+ )}
+ </Flexbox>
+ {submitError && (
+ <Text role={'alert'} type={'danger'}>
+ {submitError}
+ </Text>
+ )}
+ <Flexbox horizontal gap={8} justify={'space-between'} wrap={'wrap'}>
+ <Button disabled={loading} onClick={() => onManual(displayedPath)}>
+ {t('workingDirectory.enterPathManually')}
+ </Button>
+ <Flexbox horizontal gap={8}>
+ <Button disabled={loading} onClick={onCancel}>
+ {tCommon('cancel')}
+ </Button>
+ <Button
+ loading={loading}
+ type={'primary'}
+ disabled={
+ !directory || isLoading || (draft !== undefined && draft.trim() !== directory.path)
+ }
+ onClick={() => directory && onSelect(directory.path)}
+ >
+ {t('workingDirectory.useFolder')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 1ba0f874f98..1f6436dc20e 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -820,6 +820,11 @@ export const knowledgeBaseKeys = {
// ---- device -------------------------------------------------------------
export const deviceKeys = {
+ browseDirectory: def(
+ 'device:browseDirectory',
+ (workspaceId: string | null, deviceId: string, path?: string, cursor?: string) =>
+ ['device:browseDirectory', workspaceId, deviceId, path, cursor] as const,
+ ),
gitAheadBehind: def('device:gitAheadBehind', (deviceId: string, path: string) => [
'device:gitAheadBehind',
deviceId,
diff --git a/src/services/device.ts b/src/services/device.ts
index 066b307a8f6..63900d50c21 100644
--- a/src/services/device.ts
+++ b/src/services/device.ts
@@ -26,6 +26,11 @@ class DeviceService {
return lambdaClient.device.statPath.query({ deviceId, path });
}
+ /** Browse folders on the execution device, including cursor pagination. */
+ browseDirectory(input: Parameters<DeviceClient['browseDirectory']['query']>[0]) {
+ return lambdaClient.device.browseDirectory.query(input);
+ }
+
/** Probe whether an agent platform (openclaw / hermes) is available on a device. */
checkCapability(input: Parameters<DeviceClient['checkCapability']['query']>[0]) {
return lambdaClient.device.checkCapability.query(input);
diff --git a/src/store/device/directoryHooks.test.ts b/src/store/device/directoryHooks.test.ts
new file mode 100644
index 00000000000..f87bf374a17
--- /dev/null
+++ b/src/store/device/directoryHooks.test.ts
@@ -0,0 +1,152 @@
+import type { DeviceDirectoryBrowseResult } from '@lobechat/types';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { deviceService } from '@/services/device';
+
+import { useFetchDeviceDirectory } from './directoryHooks';
+
+const folder = (name: string) => ({
+ isSymlink: false,
+ name,
+ path: `/home/${name}`,
+ readable: true,
+});
+const page = (
+ overrides: Partial<DeviceDirectoryBrowseResult> = {},
+): DeviceDirectoryBrowseResult => ({
+ entries: [folder('projects')],
+ parentPath: '/',
+ path: '/home',
+ pathSeparator: '/',
+ roots: ['/'],
+ truncated: false,
+ ...overrides,
+});
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { provider: () => new Map(), dedupingInterval: 0 } }, children);
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('useFetchDeviceDirectory', () => {
+ it('shows the canonical home directory and appends subsequent pages', async () => {
+ vi.spyOn(deviceService, 'browseDirectory').mockImplementation(async ({ cursor, path }) => {
+ if (!cursor) return page({ nextCursor: '1', truncated: true });
+ return path === '/home' ? page({ entries: [folder('work')] }) : null;
+ });
+ const { result } = renderHook(() => useFetchDeviceDirectory('device'), { wrapper });
+ await waitFor(() => expect(result.current.directory?.path).toBe('/home'));
+ expect(result.current.hasMore).toBe(true);
+ await act(async () => {
+ await result.current.loadMore();
+ });
+ expect(result.current.entries.map(({ name }) => name)).toEqual(['projects', 'work']);
+ expect(result.current.hasMore).toBe(false);
+ });
+
+ it('reports an unavailable device as an error, then recovers on retry', async () => {
+ vi.spyOn(deviceService, 'browseDirectory')
+ .mockResolvedValueOnce(null)
+ .mockResolvedValue(page());
+ const { result } = renderHook(() => useFetchDeviceDirectory('device'), { wrapper });
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.directory).toBeUndefined();
+ expect(result.current.isLoading).toBe(false);
+ await act(async () => {
+ await result.current.retry();
+ });
+ await waitFor(() => expect(result.current.directory?.path).toBe('/home'));
+ expect(result.current.error).toBeUndefined();
+ });
+
+ it('retains loaded folders when pagination fails and retries the missing page', async () => {
+ let fail = true;
+ vi.spyOn(deviceService, 'browseDirectory').mockImplementation(async ({ cursor }) => {
+ if (!cursor) return page({ nextCursor: '1', truncated: true });
+ if (fail) throw new Error('Disconnected');
+ return page({ entries: [folder('work')] });
+ });
+ const { result } = renderHook(() => useFetchDeviceDirectory('device'), { wrapper });
+ await waitFor(() => expect(result.current.hasMore).toBe(true));
+ await act(async () => {
+ await result.current.loadMore();
+ });
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.entries.map(({ name }) => name)).toEqual(['projects']);
+ expect(result.current.isLoadingMore).toBe(false);
+ fail = false;
+ await act(async () => {
+ await result.current.retry();
+ });
+ await waitFor(() => expect(result.current.entries).toHaveLength(2));
+ expect(result.current.error).toBeUndefined();
+ });
+
+ it('does not show the previous directory while a new location loads or fails', async () => {
+ vi.spyOn(deviceService, 'browseDirectory').mockImplementation(async ({ path }) => {
+ if (path === '/missing') throw new Error('Permission denied');
+ return page();
+ });
+ const { result, rerender } = renderHook(({ path }) => useFetchDeviceDirectory('device', path), {
+ initialProps: { path: '/home' },
+ wrapper,
+ });
+ await waitFor(() => expect(result.current.directory?.path).toBe('/home'));
+ rerender({ path: '/missing' });
+ expect(result.current.directory).toBeUndefined();
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.entries).toEqual([]);
+ });
+
+ it('ignores a late response from the previous location', async () => {
+ let resolveOld!: (result: DeviceDirectoryBrowseResult) => void;
+ vi.spyOn(deviceService, 'browseDirectory').mockImplementation(async ({ path }) => {
+ if (path === '/slow')
+ return new Promise((resolve) => {
+ resolveOld = resolve;
+ });
+ return page({ entries: [], parentPath: null, path: '/' });
+ });
+ const { result, rerender } = renderHook(({ path }) => useFetchDeviceDirectory('device', path), {
+ initialProps: { path: '/slow' },
+ wrapper,
+ });
+ await waitFor(() => expect(resolveOld).toBeDefined());
+ rerender({ path: '/' });
+ await waitFor(() => expect(result.current.directory?.path).toBe('/'));
+ await act(async () => {
+ resolveOld(page({ path: '/slow' }));
+ });
+ expect(result.current.directory?.path).toBe('/');
+ expect(result.current.directory?.parentPath).toBeNull();
+ expect(result.current.entries).toEqual([]);
+ });
+
+ it('resets pagination when navigating to another directory', async () => {
+ vi.spyOn(deviceService, 'browseDirectory').mockImplementation(async ({ path, cursor }) => {
+ if (path === '/next')
+ return page({ path: '/next', entries: [folder('next')], nextCursor: '1', truncated: true });
+ return page({
+ entries: [folder(cursor ? 'second' : 'first')],
+ nextCursor: cursor ? undefined : '1',
+ truncated: !cursor,
+ });
+ });
+ const { result, rerender } = renderHook(({ path }) => useFetchDeviceDirectory('device', path), {
+ initialProps: { path: '/home' },
+ wrapper,
+ });
+ await waitFor(() => expect(result.current.directory).toBeDefined());
+ await act(async () => {
+ await result.current.loadMore();
+ });
+ expect(result.current.entries).toHaveLength(2);
+ rerender({ path: '/next' });
+ await waitFor(() => expect(result.current.directory?.path).toBe('/next'));
+ expect(result.current.entries.map(({ name }) => name)).toEqual(['next']);
+ expect(result.current.hasMore).toBe(true);
+ });
+});
diff --git a/src/store/device/directoryHooks.ts b/src/store/device/directoryHooks.ts
new file mode 100644
index 00000000000..934e10d1697
--- /dev/null
+++ b/src/store/device/directoryHooks.ts
@@ -0,0 +1,58 @@
+import type { DeviceDirectoryBrowseResult } from '@lobechat/types';
+import useSWRInfinite from 'swr/infinite';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { deviceKeys } from '@/libs/swr/keys';
+import { deviceService } from '@/services/device';
+
+/** Each device/path has its own page series, so late responses cannot replace a new location. */
+export const useFetchDeviceDirectory = (deviceId: string, path?: string) => {
+ const workspaceId = useActiveWorkspaceId();
+ const { data, error, isLoading, isValidating, mutate, setSize, size } = useSWRInfinite(
+ (_index: number, previous: DeviceDirectoryBrowseResult | null) => {
+ if (previous && !previous.nextCursor) return null;
+ return deviceKeys.browseDirectory(
+ workspaceId,
+ deviceId,
+ previous?.path ?? path,
+ previous?.nextCursor,
+ );
+ },
+ async ([, , targetDeviceId, directoryPath, cursor]: readonly [
+ string,
+ string | null,
+ string,
+ string | undefined,
+ string | undefined,
+ ]) => {
+ const result = await deviceService.browseDirectory({
+ cursor,
+ deviceId: targetDeviceId,
+ path: directoryPath,
+ });
+ // Offline / unsupported RPC is returned as null, never an empty directory.
+ if (!result) throw new Error('Device directory unavailable');
+ return result;
+ },
+ {
+ revalidateFirstPage: false,
+ revalidateOnFocus: false,
+ shouldRetryOnError: false,
+ },
+ );
+
+ const directory = data?.[0];
+ const entries = data?.flatMap((page) => page?.entries ?? []) ?? [];
+ const lastPage = data?.findLast(Boolean);
+
+ return {
+ directory,
+ entries,
+ error,
+ hasMore: !!lastPage?.nextCursor,
+ isLoading,
+ isLoadingMore: !error && (isValidating || (!!directory && !data?.[size - 1])),
+ loadMore: () => setSize(size + 1),
+ retry: () => mutate(),
+ };
+};