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): add a refresh button to the working directory picker (#20884)

AmAzing-fa0b6bb39f21
diff --git a/locales/en-US/device.json b/locales/en-US/device.json
index f38e7d1ead8..b247af73730 100644
--- a/locales/en-US/device.json
+++ b/locales/en-US/device.json
@@ -88,6 +88,7 @@
"workingDirectory.pushNoop": "Everything up-to-date",
"workingDirectory.pushSuccess": "Pushed successfully",
"workingDirectory.recent": "Working directory",
+ "workingDirectory.refreshFolders": "Refresh folders",
"workingDirectory.refreshGitStatus": "Refresh branch & PR status",
"workingDirectory.removeRecent": "Remove from recent",
"workingDirectory.removeWorktreeAction": "Delete worktree",
diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.json
index b26b4c83676..edbb79df247 100644
--- a/locales/zh-CN/device.json
+++ b/locales/zh-CN/device.json
@@ -88,6 +88,7 @@
"workingDirectory.pushNoop": "已是最新",
"workingDirectory.pushSuccess": "推送成功",
"workingDirectory.recent": "工作目录",
+ "workingDirectory.refreshFolders": "刷新文件夹列表",
"workingDirectory.refreshGitStatus": "刷新分支与 PR 状态",
"workingDirectory.removeRecent": "从最近目录中移除",
"workingDirectory.removeWorktreeAction": "删除 Worktree",
diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.ts
index 5324fbcd743..08b0657010f 100644
--- a/packages/locales/src/default/device.ts
+++ b/packages/locales/src/default/device.ts
@@ -24,6 +24,7 @@ export default {
'This device’s app doesn’t support creating folders yet. Update it and try again.',
'workingDirectory.openPath': 'Open',
'workingDirectory.parentFolder': 'Parent folder',
+ 'workingDirectory.refreshFolders': 'Refresh folders',
'workingDirectory.useFolder': 'Use this folder',
'workingDirectory.addFolder': 'Add folder…',
'workingDirectory.addFolderDesc':
diff --git a/src/features/WorkingDirectory/RemoteDirectoryBrowser.tsx b/src/features/WorkingDirectory/RemoteDirectoryBrowser.tsx
index 0920ccb3823..36945d4b29b 100644
--- a/src/features/WorkingDirectory/RemoteDirectoryBrowser.tsx
+++ b/src/features/WorkingDirectory/RemoteDirectoryBrowser.tsx
@@ -3,7 +3,7 @@
import { Flexbox } from '@lobehub/ui';
import { ActionIcon, Button, Input, Spin, Text } from '@lobehub/ui/base-ui';
import { cssVar } from 'antd-style';
-import { ArrowUpIcon, FolderPlusIcon, HouseIcon } from 'lucide-react';
+import { ArrowUpIcon, FolderPlusIcon, HouseIcon, RefreshCwIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import NavItem from '@/features/NavPanel/components/NavItem';
@@ -43,8 +43,18 @@ export const RemoteDirectoryBrowser = ({
navigate: setDirectoryPath,
setCreatingFolder,
} = useDirectoryBrowserState(defaultPath);
- const { directory, entries, error, hasMore, isLoading, isLoadingMore, loadMore, retry } =
- useFetchDeviceDirectory(deviceId, path);
+ const {
+ directory,
+ entries,
+ error,
+ hasMore,
+ isLoading,
+ isLoadingMore,
+ isRefreshing,
+ loadMore,
+ refresh,
+ retry,
+ } = useFetchDeviceDirectory(deviceId, path);
const canUseDirectory = !isLoading && isPathConfirmed(directory?.path);
const displayedPath = draft ?? directory?.path ?? path ?? '';
@@ -79,6 +89,14 @@ export const RemoteDirectoryBrowser = ({
title={t('workingDirectory.newFolder')}
onClick={() => setCreatingFolder(true)}
/>
+ <ActionIcon
+ aria-label={t('workingDirectory.refreshFolders')}
+ disabled={loading || !directory}
+ icon={RefreshCwIcon}
+ loading={isRefreshing}
+ title={t('workingDirectory.refreshFolders')}
+ onClick={() => void refresh()}
+ />
</Flexbox>
<Input
aria-label={t('workingDirectory.current')}
diff --git a/src/store/device/directoryHooks.test.ts b/src/store/device/directoryHooks.test.ts
index cc006bdf61b..f2b1f2870c9 100644
--- a/src/store/device/directoryHooks.test.ts
+++ b/src/store/device/directoryHooks.test.ts
@@ -150,6 +150,68 @@ describe('useFetchDeviceDirectory', () => {
expect(result.current.hasMore).toBe(true);
});
+ it('serves a revisited directory from cache and reloads it on refresh', async () => {
+ const listings: Record<string, DeviceDirectoryBrowseResult> = {
+ '/home': page({ entries: [folder('projects')], path: '/home' }),
+ '/home/projects': page({ entries: [], parentPath: '/home', path: '/home/projects' }),
+ };
+ const browse = vi
+ .spyOn(deviceService, 'browseDirectory')
+ .mockImplementation(async ({ path }) => listings[path ?? '/home']);
+ const homeRequests = () => browse.mock.calls.filter(([input]) => input.path === '/home');
+ const { result, rerender } = renderHook(({ path }) => useFetchDeviceDirectory('device', path), {
+ initialProps: { path: '/home' },
+ wrapper,
+ });
+ await waitFor(() => expect(result.current.directory?.path).toBe('/home'));
+
+ // A folder appears on the device while the picker is elsewhere.
+ listings['/home'] = page({ entries: [folder('ops'), folder('projects')], path: '/home' });
+ rerender({ path: '/home/projects' });
+ await waitFor(() => expect(result.current.directory?.path).toBe('/home/projects'));
+ rerender({ path: '/home' });
+ await waitFor(() => expect(result.current.directory?.path).toBe('/home'));
+ expect(result.current.entries.map(({ name }) => name)).toEqual(['projects']);
+ expect(homeRequests()).toHaveLength(1);
+
+ await act(async () => {
+ await result.current.refresh();
+ });
+ expect(result.current.entries.map(({ name }) => name)).toEqual(['ops', 'projects']);
+ expect(homeRequests()).toHaveLength(2);
+ });
+
+ it('keeps the listing visible and flags it while a refresh is in flight', async () => {
+ let resolveRefresh: ((result: DeviceDirectoryBrowseResult) => void) | undefined;
+ vi.spyOn(deviceService, 'browseDirectory')
+ .mockResolvedValueOnce(page())
+ .mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveRefresh = resolve;
+ }),
+ );
+ const { result } = renderHook(() => useFetchDeviceDirectory('device', '/home'), { wrapper });
+ await waitFor(() => expect(result.current.directory?.path).toBe('/home'));
+ expect(result.current.isRefreshing).toBe(false);
+
+ let refreshed!: Promise<void>;
+ act(() => {
+ refreshed = result.current.refresh();
+ });
+ await waitFor(() => expect(resolveRefresh).toBeDefined());
+ expect(result.current.isRefreshing).toBe(true);
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.entries.map(({ name }) => name)).toEqual(['projects']);
+
+ await act(async () => {
+ resolveRefresh?.(page({ entries: [folder('ops'), folder('projects')] }));
+ await refreshed;
+ });
+ expect(result.current.isRefreshing).toBe(false);
+ expect(result.current.entries.map(({ name }) => name)).toEqual(['ops', 'projects']);
+ });
+
it('reloads the parent after a refresh raced a move into a new child', async () => {
const listings: Record<string, DeviceDirectoryBrowseResult> = {
'/home': page({ entries: [folder('projects')], path: '/home' }),
diff --git a/src/store/device/directoryHooks.ts b/src/store/device/directoryHooks.ts
index 934e10d1697..5f8d2c5085c 100644
--- a/src/store/device/directoryHooks.ts
+++ b/src/store/device/directoryHooks.ts
@@ -1,11 +1,16 @@
import type { DeviceDirectoryBrowseResult } from '@lobechat/types';
+import { useState } from 'react';
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. */
+/**
+ * Each device/path has its own page series, so late responses cannot replace a new location.
+ * Listings stay cached per path for fast revisits, so folders created outside the picker
+ * only show up after `refresh`.
+ */
export const useFetchDeviceDirectory = (deviceId: string, path?: string) => {
const workspaceId = useActiveWorkspaceId();
const { data, error, isLoading, isValidating, mutate, setSize, size } = useSWRInfinite(
@@ -45,6 +50,18 @@ export const useFetchDeviceDirectory = (deviceId: string, path?: string) => {
const entries = data?.flatMap((page) => page?.entries ?? []) ?? [];
const lastPage = data?.findLast(Boolean);
+ const [refreshingPath, setRefreshingPath] = useState<string>();
+ const refresh = async () => {
+ if (!directory) return;
+ const target = directory.path;
+ setRefreshingPath(target);
+ try {
+ await mutate();
+ } finally {
+ setRefreshingPath((current) => (current === target ? undefined : current));
+ }
+ };
+
return {
directory,
entries,
@@ -52,7 +69,9 @@ export const useFetchDeviceDirectory = (deviceId: string, path?: string) => {
hasMore: !!lastPage?.nextCursor,
isLoading,
isLoadingMore: !error && (isValidating || (!!directory && !data?.[size - 1])),
+ isRefreshing: !!directory && refreshingPath === directory.path,
loadMore: () => setSize(size + 1),
+ refresh,
retry: () => mutate(),
};
};