🤯 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
⚡️ perf(device): persist the device list in a replica so the device name and cwd resolve on first paint (#20838)
Arvin Xu2f00975f919d
diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex 00cbf776069..a8715acdbbf 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -388,6 +388,13 @@ export interface DeviceListItem {*/metadata?: Record<string, string> | null;online: boolean;+ /**+ * Client-only: the row was hydrated from the persisted device-list snapshot+ * and has not been confirmed by a fresh `listDevices` yet. `online` is+ * `false` and `channels` empty on such rows — presence is unknown, not+ * offline. Never sent by the server.+ */+ onlineUnknown?: boolean;platform: string | null;registered: boolean;/** Personal (own) vs. workspace-enrolled device — drives picker grouping. */diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex ca13f3760ee..2b7f54719a5 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -46,6 +46,7 @@ import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { localFileService } from '@/services/electron/localFileService';import { useAgentStore } from '@/store/agent';+import { deviceSelectors, useDeviceStore } from '@/store/device';import { useElectronStore } from '@/store/electron';import { useTopicId } from '../hooks/useTopicId';@@ -296,6 +297,10 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {// dimension, so the picker kept showing the previous workspace's pool after// a switch.const { data: devices, isLoading, mutate: refreshDevices } = useDeviceList();+ // Until `useDeviceList` answers, name the bound device from the device store,+ // whose replica paints the persisted device list first — otherwise the chip+ // reads "Unknown device" on every reload.+ const storedBoundDevice = useDeviceStore(deviceSelectors.getDeviceById(boundDeviceId));// The current machine's own gateway deviceId (desktop only), used to badge the// matching device row with a "This device" tag and show the local-process@@ -471,7 +476,8 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {const boundDevice =canShowExecutionTargetSelector && executionTarget === 'device'- ? devices?.find((d) => d.deviceId === boundDeviceId)+ ? (devices?.find((d) => d.deviceId === boundDeviceId) ??+ (devices ? undefined : storedBoundDevice)): undefined;// The picker splits by whether the caller is inside a workspace agent:diff --git a/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsxindex 691672854f8..a9b58f0a67d 100644--- a/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx+++ b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx@@ -47,7 +47,7 @@ import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';-import { useDeviceStore } from '@/store/device';+import { deviceSelectors, useDeviceStore } from '@/store/device';import { useElectronStore } from '@/store/electron';import { useUserStore } from '@/store/user';import { authSelectors } from '@/store/user/selectors';@@ -202,9 +202,8 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>({ topicId },);const isLogin = useUserStore(authSelectors.isLogin);- const { isLoading: isDeviceListLoading } = useDeviceStore((s) => s.useFetchDevices)(- isLogin || isDesktop,- );+ useDeviceStore((s) => s.useFetchDevices)(isLogin || isDesktop);+ const isDeviceListLoading = !useDeviceStore(deviceSelectors.isDeviceListLoaded);const cwd = useEffectiveWorkingDirectory(agentId, { topicId });const provider = agencyConfig?.heterogeneousProvider;useElectronStore((s) => s.useFetchGatewayDeviceInfo)();diff --git a/src/features/ChatInput/ControlBar/useMigrateDeviceRecents.ts b/src/features/ChatInput/ControlBar/useMigrateDeviceRecents.tsindex 8c43e0b575e..3206dfca44c 100644--- a/src/features/ChatInput/ControlBar/useMigrateDeviceRecents.ts+++ b/src/features/ChatInput/ControlBar/useMigrateDeviceRecents.ts@@ -1,7 +1,7 @@import { isDesktop } from '@lobechat/const';import { useEffect } from 'react';-import { useDeviceStore } from '@/store/device';+import { deviceSelectors, useDeviceStore } from '@/store/device';import { useElectronStore } from '@/store/electron';import { getRecentDirs, RECENT_DIRS_KEY } from './recentDirs';@@ -21,11 +21,12 @@ let migrationStarted = false;*/export const useMigrateDeviceRecents = (): void => {const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);- const isDevicesInit = useDeviceStore((s) => s.isDevicesInit);+ // A persisted list holds stale `workingDirs`; merge only into a confirmed one.+ const isDeviceListConfirmed = useDeviceStore(deviceSelectors.isDeviceListConfirmed);const migrate = useDeviceStore((s) => s.migrateLocalRecentsToDevice);useEffect(() => {- if (migrationStarted || !isDesktop || !currentDeviceId || !isDevicesInit) return;+ if (migrationStarted || !isDesktop || !currentDeviceId || !isDeviceListConfirmed) return;const legacy = getRecentDirs();migrationStarted = true;@@ -36,5 +37,5 @@ export const useMigrateDeviceRecents = (): void => {.catch(() => {// Persist failed — keep localStorage so the next reload retries.});- }, [currentDeviceId, isDevicesInit, migrate]);+ }, [currentDeviceId, isDeviceListConfirmed, migrate]);};diff --git a/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx b/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsxindex 2070b16cbed..07c52eb492e 100644--- a/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx+++ b/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx@@ -14,7 +14,7 @@ import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';import { deviceService } from '@/services/device';-import { useDeviceStore } from '@/store/device';+import { deviceSelectors, useDeviceStore } from '@/store/device';import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';function AddDirectoryContent({@@ -26,7 +26,7 @@ function AddDirectoryContent({}) {const { t } = useTranslation('project');const deviceRequest = useDeviceStore((s) => s.useFetchDevices)(true);- const devices = useDeviceStore((s) => s.devices);+ const devices = useDeviceStore(deviceSelectors.deviceList);const environmentsRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);const environments = useProjectEnvironments(projectId);const [environmentId, setEnvironment] = useState(initialEnvironmentId ?? '');@@ -106,7 +106,9 @@ function AddDirectoryContent({{deviceRequest.error || environmentsRequest.error ? (<AsyncErrorerror={deviceRequest.error || environmentsRequest.error}- onRetry={() => Promise.all([deviceRequest.mutate(), environmentsRequest.revalidate()])}+ onRetry={() =>+ Promise.all([deviceRequest.revalidate(), environmentsRequest.revalidate()])+ }/>) : null}<Flexbox horizontal gap={8} justify="flex-end">diff --git a/src/features/Projects/WorkingDirectories/BindDirectoryModal.tsx b/src/features/Projects/WorkingDirectories/BindDirectoryModal.tsxindex aba2fa6a251..2cfc4c55422 100644--- a/src/features/Projects/WorkingDirectories/BindDirectoryModal.tsx+++ b/src/features/Projects/WorkingDirectories/BindDirectoryModal.tsx@@ -17,7 +17,7 @@ import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';-import { useDeviceStore } from '@/store/device';+import { deviceSelectors, useDeviceStore } from '@/store/device';import { useCurrentProjectList, useProjectStore } from '@/store/project';import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';@@ -45,7 +45,7 @@ function BindDirectoryContent(options: BindDirectoryOptions) {const projectSync = useProjectStore((s) => s.useFetchProjectList)();const projects = useCurrentProjectList();useDeviceStore((s) => s.useFetchDevices)(true);- const devices = useDeviceStore((s) => s.devices);+ const devices = useDeviceStore(deviceSelectors.deviceList);const device = devices.find((d) => d.deviceId === options.deviceId);const deviceName = device?.friendlyName ?? options.deviceId;const environmentsRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)();diff --git a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsxindex 06878c8ff11..32d19696955 100644--- a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx+++ b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx@@ -1,3 +1,4 @@+import type { DeviceListItem } from '@lobechat/types';import { Block, Button, cssVar, Flexbox, Icon, Select, Text } from '@lobehub/ui';import { FolderIcon, MessageSquarePlusIcon, PlusIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -6,7 +7,7 @@ import { useSearchParams } from 'react-router';import AsyncError from '@/components/AsyncError';import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useDeviceStore } from '@/store/device';+import { deviceSelectors, useDeviceStore } from '@/store/device';import { useCurrentProjectDetail, useProjectStore } from '@/store/project';import {useProjectDirectories,@@ -18,6 +19,20 @@ import { openAddDirectoryModal } from './AddDirectoryModal';import { openBindDirectoryModal } from './BindDirectoryModal';import { openProjectTopicModal } from './StartDirectoryModal';+/**+ * A device row restored from the persisted list (`onlineUnknown`) has not been+ * confirmed yet, so its presence is left unsaid until `listDevices` answers.+ */+const DevicePresence = ({ device }: { device?: DeviceListItem }) => {+ const { t } = useTranslation('project');+ if (device?.onlineUnknown) return null;+ return (+ <Text fontSize={12} type="secondary">+ {t(device?.online ? 'settings.deviceOnline' : 'settings.deviceOffline')}+ </Text>+ );+};+export function WorkingDirectorySettings({ projectId }: { projectId: string }) {const { t } = useTranslation('project');const navigate = useWorkspaceAwareNavigate();@@ -30,7 +45,8 @@ export function WorkingDirectorySettings({ projectId }: { projectId: string }) {const environments = useProjectEnvironments(projectId);const directories = useProjectDirectories(projectId);const deviceRequest = useDeviceStore((s) => s.useFetchDevices)(true);- const devices = useDeviceStore((s) => s.devices);+ const devices = useDeviceStore(deviceSelectors.deviceList);+ const isDeviceListLoaded = useDeviceStore(deviceSelectors.isDeviceListLoaded);const items = directories.filter((d) => !environmentId || d.environmentId === environmentId);const error = environmentsRequest.error || directoriesRequest.error || deviceRequest.error;return (@@ -70,14 +86,14 @@ export function WorkingDirectorySettings({ projectId }: { projectId: string }) {Promise.all([environmentsRequest.revalidate(),directoriesRequest.revalidate(),- deviceRequest.mutate(),+ deviceRequest.revalidate(),])}/>) : null}{error ? null : !directoriesRequest.hasData ||!environmentsRequest.hasData ||- deviceRequest.isLoading ? (+ !isDeviceListLoaded ? (<Text>{t('loading', { ns: 'common' })}</Text>) : !items.length ? (<Flexbox gap={12} paddingBlock={24}>@@ -113,13 +129,9 @@ export function WorkingDirectorySettings({ projectId }: { projectId: string }) {14,)}<Text fontSize={12}>{directory.deviceName || directory.deviceId}</Text>- <Text fontSize={12} type="secondary">- {t(- devices.find((d) => d.deviceId === directory.deviceId)?.online- ? 'settings.deviceOnline'- : 'settings.deviceOffline',- )}- </Text>+ <DevicePresence+ device={devices.find((d) => d.deviceId === directory.deviceId)}+ /><Text fontSize={12} type="secondary">· {directory.environmentName || t('directories.noEnvironment')}</Text>diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex dfaab4845d6..725ff0876bb 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -582,7 +582,6 @@ export const deviceKeys = {baseRef,],),- listDevices: def('device:listDevices', () => ['device:listDevices']),repoType: def('device:repoType', (path: string) => ['device:repoType', path]),};diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts b/src/routes/(main)/agent/(chat)/topicListLoader.test.tsindex babfd91d3ba..ff1da0837b7 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.test.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.test.ts@@ -13,6 +13,7 @@ const getSidebarTopicListParamsMock = vi.hoisted(() => vi.fn());const preHydrateMessagesMock = vi.hoisted(() => vi.fn(async () => true));const builtinAgentIdMap = vi.hoisted(() => ({ inbox: 'agt_inbox' }) as Record<string, string>);const preHydrateBuiltinAgentMock = vi.hoisted(() => vi.fn(async () => true));+const preHydrateDeviceListMock = vi.hoisted(() => vi.fn(async () => true));vi.mock('@lobechat/builtin-agents', () => ({BUILTIN_AGENT_SLUGS: { inbox: 'inbox' },@@ -44,6 +45,10 @@ vi.mock('@/store/chat', () => ({},}));+vi.mock('@/store/device', () => ({+ useDeviceStore: { getState: () => ({ preHydrateDeviceList: preHydrateDeviceListMock }) },+}));+const loaderArgs = (aid?: string) => ({ params: aid ? { aid } : {} }) as never;describe('agent chat topic list loader', () => {@@ -52,6 +57,8 @@ describe('agent chat topic list loader', () => {preHydrateTopicListMock.mockResolvedValue(true);preHydrateBuiltinAgentMock.mockClear();preHydrateBuiltinAgentMock.mockResolvedValue(true);+ preHydrateDeviceListMock.mockClear();+ preHydrateDeviceListMock.mockResolvedValue(true);getSidebarTopicListParamsMock.mockReset();getSidebarTopicListParamsMock.mockReturnValue({ agentId: 'agt_1', pageSize: 20 });});@@ -60,6 +67,25 @@ describe('agent chat topic list loader', () => {vi.useRealTimers();});+ // Without it the input bar's device chip read "Unknown device" until the+ // mount-time hydrate (or the network) answered.+ it('seeds the persisted device list before the route commits', async () => {+ await agentChatTopicListLoader(loaderArgs('agt_1'));++ expect(preHydrateDeviceListMock).toHaveBeenCalledTimes(1);+ });++ it('does not let a stalled device-list read block the route', async () => {+ vi.useFakeTimers();+ preHydrateDeviceListMock.mockImplementation(() => new Promise(() => {}));++ const settled = vi.fn();+ void agentChatTopicListLoader(loaderArgs('agt_1')).then(settled);++ await vi.advanceTimersByTimeAsync(PRE_PAINT_HYDRATE_TIMEOUT);+ expect(settled).toHaveBeenCalled();+ });+it('seeds the persisted page for the route agent before the route commits', async () => {getSidebarTopicListParamsMock.mockReturnValue({ agentId: 'agt_1', pageSize: 20 });diff --git a/src/routes/(main)/agent/(chat)/topicListLoader.ts b/src/routes/(main)/agent/(chat)/topicListLoader.tsindex 819a0d3d119..6efb07f2bc7 100644--- a/src/routes/(main)/agent/(chat)/topicListLoader.ts+++ b/src/routes/(main)/agent/(chat)/topicListLoader.ts@@ -6,6 +6,7 @@ import { PRE_PAINT_HYDRATE_TIMEOUT, settleWithin } from '@/libs/replica/prePaintimport { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';+import { useDeviceStore } from '@/store/device';const builtinAgentSlugs = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));@@ -63,6 +64,13 @@ export const preHydrateMessagesForRoute = async ();};+/**+ * Seed the persisted device list, so the input bar names the bound device and+ * resolves its cwd on the first frame instead of after the mount-time hydrate.+ */+export const preHydrateDeviceListForRoute = (): Promise<void> =>+ settleWithin(useDeviceStore.getState().preHydrateDeviceList(), PRE_PAINT_HYDRATE_TIMEOUT);+/** Loader for the agent chat routes (`/agent/:aid`, `/agent/:aid/:topicId`). */export const agentChatTopicListLoader = async ({ params }: LoaderFunctionArgs): Promise<null> => {/**@@ -81,6 +89,7 @@ export const agentChatTopicListLoader = async ({ params }: LoaderFunctionArgs):await Promise.all([preHydrateTopicListForRoute(params.aid),preHydrateMessagesForRoute(params.aid, params.topicId),+ preHydrateDeviceListForRoute(),]);return null;diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 8afdd4ab968..5a08dd7fa6f 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -110,7 +110,7 @@ afterEach(() => {// Zustand state and the window-backed agent context survive `restoreAllMocks`,// so a cwd test that seeds a device (or a desktop path) would otherwise leak// a working directory into every later send in this file.- useDeviceStore.setState({ devices: [] });+ useDeviceStore.setState({ deviceListMap: {} });delete window.__LOBE_GLOBAL_AGENT_CONTEXT__;vi.restoreAllMocks();});@@ -2527,7 +2527,7 @@ describe('ConversationLifecycle actions', () => {});act(() => {useDeviceStore.setState({- devices: [{ defaultCwd: '/repo/default', deviceId, name: 'Mac' }] as any,+ deviceListMap: { all: [{ defaultCwd: '/repo/default', deviceId, name: 'Mac' }] as any },});});@@ -2791,9 +2791,11 @@ describe('ConversationLifecycle actions', () => {const sendMessageInServerSpy = setupHeteroRun();act(() => {useDeviceStore.setState({- devices: [- { defaultCwd: '/repo/device-default', deviceId: HETERO_DEVICE_ID, name: 'Mac' },- ] as any,+ deviceListMap: {+ all: [+ { defaultCwd: '/repo/device-default', deviceId: HETERO_DEVICE_ID, name: 'Mac' },+ ] as any,+ },});});@@ -2883,9 +2885,11 @@ describe('ConversationLifecycle actions', () => {});act(() => {useDeviceStore.setState({- devices: [- { defaultCwd: '/repo/device-default', deviceId: HETERO_DEVICE_ID, name: 'Mac' },- ] as any,+ deviceListMap: {+ all: [+ { defaultCwd: '/repo/device-default', deviceId: HETERO_DEVICE_ID, name: 'Mac' },+ ] as any,+ },});});diff --git a/src/store/device/action.test.ts b/src/store/device/action.test.tsindex 5b37f0c58b4..994d7184604 100644--- a/src/store/device/action.test.ts+++ b/src/store/device/action.test.ts@@ -2,10 +2,12 @@ import type { DeviceListItem, WorkingDirEntry } from '@lobechat/types';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DEVICE_LIST_SWR_KEY } from '@/features/DeviceManager/const';+import { cacheScope } from '@/libs/replica';import { mutate } from '@/libs/swr';-import { deviceKeys } from '@/libs/swr/keys';import { deviceService } from '@/services/device';+import { initialState } from './initialState';+import { DEVICE_LIST_KEY } from './projection';import { deviceSelectors } from './selectors';import { useDeviceStore } from './store';@@ -14,6 +16,21 @@ vi.mock('@/libs/swr', () => ({useClientDataSWR: vi.fn(),}));+const seedDevices = (devices: DeviceListItem[]) =>+ useDeviceStore.setState({ deviceListMap: { [DEVICE_LIST_KEY]: devices } });++/** The SWR matchers the action revalidated with. */+const revalidatedMatchers = () =>+ vi+ .mocked(mutate)+ .mock.calls.map(([key]) => key)+ .filter((key): key is (key: unknown) => boolean => typeof key === 'function');++const revalidatedDeviceListReplica = () =>+ revalidatedMatchers().some((matcher) =>+ matcher(['replica:sync', 'deviceList', 1, cacheScope.get(), DEVICE_LIST_KEY, {}]),+ );+const buildDevice = (overrides: Partial<DeviceListItem> = {}): DeviceListItem => ({channels: [],defaultCwd: '/repo',@@ -42,7 +59,7 @@ describe('DeviceAction', () => {vi.spyOn(deviceService, 'removeWorkspaceDeviceWorkingDir').mockResolvedValue({success: true,});- useDeviceStore.setState({ devices: [], isDevicesInit: true });+ useDeviceStore.setState(initialState);});afterEach(() => {@@ -60,40 +77,35 @@ describe('DeviceAction', () => {deviceId: 'dev-2',workingDirs: [{ path: '/other-device' }],});- useDeviceStore.setState({- devices: [buildDevice({ workingDirs }), otherDevice],- });+ seedDevices([buildDevice({ workingDirs }), otherDevice]);await useDeviceStore.getState().clearDeviceDefaultCwd('dev-1');const state = useDeviceStore.getState();expect(deviceSelectors.getDeviceDefaultCwd('dev-1')(state)).toBeUndefined();expect(deviceSelectors.getDeviceWorkingDirs('dev-1')(state)).toEqual(workingDirs);- expect(state.devices.find((device) => device.deviceId === 'dev-2')).toEqual(otherDevice);+ expect(deviceSelectors.getDeviceById('dev-2')(state)).toEqual(otherDevice);expect(deviceService.updateDevice).toHaveBeenCalledWith({defaultCwd: null,deviceId: 'dev-1',});- expect(mutate).toHaveBeenCalledWith(deviceKeys.listDevices());+ expect(revalidatedDeviceListReplica()).toBe(true);});// Task controls read the workspace-scoped `useDeviceList` entry, so a cwd// write that only revalidated this store's key left them showing stale recents.it('also revalidates the canonical device-list cache', async () => {- useDeviceStore.setState({ devices: [buildDevice()] });+ seedDevices([buildDevice()]);await useDeviceStore.getState().clearDeviceDefaultCwd('dev-1');- const matcher = vi- .mocked(mutate)- .mock.calls.map(([key]) => key)- .find((key): key is (key: unknown) => boolean => typeof key === 'function');- expect(matcher?.([DEVICE_LIST_SWR_KEY, 'ws-1'])).toBe(true);- expect(matcher?.(deviceKeys.listDevices())).toBe(false);+ const matchers = revalidatedMatchers();+ expect(matchers.some((matcher) => matcher([DEVICE_LIST_SWR_KEY, 'ws-1']))).toBe(true);+ expect(revalidatedDeviceListReplica()).toBe(true);});it('does nothing when the target device does not exist', async () => {- useDeviceStore.setState({ devices: [buildDevice()] });+ seedDevices([buildDevice()]);await useDeviceStore.getState().clearDeviceDefaultCwd('missing');@@ -103,7 +115,7 @@ describe('DeviceAction', () => {it('restores the previous default and revalidates when persistence fails', async () => {const workingDirs: WorkingDirEntry[] = [{ path: '/repo', repoType: 'git' }];- useDeviceStore.setState({ devices: [buildDevice({ workingDirs })] });+ seedDevices([buildDevice({ workingDirs })]);vi.mocked(deviceService.updateDevice).mockRejectedValueOnce(new Error('save failed'));await expect(useDeviceStore.getState().clearDeviceDefaultCwd('dev-1')).rejects.toThrow(@@ -113,7 +125,7 @@ describe('DeviceAction', () => {const state = useDeviceStore.getState();expect(deviceSelectors.getDeviceDefaultCwd('dev-1')(state)).toBe('/repo');expect(deviceSelectors.getDeviceWorkingDirs('dev-1')(state)).toEqual(workingDirs);- expect(mutate).toHaveBeenCalledWith(deviceKeys.listDevices());+ expect(revalidatedDeviceListReplica()).toBe(true);});});@@ -130,7 +142,7 @@ describe('DeviceAction', () => {// Members share the list, so only the touched entry is sent — never this// client's whole (possibly stale) snapshot.it('removes one recent dir through the workspace entry mutation', async () => {- useDeviceStore.setState({ devices: [workspaceDevice()] });+ seedDevices([workspaceDevice()]);await useDeviceStore.getState().removeDeviceWorkingDir('ws-dev', '/a');@@ -146,7 +158,7 @@ describe('DeviceAction', () => {});it('adds one picked dir through the workspace entry mutation', async () => {- useDeviceStore.setState({ devices: [workspaceDevice()] });+ seedDevices([workspaceDevice()]);await useDeviceStore.getState()@@ -161,7 +173,7 @@ describe('DeviceAction', () => {});it('sets the device default separately from the entry add', async () => {- useDeviceStore.setState({ devices: [workspaceDevice()] });+ seedDevices([workspaceDevice()]);await useDeviceStore.getState().updateDeviceCwd('ws-dev', { path: '/c' });@@ -176,7 +188,7 @@ describe('DeviceAction', () => {});it('keeps personal devices on the personal mutation', async () => {- useDeviceStore.setState({ devices: [buildDevice({ workingDirs: [{ path: '/a' }] })] });+ seedDevices([buildDevice({ workingDirs: [{ path: '/a' }] })]);await useDeviceStore.getState().removeDeviceWorkingDir('dev-1', '/a');diff --git a/src/store/device/action.ts b/src/store/device/action.tsindex bf838669954..35ee7ba9abc 100644--- a/src/store/device/action.ts+++ b/src/store/device/action.ts@@ -1,23 +1,18 @@import type { DeviceListItem, WorkingDirEntry } from '@lobechat/types';-import { type SWRResponse } from 'swr';import { refreshDeviceList } from '@/features/DeviceManager/const';-import { mutate, useClientDataSWR } from '@/libs/swr';-import { deviceKeys } from '@/libs/swr/keys';+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';import { deviceService } from '@/services/device';import { type StoreSetter } from '@/store/types';import { nextWorkingDirs, removeWorkingDir, WORKING_DIRS_MAX } from './deviceCwd';+import { DEVICE_LIST_KEY, type DeviceListParams, deviceListResource } from './projection';+import { deviceSelectors } from './selectors';import { type DeviceStore } from './store';type Setter = StoreSetter<DeviceStore>;-/**- * Revalidate both device-list caches: this store's own key and the canonical- * workspace-scoped `useDeviceList` entry, which task controls read.- */-const revalidateDeviceLists = () =>- Promise.all([mutate(deviceKeys.listDevices()), refreshDeviceList()]);+const LIST_PARAMS = {} as DeviceListParams;type UpdateDeviceInput = Parameters<typeof deviceService.updateDevice>[0];@@ -36,14 +31,54 @@ export const deviceSlice = (set: Setter, get: () => DeviceStore, _api?: unknown)export class DeviceActionImpl {readonly #get: () => DeviceStore;- readonly #set: Setter;+ readonly #list;constructor(set: Setter, get: () => DeviceStore, _api?: unknown) {void _api;- this.#set = set;this.#get = get;+ this.#list = createReplicaSlice(deviceListResource, {+ actionPrefix: 'device/list',+ fetcher: () => deviceService.listDevices(),+ get,+ set,+ stateKey: 'deviceListReplica',+ view: recordLens<DeviceStore, DeviceListItem[]>('deviceListMap'),+ });}+ #devices = (): DeviceListItem[] => deviceSelectors.deviceList(this.#get());++ /** Patch one device row optimistically; rolls back if `serverCall` rejects. */+ #patchDevice = <T>(+ deviceId: string,+ patch: (device: DeviceListItem) => DeviceListItem,+ serverCall: () => Promise<T>,+ ): Promise<T> =>+ this.#list.optimistic(+ DEVICE_LIST_KEY,+ (devices) => devices.map((d) => (d.deviceId === deviceId ? patch(d) : d)),+ serverCall,+ );++ /**+ * Revalidate both device lists: this store's replica and the canonical+ * workspace-scoped `useDeviceList` entry, which task controls read.+ */+ #revalidateDeviceLists = () =>+ Promise.all([this.#list.revalidate(DEVICE_LIST_KEY), refreshDeviceList()]);++ /**+ * Seed the persisted device list before the route commits, so the bound+ * device's name and cwd paint on the first frame instead of after the+ * mount-time hydrate. Call from a route loader, bounded by a timeout.+ */+ preHydrateDeviceList = async (): Promise<boolean> => {+ const scope = deviceListResource.scope.get();+ // The slot may still hold the previous identity's rows; drop them first.+ this.#list.ensureScope(scope);+ return this.#list.hydrate(LIST_PARAMS, scope);+ };+/*** Persist a working-directory choice to a device (`defaultCwd` + `workingDirs`)* with an optimistic store update, then revalidate from the server. Pass@@ -59,79 +94,58 @@ export class DeviceActionImpl {if (!trimmed) return;const setDefault = options.setDefault ?? true;- const device = this.#get().devices.find((d) => d.deviceId === deviceId);+ const device = this.#devices().find((d) => d.deviceId === deviceId);const updatedDirs = nextWorkingDirs(entry, device?.workingDirs ?? []);- // Optimistic: patch the touched device in place. Spreading widens the item- // out of the listDevices union, so re-assert the element type.- this.#set(- {- devices: this.#get().devices.map((d) =>- d.deviceId === deviceId- ? { ...d, ...(setDefault ? { defaultCwd: trimmed } : {}), workingDirs: updatedDirs }- : d,- ) as DeviceListItem[],- },- false,- 'updateDeviceCwd',- );-try {- if (device?.scope === 'workspace') {- // Members share this list: add the one entry server-side instead of- // replacing the list with this client's possibly stale snapshot.- await deviceService.addWorkspaceDeviceWorkingDir({- deviceId,- entry: { ...entry, path: trimmed },- });- if (setDefault)- await deviceService.updateWorkspaceDevice({ defaultCwd: trimmed, deviceId });- } else {- await deviceService.updateDevice({- deviceId,- ...(setDefault ? { defaultCwd: trimmed } : {}),- workingDirs: updatedDirs,- });- }+ // Spreading widens the item out of the listDevices union, so re-assert it.+ await this.#patchDevice(+ deviceId,+ (d) =>+ ({+ ...d,+ ...(setDefault ? { defaultCwd: trimmed } : {}),+ workingDirs: updatedDirs,+ }) as DeviceListItem,+ async () => {+ if (device?.scope === 'workspace') {+ // Members share this list: add the one entry server-side instead of+ // replacing the list with this client's possibly stale snapshot.+ await deviceService.addWorkspaceDeviceWorkingDir({+ deviceId,+ entry: { ...entry, path: trimmed },+ });+ if (setDefault)+ await deviceService.updateWorkspaceDevice({ defaultCwd: trimmed, deviceId });+ } else {+ await deviceService.updateDevice({+ deviceId,+ ...(setDefault ? { defaultCwd: trimmed } : {}),+ workingDirs: updatedDirs,+ });+ }+ },+ );} finally {- // Re-fetch the truth (self-corrects a failed optimistic write).- await revalidateDeviceLists();+ // Re-fetch the truth (server-normalized fields, other tabs' writes).+ await this.#revalidateDeviceLists();}};/** Clear a device's default cwd without removing it from the recent directory list. */clearDeviceDefaultCwd = async (deviceId: string): Promise<void> => {- const device = this.#get().devices.find((d) => d.deviceId === deviceId);+ const device = this.#devices().find((d) => d.deviceId === deviceId);if (!device?.defaultCwd) return;- const previousDefaultCwd = device.defaultCwd;-- this.#set(- {- devices: this.#get().devices.map((d) =>- d.deviceId === deviceId ? { ...d, defaultCwd: null } : d,- ) as DeviceListItem[],- },- false,- 'clearDeviceDefaultCwd',- );-try {- await persistDevice(device, { defaultCwd: null, deviceId });- } catch (error) {- // Preserve the prior default if the optimistic write cannot be persisted.- this.#set(- {- devices: this.#get().devices.map((d) =>- d.deviceId === deviceId ? { ...d, defaultCwd: previousDefaultCwd } : d,- ) as DeviceListItem[],- },- false,- 'clearDeviceDefaultCwd/error',+ // A failed write rolls back to the prior default.+ await this.#patchDevice(+ deviceId,+ (d) => ({ ...d, defaultCwd: null }) as DeviceListItem,+ () => persistDevice(device, { defaultCwd: null, deviceId }),);- throw error;} finally {- await revalidateDeviceLists();+ await this.#revalidateDeviceLists();}};@@ -147,7 +161,7 @@ export class DeviceActionImpl {): Promise<void> => {if (legacyEntries.length === 0) return;- const device = this.#get().devices.find((d) => d.deviceId === deviceId);+ const device = this.#devices().find((d) => d.deviceId === deviceId);const existing = device?.workingDirs ?? [];const existingPaths = new Set(existing.map((d) => d.path));const merged = [...existing, ...legacyEntries.filter((d) => !existingPaths.has(d.path))].slice(@@ -155,59 +169,44 @@ export class DeviceActionImpl {WORKING_DIRS_MAX,);- this.#set(- {- devices: this.#get().devices.map((d) =>- d.deviceId === deviceId ? { ...d, workingDirs: merged } : d,- ) as DeviceListItem[],- },- false,- 'migrateLocalRecents',- );-try {- await persistDevice(device, { deviceId, workingDirs: merged });+ await this.#patchDevice(+ deviceId,+ (d) => ({ ...d, workingDirs: merged }) as DeviceListItem,+ () => persistDevice(device, { deviceId, workingDirs: merged }),+ );} finally {- await revalidateDeviceLists();+ await this.#revalidateDeviceLists();}};/** Remove a path from a device's `workingDirs` recent list (optimistic). */removeDeviceWorkingDir = async (deviceId: string, path: string): Promise<void> => {- const device = this.#get().devices.find((d) => d.deviceId === deviceId);+ const device = this.#devices().find((d) => d.deviceId === deviceId);if (!device) return;const updated = removeWorkingDir(path, device.workingDirs ?? []);- this.#set(- {- devices: this.#get().devices.map((d) =>- d.deviceId === deviceId ? { ...d, workingDirs: updated } : d,- ) as DeviceListItem[],- },- false,- 'removeDeviceWorkingDir',- );-try {- await (device.scope === 'workspace'- ? deviceService.removeWorkspaceDeviceWorkingDir({ deviceId, path })- : deviceService.updateDevice({ deviceId, workingDirs: updated }));+ await this.#patchDevice(+ deviceId,+ (d) => ({ ...d, workingDirs: updated }) as DeviceListItem,+ () =>+ device.scope === 'workspace'+ ? deviceService.removeWorkspaceDeviceWorkingDir({ deviceId, path })+ : deviceService.updateDevice({ deviceId, workingDirs: updated }),+ );} finally {- await revalidateDeviceLists();+ await this.#revalidateDeviceLists();}};- useFetchDevices = (enabled = false): SWRResponse<DeviceListItem[]> =>- useClientDataSWR<DeviceListItem[]>(- enabled ? deviceKeys.listDevices() : null,- () => deviceService.listDevices(),- {- fallbackData: [],- onSuccess: (data) => {- this.#set({ devices: data, isDevicesInit: true }, false, 'fetchDevices');- },- },- );+ /**+ * Fetch orchestration only; read the rows with `deviceSelectors.deviceList`.+ * The persisted copy paints first (presence unknown), then the server+ * confirms it in the background.+ */+ useFetchDevices = (enabled = false): ReplicaSyncResult =>+ this.#list.useSync(LIST_PARAMS, { enabled });}export type DeviceAction = Pick<DeviceActionImpl, keyof DeviceActionImpl>;diff --git a/src/store/device/deviceListReplica.test.ts b/src/store/device/deviceListReplica.test.tsnew file mode 100644index 00000000000..fa73a5bd6fc--- /dev/null+++ b/src/store/device/deviceListReplica.test.ts@@ -0,0 +1,198 @@+/**+ * @vitest-environment happy-dom+ *+ * The device list is a replica: a reload paints the persisted copy (device+ * names, `defaultCwd`) on the first frame, with presence unknown, and the+ * server confirms it in the background.+ */+import { randomUUID } from 'node:crypto';++import type { DeviceListItem } from '@lobechat/types';+import { act, renderHook, waitFor } from '@testing-library/react';+import type { PropsWithChildren } from 'react';+import { createElement, useEffect } from 'react';+import { SWRConfig, useSWRConfig } from 'swr';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { cacheScope } from '@/libs/replica';+import { setScopedMutate } from '@/libs/swr/mutate';+import { deviceService } from '@/services/device';++import { initialState } from './initialState';+import { deviceListResource, MAX_PERSISTED_DEVICES } from './projection';+import { deviceSelectors } from './selectors';+import { useDeviceStore } from './store';++vi.mock('@/services/device', () => ({+ deviceService: { listDevices: vi.fn(), updateDevice: vi.fn() },+}));++const MutateBridge = () => {+ const { mutate } = useSWRConfig();+ useEffect(() => setScopedMutate(mutate), [mutate]);+ return null;+};++const wrapper = ({ children }: PropsWithChildren) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map() } },+ createElement(MutateBridge),+ children,+ );++const device = (deviceId: string, overrides: Partial<DeviceListItem> = {}): DeviceListItem => ({+ channels: [{ channel: 'cli', connectedAt: new Date(0).toISOString() } as never],+ defaultCwd: `/repo/${deviceId}`,+ deviceId,+ enroller: null,+ friendlyName: `Mac ${deviceId}`,+ hostname: null,+ identitySource: 'machine-id',+ lastSeen: new Date(0).toISOString(),+ online: true,+ platform: 'darwin',+ registered: true,+ scope: 'personal',+ visibility: null,+ workingDirs: [{ path: `/repo/${deviceId}` }],+ ...overrides,+});++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const ROW_KEY = deviceListResource.storageKey({});+const readRow = (scope: string) =>+ deviceListResource.storage!.get({ queryKey: ROW_KEY, scope }).then((row) => row?.data);++describe('device list replica', () => {+ const scopes = new Set<string>();+ let scope = '';+ const useScope = (next: string) => {+ scope = next;+ scopes.add(next);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ };++ beforeEach(() => {+ useScope(`device-user-${randomUUID()}:personal`);+ act(() => useDeviceStore.setState(initialState));+ });++ afterEach(async () => {+ await Promise.all(+ [...scopes].map((value) =>+ deviceListResource.storage!.remove({ queryKey: ROW_KEY, scope: value }),+ ),+ );+ scopes.clear();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it('paints the persisted list after a reload, before the network answers', async () => {+ await deviceListResource.storage!.set(+ { queryKey: ROW_KEY, scope },+ { data: [device('dev-1')], updatedAt: 1 },+ );+ vi.mocked(deviceService.listDevices).mockImplementation(pending);++ renderHook(() => useDeviceStore((s) => s.useFetchDevices)(true), { wrapper });++ await waitFor(() =>+ expect(deviceSelectors.getDeviceDefaultCwd('dev-1')(useDeviceStore.getState())).toBe(+ '/repo/dev-1',+ ),+ );+ const state = useDeviceStore.getState();+ expect(deviceSelectors.getDeviceById('dev-1')(state)?.friendlyName).toBe('Mac dev-1');+ expect(deviceSelectors.isDeviceListLoaded(state)).toBe(true);+ // A stored row is not a confirmed one: presence stays unknown.+ expect(deviceSelectors.isDeviceListConfirmed(state)).toBe(false);+ expect(deviceSelectors.getDeviceById('dev-1')(state)).toMatchObject({+ channels: [],+ online: false,+ onlineUnknown: true,+ });+ expect(deviceSelectors.hasTerminalTarget(state)).toBe(false);+ });++ it('seeds the persisted list from a route loader without a mounted view', async () => {+ await deviceListResource.storage!.set(+ { queryKey: ROW_KEY, scope },+ { data: [device('dev-1')], updatedAt: 1 },+ );++ await expect(useDeviceStore.getState().preHydrateDeviceList()).resolves.toBe(true);++ expect(deviceSelectors.getDeviceById('dev-1')(useDeviceStore.getState())?.friendlyName).toBe(+ 'Mac dev-1',+ );+ });++ it('keeps live presence in memory but persists it as unknown', async () => {+ vi.mocked(deviceService.listDevices).mockResolvedValue([device('dev-1')]);++ renderHook(() => useDeviceStore((s) => s.useFetchDevices)(true), { wrapper });++ await waitFor(() =>+ expect(deviceSelectors.isDeviceListConfirmed(useDeviceStore.getState())).toBe(true),+ );+ expect(deviceSelectors.getDeviceById('dev-1')(useDeviceStore.getState())).toMatchObject({+ online: true,+ });+ expect(deviceSelectors.hasTerminalTarget(useDeviceStore.getState())).toBe(true);++ await waitFor(async () =>+ expect(await readRow(scope)).toEqual([+ { ...device('dev-1'), channels: [], online: false, onlineUnknown: true },+ ]),+ );+ });++ it('caps the persisted snapshot', async () => {+ const many = Array.from({ length: MAX_PERSISTED_DEVICES + 5 }, (_, i) => device(`dev-${i}`));+ vi.mocked(deviceService.listDevices).mockResolvedValue(many);++ renderHook(() => useDeviceStore((s) => s.useFetchDevices)(true), { wrapper });++ await waitFor(async () => expect(await readRow(scope)).toHaveLength(MAX_PERSISTED_DEVICES));+ expect(deviceSelectors.deviceList(useDeviceStore.getState())).toHaveLength(many.length);+ });++ it('never paints another identity’s devices', async () => {+ const other = `device-user-${randomUUID()}:personal`;+ scopes.add(other);+ await deviceListResource.storage!.set(+ { queryKey: ROW_KEY, scope: other },+ { data: [device('theirs')], updatedAt: 1 },+ );+ vi.mocked(deviceService.listDevices).mockImplementation(pending);++ const sync = renderHook(() => useDeviceStore((s) => s.useFetchDevices)(true), { wrapper });++ await waitFor(() => expect(sync.result.current.isHydrated).toBe(true));+ expect(deviceSelectors.getDeviceById('theirs')(useDeviceStore.getState())).toBeUndefined();+ expect(deviceSelectors.isDeviceListLoaded(useDeviceStore.getState())).toBe(false);+ });++ it('rolls back an optimistic cwd write the server rejects', async () => {+ vi.mocked(deviceService.listDevices).mockResolvedValue([device('dev-1')]);+ renderHook(() => useDeviceStore((s) => s.useFetchDevices)(true), { wrapper });+ await waitFor(() =>+ expect(deviceSelectors.isDeviceListConfirmed(useDeviceStore.getState())).toBe(true),+ );+ vi.mocked(deviceService.updateDevice).mockRejectedValueOnce(new Error('save failed'));++ await expect(+ useDeviceStore.getState().updateDeviceCwd('dev-1', { path: '/elsewhere' }),+ ).rejects.toThrow('save failed');++ expect(deviceSelectors.getDeviceDefaultCwd('dev-1')(useDeviceStore.getState())).toBe(+ '/repo/dev-1',+ );+ });+});diff --git a/src/store/device/initialState.ts b/src/store/device/initialState.tsindex 4d2e9b934e9..40267dbe2a1 100644--- a/src/store/device/initialState.ts+++ b/src/store/device/initialState.ts@@ -1,11 +1,18 @@import type { DeviceListItem } from '@lobechat/types';+import { createReplicaState, type ReplicaState } from '@/libs/replica';+export interface DeviceState {- devices: DeviceListItem[];- isDevicesInit: boolean;+ /**+ * `deviceListMap.all`: every device of the active scope, or `undefined` until+ * the persisted copy or the server answers. Read it through `deviceSelectors`.+ */+ deviceListMap: Record<string, DeviceListItem[]>;+ /** Replica bookkeeping for `deviceListMap`. */+ deviceListReplica: ReplicaState<DeviceListItem[]>;}export const initialState: DeviceState = {- devices: [],- isDevicesInit: false,+ deviceListMap: {},+ deviceListReplica: createReplicaState(),};diff --git a/src/store/device/projection.ts b/src/store/device/projection.tsnew file mode 100644index 00000000000..65a743a280a--- /dev/null+++ b/src/store/device/projection.ts@@ -0,0 +1,60 @@+import type { DeviceListItem } from '@lobechat/types';++import { LocalStorageQueryProjectionStorage } from '@/libs/queryProjectionStorage';+import { defineReplica, REPLICA_INDEX_KEY, type ReplicaStorage } from '@/libs/replica';++/** The store reads every device of the active scope, so the list has one entry. */+export const DEVICE_LIST_KEY = 'all';++export type DeviceListParams = Record<string, never>;++/** Upper bound on persisted device rows — the snapshot must stay a small shell. */+export const MAX_PERSISTED_DEVICES = 50;++/**+ * A persisted device row keeps what the UI needs to name the device and+ * resolve its working directory (name, platform, `defaultCwd`, `workingDirs`).+ * Presence is a live gateway fact, so it never reaches storage: `online` is+ * stored as `false`, the live `channels` are dropped, and `onlineUnknown` marks+ * the row until the next `listDevices` replaces it.+ */+export const toPersistedDevice = (device: DeviceListItem): DeviceListItem => ({+ ...device,+ channels: [],+ online: false,+ onlineUnknown: true,+});++/**+ * localStorage, with the device rows reshaped by {@link toPersistedDevice} on+ * write. Memory keeps the confirmed presence; only what survives a reload is+ * narrowed. The engine's own index row passes through untouched.+ */+const createDeviceListStorage = (namespace: string): ReplicaStorage<DeviceListItem[]> => {+ const storage = new LocalStorageQueryProjectionStorage<DeviceListItem[]>({ namespace });++ return {+ get: storage.get,+ getStrict: storage.getStrict,+ remove: storage.remove,+ set: (key, row) =>+ storage.set(+ key,+ key.queryKey === REPLICA_INDEX_KEY+ ? row+ : { ...row, data: row.data.slice(0, MAX_PERSISTED_DEVICES).map(toPersistedDevice) },+ ),+ };+};++/**+ * Every device of the active scope (`deviceListMap.all`). Persisted per user ++ * workspace so a reload names the bound device and resolves its cwd on first+ * paint; presence stays unknown until the server answers.+ */+export const deviceListResource = defineReplica<DeviceListParams, DeviceListItem[]>({+ key: () => DEVICE_LIST_KEY,+ name: 'deviceList',+ storage: createDeviceListStorage('replica:deviceList:v1'),+ version: 1,+});diff --git a/src/store/device/selectors.test.ts b/src/store/device/selectors.test.tsindex ab7a0956586..91034b2a3da 100644--- a/src/store/device/selectors.test.ts+++ b/src/store/device/selectors.test.ts@@ -14,7 +14,7 @@ const channel = (name: string | null) => ({platform: null,});-const state = (devices: DeviceListItem[]) => ({ devices }) as DeviceState;+const state = (devices: DeviceListItem[]) => ({ deviceListMap: { all: devices } }) as DeviceState;describe('canHostTerminal', () => {it('accepts a live CLI connection, including its suffixed variants', () => {diff --git a/src/store/device/selectors.ts b/src/store/device/selectors.tsindex 927a75764f8..cd6d8d4eae8 100644--- a/src/store/device/selectors.ts+++ b/src/store/device/selectors.ts@@ -3,8 +3,24 @@ import type { DeviceListItem } from '@lobechat/types';import { getChannelKind } from '@/features/DeviceManager/channelKind';import type { DeviceState } from './initialState';+import { DEVICE_LIST_KEY } from './projection';-const deviceList = (s: DeviceState): DeviceListItem[] => s.devices;+const EMPTY_DEVICES: DeviceListItem[] = [];++const deviceList = (s: DeviceState): DeviceListItem[] =>+ s.deviceListMap[DEVICE_LIST_KEY] ?? EMPTY_DEVICES;++/** The list is on screen — from the persisted copy or the server. */+const isDeviceListLoaded = (s: DeviceState): boolean =>+ s.deviceListMap[DEVICE_LIST_KEY] !== undefined;++/**+ * The list was confirmed by the server this session. A persisted copy holds+ * stale `workingDirs` and unknown presence, so writes that merge into a device+ * row wait for this.+ */+const isDeviceListConfirmed = (s: DeviceState): boolean =>+ s.deviceListReplica.entries[DEVICE_LIST_KEY]?.source === 'server';/*** Whether a shell opened from the browser can run on this device.@@ -33,12 +49,12 @@ export const canHostTerminal = (device: DeviceListItem): boolean => {* `Object.is`, and a fresh array on every call would re-render the panel on* every unrelated store write.*/-const hasTerminalTarget = (s: DeviceState): boolean => s.devices.some(canHostTerminal);+const hasTerminalTarget = (s: DeviceState): boolean => deviceList(s).some(canHostTerminal);const getDeviceById =(deviceId: string | undefined) =>(s: DeviceState): DeviceListItem | undefined =>- deviceId ? s.devices.find((d) => d.deviceId === deviceId) : undefined;+ deviceId ? deviceList(s).find((d) => d.deviceId === deviceId) : undefined;/** A device's user-configured default working directory (per-device fallback cwd). */const getDeviceDefaultCwd =@@ -56,4 +72,6 @@ export const deviceSelectors = {getDeviceDefaultCwd,getDeviceWorkingDirs,hasTerminalTarget,+ isDeviceListConfirmed,+ isDeviceListLoaded,};