🤯 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
🐛 fix(working-directory): wake a sleeping cloud device in the folder picker (#22969)
YuTengjing9f4282d8a3ff
diff --git a/locales/en-US/device.json b/locales/en-US/device.jsonindex d21471e70bf..5ba8219e752 100644--- a/locales/en-US/device.json+++ b/locales/en-US/device.json@@ -40,6 +40,9 @@"workingDirectory.detachedHead": "Detached HEAD at {{sha}}","workingDirectory.detachedHeadShort": "detached@{{sha}}","workingDirectory.detachedWorktree": "detached",+ "workingDirectory.deviceWakeFailed": "Could not wake this cloud device. Try again.",+ "workingDirectory.deviceWakeSlow": "The cloud device is still starting. Try again in a moment.",+ "workingDirectory.deviceWaking": "Waking the cloud device… This can take up to two minutes.","workingDirectory.diffLineStatTooltip": "Added lines {{added}} · Deleted lines {{deleted}} · Changed files {{files}}","workingDirectory.diffStatTooltip": "Added {{added}} · Modified {{modified}} · Deleted {{deleted}}","workingDirectory.drive.actionFailed": "That didn’t work. Try again.",diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.jsonindex b99dc1b60f5..dc900b54ee8 100644--- a/locales/zh-CN/device.json+++ b/locales/zh-CN/device.json@@ -40,6 +40,9 @@"workingDirectory.detachedHead": "游离 HEAD,当前提交 {{sha}}","workingDirectory.detachedHeadShort": "detached@{{sha}}","workingDirectory.detachedWorktree": "detached",+ "workingDirectory.deviceWakeFailed": "无法唤醒该云端设备,请重试。",+ "workingDirectory.deviceWakeSlow": "云端设备仍在启动,请稍后重试。",+ "workingDirectory.deviceWaking": "正在唤醒云端设备,最多需要 2 分钟…","workingDirectory.diffLineStatTooltip": "新增行 {{added}} · 删除行 {{deleted}} · 变更文件 {{files}}","workingDirectory.diffStatTooltip": "新增 {{added}} · 修改 {{modified}} · 删除 {{deleted}}","workingDirectory.drive.actionFailed": "操作失败,请重试。",diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.tsindex 47e91e1d098..639e675d47c 100644--- a/packages/locales/src/default/device.ts+++ b/packages/locales/src/default/device.ts@@ -14,6 +14,9 @@ export default {'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.deviceWaking': 'Waking the cloud device… This can take up to two minutes.',+ 'workingDirectory.deviceWakeFailed': 'Could not wake this cloud device. Try again.',+ 'workingDirectory.deviceWakeSlow': 'The cloud device is still starting. Try again in a moment.','workingDirectory.home': 'Home folder','workingDirectory.loadMoreFolders': 'Load more folders','workingDirectory.newFolder': 'New folder',diff --git a/src/features/ChatInput/ControlBar/__tests__/reconnectDevice.test.ts b/src/features/ChatInput/ControlBar/__tests__/reconnectDevice.test.tsindex cbdb06107c7..2e7dfbeb6c3 100644--- a/src/features/ChatInput/ControlBar/__tests__/reconnectDevice.test.ts+++ b/src/features/ChatInput/ControlBar/__tests__/reconnectDevice.test.ts@@ -1,7 +1,11 @@import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';import { describe, expect, it, vi } from 'vitest';-import { MANAGED_DEVICE_WAKE_POLL, reconnectDevice } from '../reconnectDevice';+import {+ MANAGED_DEVICE_WAKE_POLL,+ reconnectDevice,+ wakeManagedDeviceAndWait,+} from '../reconnectDevice';const managed = {deviceId: 'managed-a',@@ -115,3 +119,20 @@ describe('reconnectDevice', () => {await expect(reconnectDevice(desktop, { isCurrentMachine: false }, d)).resolves.toBe('failed');});});++describe('wakeManagedDeviceAndWait', () => {+ it('stops polling once the surface that asked is gone', async () => {+ const d = deps(Number.POSITIVE_INFINITY);+ let polls = 0;+ const shouldStop = () => polls >= 2;+ const refreshDevices = d.refreshDevices as unknown as ReturnType<typeof vi.fn>;+ refreshDevices.mockImplementation(async () => {+ polls += 1;+ return [];+ });++ await expect(wakeManagedDeviceAndWait(managed, { ...d, shouldStop })).resolves.toBe('starting');+ expect(d.wakeManagedDevice).toHaveBeenCalledTimes(1);+ expect(refreshDevices).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/features/ChatInput/ControlBar/reconnectDevice.ts b/src/features/ChatInput/ControlBar/reconnectDevice.tsindex b30ae79d817..b1c318fea0e 100644--- a/src/features/ChatInput/ControlBar/reconnectDevice.ts+++ b/src/features/ChatInput/ControlBar/reconnectDevice.ts@@ -30,6 +30,59 @@ export const MANAGED_DEVICE_WAKE_POLL = { attempts: 40, intervalMs: 3000 };const defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));+/**+ * Poll the device list until `deviceId` is online. A failed refresh counts as+ * one poll in which the device is not online yet. Resolves `true` once it is+ * online, `false` when the attempts run out or `shouldStop` answers true.+ */+const pollDeviceOnline = async (+ deviceId: string,+ poll: { attempts: number; intervalMs: number },+ {+ refreshDevices,+ shouldStop,+ sleep,+ }: Pick<ReconnectDeviceDeps, 'refreshDevices'> & {+ shouldStop?: () => boolean;+ sleep: (ms: number) => Promise<void>;+ },+): Promise<boolean> => {+ for (let attempt = 0; attempt < poll.attempts; attempt += 1) {+ if (shouldStop?.()) return false;+ let nextDevices: DeviceListItem[] | undefined;+ try {+ nextDevices = await refreshDevices();+ } catch (error) {+ console.warn('Device list refresh failed while waiting for a device:', error);+ }+ if (nextDevices?.some((item) => item.deviceId === deviceId && item.online)) return true;+ await sleep(poll.intervalMs);+ }+ return false;+};++/**+ * Wake a managed cloud device through the server, then poll the device list+ * until it is online (`connected`) or the wait runs out (`starting`). A+ * surface that needs the device, such as the folder picker, calls this+ * without the user pressing "Wake now". A failed wake request throws.+ * `shouldStop` lets a closed surface stop polling; it then ends as `starting`.+ */+export const wakeManagedDeviceAndWait = async (+ device: Pick<DeviceListItem, 'deviceId' | 'scope'>,+ deps: Pick<ReconnectDeviceDeps, 'refreshDevices' | 'sleep' | 'wakeManagedDevice'> & {+ shouldStop?: () => boolean;+ },+): Promise<Extract<ReconnectOutcome, 'connected' | 'starting'>> => {+ await deps.wakeManagedDevice({ deviceId: device.deviceId, scope: device.scope });+ const online = await pollDeviceOnline(device.deviceId, MANAGED_DEVICE_WAKE_POLL, {+ refreshDevices: deps.refreshDevices,+ shouldStop: deps.shouldStop,+ sleep: deps.sleep ?? defaultSleep,+ });+ return online ? 'connected' : 'starting';+};+/*** Bring a device back online from the device picker, then poll the device* list until it is online. The list refresh also refreshes a managed@@ -51,28 +104,17 @@ export const reconnectDevice = async (deps: ReconnectDeviceDeps,): Promise<ReconnectOutcome> => {const { deviceId } = device;- const managed = isManagedCloudDevice(device);- const sleep = deps.sleep ?? defaultSleep;+ if (isManagedCloudDevice(device)) return wakeManagedDeviceAndWait(device, deps);- if (managed) {- await deps.wakeManagedDevice({ deviceId, scope: device.scope });- } else if (isCurrentMachine) {+ if (isCurrentMachine) {await deps.connectGateway();} else {deps.openDeepLink(`lobehub://device/reconnect?deviceId=${encodeURIComponent(deviceId)}`);}- const poll = managed ? MANAGED_DEVICE_WAKE_POLL : DEVICE_RECONNECT_POLL;- for (let attempt = 0; attempt < poll.attempts; attempt += 1) {- let nextDevices: DeviceListItem[] | undefined;- try {- nextDevices = await deps.refreshDevices();- } catch (error) {- console.warn('Device list refresh failed while waiting for a device:', error);- }- if (nextDevices?.some((item) => item.deviceId === deviceId && item.online)) return 'connected';- await sleep(poll.intervalMs);- }-- return managed ? 'starting' : 'failed';+ const online = await pollDeviceOnline(deviceId, DEVICE_RECONNECT_POLL, {+ refreshDevices: deps.refreshDevices,+ sleep: deps.sleep ?? defaultSleep,+ });+ return online ? 'connected' : 'failed';};diff --git a/src/features/WorkingDirectory/DirectoryBrowser.tsx b/src/features/WorkingDirectory/DirectoryBrowser.tsxindex 3797a779153..a1328219331 100644--- a/src/features/WorkingDirectory/DirectoryBrowser.tsx+++ b/src/features/WorkingDirectory/DirectoryBrowser.tsx@@ -98,11 +98,13 @@ export const DirectoryBrowser = ({directory,entries,error,+ errorLabel,hasMore,isLoading,isLoadingMore,isRefreshing,loadMore,+ loadingLabel,notice,refresh,retry,@@ -198,7 +200,7 @@ export const DirectoryBrowser = ({{isLoading ? (<Flexbox align={'center'} flex={1} gap={8} justify={'center'}><Spin size="small" />- <Text type={'secondary'}>{t('workingDirectory.foldersLoading')}</Text>+ <Text type={'secondary'}>{loadingLabel ?? t('workingDirectory.foldersLoading')}</Text></Flexbox>) : (<>@@ -247,7 +249,7 @@ export const DirectoryBrowser = ({{error ? (<Flexbox align={'center'} gap={8} padding={16} role={'alert'}><Text style={{ textAlign: 'center', whiteSpace: 'normal' }} type={'secondary'}>- {t(source.listErrorKey ?? 'workingDirectory.foldersLoadFailed')}+ {errorLabel ?? t(source.listErrorKey ?? 'workingDirectory.foldersLoadFailed')}</Text><Button disabled={loading} onClick={() => void retry()}>{tCommon('retry')}diff --git a/src/features/WorkingDirectory/directorySource.ts b/src/features/WorkingDirectory/directorySource.tsindex 2c2ce29f2b5..3dee48cf94d 100644--- a/src/features/WorkingDirectory/directorySource.ts+++ b/src/features/WorkingDirectory/directorySource.ts@@ -25,10 +25,14 @@ export interface DirectoryListing {directory?: { parentPath?: string | null; path: string; roots?: string[] };entries: DirectoryEntry[];error?: unknown;+ /** In place of the generic failure text, when the source knows why it failed. */+ errorLabel?: string;hasMore: boolean;isLoading: boolean;isLoadingMore: boolean;isRefreshing: boolean;+ /** In place of the generic loading text, e.g. while a cloud device wakes. */+ loadingLabel?: string;loadMore: () => void;/** Above the entries: something about this folder worth saying before its contents. */notice?: ReactNode;diff --git a/src/features/WorkingDirectory/sources/useDeviceDirectorySource.test.tsx b/src/features/WorkingDirectory/sources/useDeviceDirectorySource.test.tsxnew file mode 100644index 00000000000..6d405a73037--- /dev/null+++ b/src/features/WorkingDirectory/sources/useDeviceDirectorySource.test.tsx@@ -0,0 +1,143 @@+import { MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE } from '@lobechat/types';+import { act, renderHook, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { SWRConfig } from 'swr';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { create } from 'zustand';++import { deviceService } from '@/services/device';++import { useDeviceDirectorySource } from './useDeviceDirectorySource';++interface Row {+ deviceId: string;+ identitySource?: string;+ online: boolean;+ scope: 'personal' | 'workspace';+}++const sleepingCloud: Row = {+ deviceId: 'cloud-1',+ identitySource: MANAGED_CLOUD_DEVICE_IDENTITY_SOURCE,+ online: false,+ scope: 'personal',+};++/** The device list as the server reports it; `refresh` is what the next poll returns. */+const deviceList = create<{ devices: Row[]; refresh: () => Row[] }>(() => ({+ devices: [],+ refresh: () => [],+}));++/** Stable like the real store action, so it does not restart the wake effect. */+const refreshDevices = async () => {+ const next = deviceList.getState().refresh();+ deviceList.setState({ devices: next });+ return next;+};++vi.mock('@/store/device/useDeviceList', () => ({+ useDeviceList: () => ({+ data: deviceList((s) => s.devices),+ error: undefined,+ isConfirmed: true,+ isLoading: false,+ isValidating: false,+ mutate: refreshDevices,+ }),+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => undefined,+}));++vi.mock('@/services/device', () => ({+ deviceService: { browseDirectory: vi.fn(), createDirectory: vi.fn(), wakeManagedDevice: vi.fn() },+}));++const wrapper = ({ children }: { children: ReactNode }) => (+ <SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>{children}</SWRConfig>+);++const renderListing = (deviceId: string) =>+ renderHook(() => useDeviceDirectorySource(deviceId).useListing(), { wrapper });++describe('useDeviceDirectorySource', () => {+ beforeEach(() => {+ vi.mocked(deviceService.browseDirectory)+ .mockReset()+ .mockResolvedValue({+ entries: [{ name: 'src', path: '/home/agent/src', readable: true }],+ path: '/home/agent',+ } as any);+ vi.mocked(deviceService.wakeManagedDevice)+ .mockReset()+ .mockResolvedValue({} as any);+ });++ it('wakes a sleeping cloud device before it lists, and lists once it is online', async () => {+ deviceList.setState({+ devices: [sleepingCloud],+ refresh: () => [{ ...sleepingCloud, online: true }],+ });++ const { result } = renderListing('cloud-1');++ await waitFor(() => expect(result.current.entries).toHaveLength(1));+ expect(deviceService.wakeManagedDevice).toHaveBeenCalledWith({+ deviceId: 'cloud-1',+ scope: 'personal',+ });+ // Listed only after the wake: a listing sent to the sleeping device answers "unavailable".+ expect(vi.mocked(deviceService.wakeManagedDevice).mock.invocationCallOrder[0]).toBeLessThan(+ vi.mocked(deviceService.browseDirectory).mock.invocationCallOrder[0],+ );+ });++ it('says it is waking the device while the device starts', async () => {+ // Never answers, so the device stays asleep for the whole test.+ vi.mocked(deviceService.wakeManagedDevice).mockReturnValue(new Promise(() => {}));+ deviceList.setState({ devices: [sleepingCloud], refresh: () => [sleepingCloud] });++ const { result } = renderListing('cloud-1');++ await waitFor(() => expect(deviceService.wakeManagedDevice).toHaveBeenCalled());+ expect(result.current.isLoading).toBe(true);+ expect(result.current.loadingLabel).toBe('workingDirectory.deviceWaking');+ expect(deviceService.browseDirectory).not.toHaveBeenCalled();+ });++ it('reports a failed wake, and wakes again on retry', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(deviceService.wakeManagedDevice).mockRejectedValueOnce(new Error('refused'));+ deviceList.setState({+ devices: [sleepingCloud],+ refresh: () => [{ ...sleepingCloud, online: true }],+ });++ const { result } = renderListing('cloud-1');++ await waitFor(() =>+ expect(result.current.errorLabel).toBe('workingDirectory.deviceWakeFailed'),+ );+ expect(deviceService.browseDirectory).not.toHaveBeenCalled();++ act(() => result.current.retry());++ await waitFor(() => expect(result.current.entries).toHaveLength(1));+ expect(deviceService.wakeManagedDevice).toHaveBeenCalledTimes(2);+ });++ it('lists an ordinary device without waking it', async () => {+ deviceList.setState({+ devices: [+ { deviceId: 'mac-1', identitySource: 'machine-id', online: true, scope: 'personal' },+ ],+ });++ const { result } = renderListing('mac-1');++ await waitFor(() => expect(result.current.entries).toHaveLength(1));+ expect(deviceService.wakeManagedDevice).not.toHaveBeenCalled();+ });+});diff --git a/src/features/WorkingDirectory/sources/useDeviceDirectorySource.tsx b/src/features/WorkingDirectory/sources/useDeviceDirectorySource.tsxindex 40cb325d77b..6bee5184a99 100644--- a/src/features/WorkingDirectory/sources/useDeviceDirectorySource.tsx+++ b/src/features/WorkingDirectory/sources/useDeviceDirectorySource.tsx@@ -6,20 +6,46 @@ import { deviceService } from '@/services/device';import { useFetchDeviceDirectory } from '@/store/device/directoryHooks';import type { DirectoryListing, DirectorySource } from '../directorySource';+import { useManagedDeviceWake } from './useManagedDeviceWake';/*** A connected device's folders, through the device gateway's directory RPCs.* Any readable folder may be picked, and a path may be typed in by hand.+ *+ * A sleeping managed cloud device is woken first, and the listing waits for it:+ * without that it answers "unavailable" until the user wakes it elsewhere.*/-export const useDeviceDirectorySource = (deviceId: string): DirectorySource =>- useMemo(+export const useDeviceDirectorySource = (deviceId: string): DirectorySource => {+ const { retry: retryWake, status: wakeStatus } = useManagedDeviceWake(deviceId);++ return useMemo(() => ({createFolder: (parentPath, name) =>deviceService.createDirectory({ deviceId, name, parentPath }),editablePath: true,useListing: (path?: string): DirectoryListing => {const { t } = useTranslation('device');- const listing = useFetchDeviceDirectory(deviceId, path);+ const ready = wakeStatus === 'ready';+ const listing = useFetchDeviceDirectory(deviceId, path, ready);++ if (!ready) {+ const wakeEnded = wakeStatus === 'failed' || wakeStatus === 'starting';+ return {+ ...listing,+ entries: [],+ error: wakeEnded ? new Error(`Managed device wake ${wakeStatus}`) : undefined,+ errorLabel: wakeEnded+ ? t(+ wakeStatus === 'failed'+ ? 'workingDirectory.deviceWakeFailed'+ : 'workingDirectory.deviceWakeSlow',+ )+ : undefined,+ isLoading: !wakeEnded,+ loadingLabel: wakeStatus === 'waking' ? t('workingDirectory.deviceWaking') : undefined,+ retry: retryWake,+ };+ }return {...listing,@@ -34,5 +60,6 @@ export const useDeviceDirectorySource = (deviceId: string): DirectorySource =>};},}),- [deviceId],+ [deviceId, retryWake, wakeStatus],);+};diff --git a/src/features/WorkingDirectory/sources/useManagedDeviceWake.ts b/src/features/WorkingDirectory/sources/useManagedDeviceWake.tsnew file mode 100644index 00000000000..8bd2b2e69a5--- /dev/null+++ b/src/features/WorkingDirectory/sources/useManagedDeviceWake.ts@@ -0,0 +1,84 @@+import { isWakeableManagedDevice } from '@lobechat/types';+import { useCallback, useEffect, useState } from 'react';++import { wakeManagedDeviceAndWait } from '@/features/ChatInput/ControlBar/reconnectDevice';+import { deviceService } from '@/services/device';+import { useDeviceList } from '@/store/device/useDeviceList';++/**+ * Whether a device's folders can be listed yet:+ * - `checking`: the device list has not confirmed the device's presence yet.+ * - `waking`: a sleeping managed cloud device was asked to start; waiting for it.+ * - `starting`: it accepted the wake but is still not online after the wait.+ * - `failed`: the wake request failed.+ * - `ready`: list the folders. Also the answer for any device this hook cannot+ * wake (an ordinary connected device, an unknown id, a failed device list),+ * which keeps the listing's own offline error.+ */+export type DeviceWakeStatus = 'checking' | 'failed' | 'ready' | 'starting' | 'waking';++export interface ManagedDeviceWake {+ /** Ask the device to start again after `starting` or `failed`. */+ retry: () => void;+ status: DeviceWakeStatus;+}++/**+ * Wake a sleeping managed cloud device as soon as a surface needs it, without+ * the user pressing "Wake now" in the device picker first. A listing for such+ * a device answers "unavailable" until it is online, so the folder picker waits+ * on this before it lists.+ */+export const useManagedDeviceWake = (deviceId: string): ManagedDeviceWake => {+ const { data: devices, error, isConfirmed, mutate } = useDeviceList();+ const device = devices?.find((item) => item.deviceId === deviceId);+ // Only a server-confirmed row says the device is asleep: a persisted row+ // reads offline until then.+ const wakeable = isConfirmed && !!device && isWakeableManagedDevice(device);+ const scope = device?.scope;++ const [attempt, setAttempt] = useState(0);+ const [outcome, setOutcome] = useState<{+ attempt: number;+ deviceId: string;+ status: 'failed' | 'starting';+ }>();++ useEffect(() => {+ if (!wakeable || !scope) return;+ let stopped = false;++ wakeManagedDeviceAndWait(+ { deviceId, scope },+ {+ refreshDevices: mutate,+ shouldStop: () => stopped,+ wakeManagedDevice: (input) => deviceService.wakeManagedDevice(input),+ },+ )+ .then((result) => {+ // `connected` needs no state: the refreshed list shows the device online.+ if (!stopped && result === 'starting')+ setOutcome({ attempt, deviceId, status: 'starting' });+ })+ .catch((cause) => {+ console.error('Failed to wake the managed device for folder browsing', cause);+ if (!stopped) setOutcome({ attempt, deviceId, status: 'failed' });+ });++ return () => {+ stopped = true;+ };+ }, [attempt, deviceId, mutate, scope, wakeable]);++ const retry = useCallback(() => setAttempt((value) => value + 1), []);++ if (wakeable) {+ const settled = outcome?.attempt === attempt && outcome.deviceId === deviceId;+ return { retry, status: settled ? outcome.status : 'waking' };+ }+ // A persisted row that may still be a sleeping device: wait for the server.+ if (!isConfirmed && !error && !device?.online) return { retry, status: 'checking' };++ return { retry, status: 'ready' };+};diff --git a/src/store/device/directoryHooks.ts b/src/store/device/directoryHooks.tsindex 5f8d2c5085c..d105e6b4cbc 100644--- a/src/store/device/directoryHooks.ts+++ b/src/store/device/directoryHooks.ts@@ -9,12 +9,14 @@ import { deviceService } from '@/services/device';/*** 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`.+ * only show up after `refresh`. `enabled: false` holds the request, e.g. until a+ * sleeping cloud device is online.*/-export const useFetchDeviceDirectory = (deviceId: string, path?: string) => {+export const useFetchDeviceDirectory = (deviceId: string, path?: string, enabled = true) => {const workspaceId = useActiveWorkspaceId();const { data, error, isLoading, isValidating, mutate, setSize, size } = useSWRInfinite((_index: number, previous: DeviceDirectoryBrowseResult | null) => {+ if (!enabled) return null;if (previous && !previous.nextCursor) return null;return deviceKeys.browseDirectory(workspaceId,