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.

⚡️ perf(device): serve every device list reader from the device replica (#21200)

Arvin Xua237fcb26e34
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 9a3b155e89b..28f30489526 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1443,6 +1443,7 @@
"heteroAgent.executionTarget.gateway": "Gateway",
"heteroAgent.executionTarget.gatewayDesc": "Run through the device gateway so other clients can follow progress",
"heteroAgent.executionTarget.infoTooltip": "Choose where this Agent runs. A device can read and write files or operate a computer; Cloud Sandbox runs in an isolated temporary environment.",
+ "heteroAgent.executionTarget.loadFailed": "Couldn’t load devices.",
"heteroAgent.executionTarget.loading": "Loading devices…",
"heteroAgent.executionTarget.local": "Local device",
"heteroAgent.executionTarget.localDesc": "Run as a local process on this desktop app",
@@ -1462,6 +1463,7 @@
"heteroAgent.executionTarget.onlineConnections_one": "Online · {{count}} connection",
"heteroAgent.executionTarget.onlineConnections_other": "Online · {{count}} connections",
"heteroAgent.executionTarget.personalGroup": "Private Devices",
+ "heteroAgent.executionTarget.presenceChecking": "Checking status…",
"heteroAgent.executionTarget.projectDevicesHint": "Only devices with this project's working directory are listed. Add a directory for another device in the project settings.",
"heteroAgent.executionTarget.reconnect": "Reconnect",
"heteroAgent.executionTarget.reconnectFailed": "Could not reconnect this device. Make sure the desktop app is running, then try again.",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index ef8e21154bf..8a5f07c2fda 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -551,6 +551,7 @@
"devices.share.viewerHint": "Viewers cannot share devices",
"devices.share.visibilityTag.private": "Private",
"devices.share.visibilityTag.public": "Workspace",
+ "devices.status.checking": "Checking status…",
"devices.status.offline": "Offline",
"devices.status.online": "Online",
"devices.status.onlineConnections_one": "Online · {{count}} connection",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 18bc080be3b..0a4eea76e5d 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1443,6 +1443,7 @@
"heteroAgent.executionTarget.gateway": "网关",
"heteroAgent.executionTarget.gatewayDesc": "经由设备网关运行,其他客户端可跟踪进度",
"heteroAgent.executionTarget.infoTooltip": "选择此代理运行的位置。设备可以读取和写入文件或操作计算机;云沙盒在隔离的临时环境中运行。",
+ "heteroAgent.executionTarget.loadFailed": "设备加载失败。",
"heteroAgent.executionTarget.loading": "正在加载设备…",
"heteroAgent.executionTarget.local": "本地设备",
"heteroAgent.executionTarget.localDesc": "在当前桌面端以本地进程运行",
@@ -1462,6 +1463,7 @@
"heteroAgent.executionTarget.onlineConnections_one": "在线 · {{count}} 个连接",
"heteroAgent.executionTarget.onlineConnections_other": "在线 · {{count}} 个连接",
"heteroAgent.executionTarget.personalGroup": "私人设备",
+ "heteroAgent.executionTarget.presenceChecking": "正在确认状态…",
"heteroAgent.executionTarget.projectDevicesHint": "仅列出已绑定此项目工作目录的设备。其他设备可在项目设置中添加目录。",
"heteroAgent.executionTarget.reconnect": "重新连接",
"heteroAgent.executionTarget.reconnectFailed": "无法重新连接此设备。请确认桌面端正在运行,然后重试。",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 0d6d676a541..1d742a95216 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -551,6 +551,7 @@
"devices.share.viewerHint": "查看者无法共享设备",
"devices.share.visibilityTag.private": "私人",
"devices.share.visibilityTag.public": "工作区",
+ "devices.status.checking": "正在确认状态…",
"devices.status.offline": "离线",
"devices.status.online": "在线",
"devices.status.onlineConnections_one": "在线 · {{count}} 个连接",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 002613547d1..2ad7e2aa67e 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -855,6 +855,7 @@ export default {
'heteroAgent.executionTarget.gateway': 'Gateway',
'heteroAgent.executionTarget.gatewayDesc':
'Run through the device gateway so other clients can follow progress',
+ 'heteroAgent.executionTarget.loadFailed': 'Couldn’t load devices.',
'heteroAgent.executionTarget.loading': 'Loading devices…',
'heteroAgent.executionTarget.local': 'Local device',
'heteroAgent.executionTarget.localDesc': 'Run as a local process on this desktop app',
@@ -878,6 +879,7 @@ export default {
'heteroAgent.executionTarget.online': 'Online',
'heteroAgent.executionTarget.onlineConnections_one': 'Online · {{count}} connection',
'heteroAgent.executionTarget.onlineConnections_other': 'Online · {{count}} connections',
+ 'heteroAgent.executionTarget.presenceChecking': 'Checking status…',
'heteroAgent.executionTarget.projectDevicesHint':
"Only devices with this project's working directory are listed. Add a directory for another device in the project settings.",
'heteroAgent.executionTarget.switchProjectTopic.content':
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 13cbb17f3c2..653ead3e1d6 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -828,6 +828,7 @@ export default {
'devices.share.visibilityTag.private': 'Private',
'devices.share.visibilityTag.public': 'Workspace',
'devices.status.offline': 'Offline',
+ 'devices.status.checking': 'Checking status…',
'devices.status.online': 'Online',
'devices.status.onlineConnections_one': 'Online · {{count}} connection',
'devices.status.onlineConnections_other': 'Online · {{count}} connections',
diff --git a/src/features/AgentHome/StagedProjectHint.tsx b/src/features/AgentHome/StagedProjectHint.tsx
index da9bd1c0709..ac20d4198fa 100644
--- a/src/features/AgentHome/StagedProjectHint.tsx
+++ b/src/features/AgentHome/StagedProjectHint.tsx
@@ -7,8 +7,8 @@ import { Trans } from 'react-i18next';
import Avatar from '@/components/Avatar';
import { projectDirectoryDeviceName } from '@/features/ChatInput/ControlBar/projectDeviceTargets';
-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';
+import { useDeviceList } from '@/store/device';
import { useStagedNewTopicDirectory } from './useStagedNewTopicDirectory';
diff --git a/src/features/AgentPermission/useAgentPermission.test.ts b/src/features/AgentPermission/useAgentPermission.test.ts
index b0eb3f5dc74..243a0f82f54 100644
--- a/src/features/AgentPermission/useAgentPermission.test.ts
+++ b/src/features/AgentPermission/useAgentPermission.test.ts
@@ -27,8 +27,8 @@ vi.mock('@/store/user', () => ({
selector({ user: { id: mocks.viewerId } }),
}));
-vi.mock('@/features/DeviceManager/useDeviceList', () => ({
- useDeviceList: () => ({ data: mocks.devices }),
+vi.mock('@/store/device/useDeviceList', () => ({
+ useDeviceList: () => ({ data: mocks.devices, isConfirmed: true }),
}));
vi.mock('@/features/ResourcePermission/useResourcePermission', () => ({
diff --git a/src/features/AgentTasks/features/TaskDeviceChip.tsx b/src/features/AgentTasks/features/TaskDeviceChip.tsx
index b332994dab6..a549e6916df 100644
--- a/src/features/AgentTasks/features/TaskDeviceChip.tsx
+++ b/src/features/AgentTasks/features/TaskDeviceChip.tsx
@@ -11,7 +11,7 @@ import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/Exe
import { taskExecutionStyles as styles } from './taskExecutionStyles';
import TaskPickerOption from './TaskPickerOption';
-import { deviceLabel, useTaskRunTarget } from './useTaskRunTarget';
+import { deviceLabel, getTaskDeviceLockReason, useTaskRunTarget } from './useTaskRunTarget';
interface TaskDeviceChipProps {
/** The assignee whose execution environment is inherited when nothing is pinned. */
@@ -55,12 +55,21 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
const { t } = useTranslation('chat');
const [open, setOpen] = useState(false);
- const { canSelect, devices, inheritedLabel, inheritedTarget, isPending, pinnedDeviceId } =
- useTaskRunTarget(agentId, value);
+ const {
+ canSelect,
+ devices,
+ devicesFailed,
+ inheritedLabel,
+ inheritedTarget,
+ isPending,
+ pinnedDeviceId,
+ retryDevices,
+ } = useTaskRunTarget(agentId, value);
// The agent's policy is author-controlled: the server's resolver would drop
// this pin, so the control must not pretend it can set one.
- const isLocked = disabled || isPending || !canSelect;
+ const lockReason = getTaskDeviceLockReason({ canSelect, disabled, isPending });
+ const isLocked = !!lockReason;
// Read the EFFECTIVE pin, never the raw prop: an author-fixed policy makes
// the run side drop a requested device, and showing the stored one would
@@ -108,6 +117,8 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
offlineLabel={t('heteroAgent.executionTarget.offline')}
online={device.online}
onlineLabel={t('heteroAgent.executionTarget.online')}
+ unknown={device.onlineUnknown}
+ unknownLabel={t('heteroAgent.executionTarget.presenceChecking')}
/>
</div>
</Flexbox>
@@ -142,10 +153,18 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
{isPending && (
<div className={styles.sectionTitle}>{t('heteroAgent.executionTarget.loading')}</div>
)}
- {!isPending && devices && devices.length > 0 && (
+ {devicesFailed && (
+ <div className={styles.emptyHint}>
+ {t('heteroAgent.executionTarget.loadFailed')}{' '}
+ <a role="button" onClick={retryDevices}>
+ {t('retry', { ns: 'common' })}
+ </a>
+ </div>
+ )}
+ {!isPending && !devicesFailed && devices && devices.length > 0 && (
<div className={styles.scroll}>{devices.map(renderDeviceRow)}</div>
)}
- {!isPending && devices?.length === 0 && (
+ {!isPending && !devicesFailed && devices?.length === 0 && (
<div className={styles.emptyHint}>{t('heteroAgent.executionTarget.noDevices')}</div>
)}
@@ -191,7 +210,9 @@ const TaskDeviceChip = memo<TaskDeviceChipProps>(
<Tooltip
title={formatLockedControlTooltip(
t('taskExecution.runLocation'),
- t('taskExecution.fixedTip'),
+ lockReason === 'pending'
+ ? t('heteroAgent.executionTarget.presenceChecking')
+ : t('taskExecution.fixedTip'),
)}
>
{chip}
diff --git a/src/features/AgentTasks/features/TaskExecutionControls.tsx b/src/features/AgentTasks/features/TaskExecutionControls.tsx
index ab261be5595..ffdf3fdb49f 100644
--- a/src/features/AgentTasks/features/TaskExecutionControls.tsx
+++ b/src/features/AgentTasks/features/TaskExecutionControls.tsx
@@ -131,7 +131,7 @@ const TaskExecutionControlsInner = memo<
{target.directoryKind === 'device' && target.deviceId ? (
<TaskWorkingDirectoryChip
deviceId={target.deviceId}
- disabled={disabled}
+ disabled={disabled || target.isPending}
value={value?.workingDirectoryConfig}
onChange={handleDirectoryChange}
/>
diff --git a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.test.tsx b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.test.tsx
index f1ad8f0f2c4..ea5d02f0ae5 100644
--- a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.test.tsx
+++ b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.test.tsx
@@ -26,7 +26,7 @@ vi.mock('@/features/WorkingDirectory', () => ({ openAddWorkingDirModal: vi.fn()
vi.mock('@/services/device', () => ({ deviceService: { statPath: vi.fn() } }));
-vi.mock('@/features/DeviceManager/useDeviceList', () => ({
+vi.mock('@/store/device/useDeviceList', () => ({
useDeviceList: () => ({
data: [
{
diff --git a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx
index 9be597bd94b..d970577a0c7 100644
--- a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx
+++ b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx
@@ -9,13 +9,13 @@ import { useTranslation } from 'react-i18next';
import DirIcon from '@/features/ChatInput/ControlBar/DirIcon';
import { formatLockedControlTooltip } from '@/features/ChatInput/utils/lockedControlTooltip';
-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { openAddWorkingDirModal } from '@/features/WorkingDirectory';
import {
getWorkingDirectoryName,
getWorkingDirectoryPathString,
} from '@/helpers/workingDirectoryPath';
import { deviceService } from '@/services/device';
+import { useDeviceList } from '@/store/device';
import { taskExecutionStyles as styles } from './taskExecutionStyles';
import TaskPickerOption from './TaskPickerOption';
@@ -49,9 +49,9 @@ const TaskWorkingDirectoryChip = memo<TaskWorkingDirectoryChipProps>(
const { t: tDevice } = useTranslation('device');
const [open, setOpen] = useState(false);
- // Read the canonical device list (the same SWR entry `useTaskRunTarget`
- // fetches), not the device store: a task page may render nothing that
- // populates the store, which left the recents empty on a cold load.
+ // `useDeviceList` mounts the device replica's sync itself: a task page may
+ // render nothing else that fetches the list, which left the recents empty
+ // on a cold load.
const { data: devices } = useDeviceList();
const device = devices?.find((item) => item.deviceId === deviceId);
const deviceDefaultCwd = getWorkingDirectoryPathString(device?.defaultCwd ?? undefined);
diff --git a/src/features/AgentTasks/features/useTaskRunTarget.test.ts b/src/features/AgentTasks/features/useTaskRunTarget.test.ts
index 14bafbdf33e..e5135c14397 100644
--- a/src/features/AgentTasks/features/useTaskRunTarget.test.ts
+++ b/src/features/AgentTasks/features/useTaskRunTarget.test.ts
@@ -1,7 +1,7 @@
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { useTaskRunTarget } from './useTaskRunTarget';
+import { getTaskDeviceLockReason, useTaskRunTarget } from './useTaskRunTarget';
const DEVICE_AGENT_BOUND = 'device-agent-bound';
const DEVICE_TASK_PIN = 'device-task-pin';
@@ -28,6 +28,9 @@ const mocks = vi.hoisted(() => ({
activeTopicAgency: undefined as undefined | { agencyConfig: Record<string, unknown> },
agentState: { agentMap: {} as Record<string, { workspaceId?: string }> },
devices: [] as { deviceId: string; scope?: string; visibility?: string }[],
+ devicesConfirmed: true,
+ devicesError: undefined as unknown,
+ mutateDevices: vi.fn(),
electron: { currentDeviceId: undefined as string | undefined, isDesktop: false },
}));
@@ -50,8 +53,15 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
-vi.mock('@/features/DeviceManager/useDeviceList', () => ({
- useDeviceList: () => ({ data: mocks.devices, isLoading: false }),
+vi.mock('@/store/device/useDeviceList', () => ({
+ useDeviceList: () => ({
+ data: mocks.devices,
+ error: mocks.devicesError,
+ isConfirmed: mocks.devicesConfirmed,
+ isLoading: false,
+ isValidating: false,
+ mutate: mocks.mutateDevices,
+ }),
}));
vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
@@ -82,6 +92,9 @@ const deviceBoundAgent = {
beforeEach(() => {
mocks.activeTopicAgency = undefined;
+ mocks.devicesConfirmed = true;
+ mocks.devicesError = undefined;
+ mocks.mutateDevices.mockReset();
mocks.agency.agencyConfig = {};
mocks.agency.canSelectExecutionTarget = true;
mocks.agency.isPreferenceLoading = false;
@@ -93,6 +106,36 @@ beforeEach(() => {
describe('useTaskRunTarget', () => {
// A task's runs never carry the open chat topic's binding, so the machine
// shown for a task must not follow whatever conversation happens to be active.
+ it('keeps the target controls pending while the device list is the stored copy', () => {
+ mocks.devices = [PERSONAL_DEVICE];
+ mocks.devicesConfirmed = false;
+
+ const { result, rerender } = renderHook(() => useTaskRunTarget('agent-1'));
+
+ // A stored row may since have been deleted or unshared: no pin from it yet.
+ expect(result.current.isPending).toBe(true);
+
+ mocks.devicesConfirmed = true;
+ rerender();
+
+ expect(result.current.isPending).toBe(false);
+ });
+
+ it('unlocks with a retry, not a pin, when the unconfirmed device list fails to load', () => {
+ mocks.devices = [PERSONAL_DEVICE];
+ mocks.devicesConfirmed = false;
+ mocks.devicesError = new Error('network down');
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+
+ // Not stuck pending: the chip opens and says why, offering a retry.
+ expect(result.current.isPending).toBe(false);
+ expect(result.current.devicesFailed).toBe(true);
+
+ result.current.retryDevices();
+ expect(mocks.mutateDevices).toHaveBeenCalledTimes(1);
+ });
+
it('ignores the active chat topic device binding', () => {
mocks.agency.agencyConfig = deviceBoundAgent;
mocks.activeTopicAgency = {
@@ -251,3 +294,20 @@ describe('useTaskRunTarget', () => {
]);
});
});
+
+describe('getTaskDeviceLockReason', () => {
+ it('explains a lock caused by the unconfirmed device list as pending, not fixed', () => {
+ expect(getTaskDeviceLockReason({ canSelect: true, isPending: true })).toBe('pending');
+ });
+
+ it('keeps the fixed reason for an author-fixed policy or a disabled form', () => {
+ expect(getTaskDeviceLockReason({ canSelect: false, isPending: true })).toBe('fixed');
+ expect(getTaskDeviceLockReason({ canSelect: true, disabled: true, isPending: false })).toBe(
+ 'fixed',
+ );
+ });
+
+ it('does not lock a selectable, confirmed target', () => {
+ expect(getTaskDeviceLockReason({ canSelect: true, isPending: false })).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentTasks/features/useTaskRunTarget.ts b/src/features/AgentTasks/features/useTaskRunTarget.ts
index 086be2933e2..76c428bd229 100644
--- a/src/features/AgentTasks/features/useTaskRunTarget.ts
+++ b/src/features/AgentTasks/features/useTaskRunTarget.ts
@@ -2,11 +2,10 @@
import { isDesktop } from '@lobechat/const';
import type { DeviceExecutionTarget, DeviceListItem, WorkingDirConfig } from '@lobechat/types';
-import { useMemo } from 'react';
+import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { resolveWorkspaceSurface } from '@/features/ChatInput/ControlBar/useWorkspaceSurface';
-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { devicePoolForAgent, devicePoolForTask } from '@/features/ExecutionTargetPicker';
import { resolveAgentWorkingDirectoryConfig } from '@/helpers/agentWorkingDirectory';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
@@ -15,6 +14,7 @@ import { getWorkingDirectoryPathString } from '@/helpers/workingDirectoryPath';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useDeviceList } from '@/store/device';
import { useElectronStore } from '@/store/electron';
export type DeviceLabelSource = Pick<DeviceListItem, 'deviceId' | 'friendlyName' | 'hostname'>;
@@ -22,6 +22,25 @@ export type DeviceLabelSource = Pick<DeviceListItem, 'deviceId' | 'friendlyName'
export const deviceLabel = (device: DeviceLabelSource, unknownLabel: string) =>
device.friendlyName || device.hostname || unknownLabel;
+/**
+ * Why the run-location control is locked, for its tooltip. An author-fixed
+ * policy (or a disabled form) says so; a target still waiting on the device
+ * list is only being checked, not fixed.
+ */
+export const getTaskDeviceLockReason = ({
+ canSelect,
+ disabled,
+ isPending,
+}: {
+ canSelect: boolean;
+ disabled?: boolean;
+ isPending: boolean;
+}): 'fixed' | 'pending' | undefined => {
+ if (disabled || !canSelect) return 'fixed';
+ if (isPending) return 'pending';
+ return undefined;
+};
+
/**
* What the directory axis can offer, which is a property of the TARGET and not
* of the task: a cloud repo identifier and a path on a machine are the same
@@ -46,6 +65,12 @@ export interface TaskRunTarget {
* device the caller can see (see `devicePoolForAgent`).
*/
devices?: DeviceListItem[];
+ /**
+ * The device list could not be confirmed: its request failed and no retry is
+ * in flight. The stored rows still cannot be pinned, but the control stays
+ * open so the user can retry ({@link retryDevices}) or follow the agent.
+ */
+ devicesFailed: boolean;
directoryKind: TaskDirectoryKind;
/** Where the run lands: the task's pin if it has one, else the agent's own target. */
effectiveTarget: DeviceExecutionTarget;
@@ -65,6 +90,12 @@ export interface TaskRunTarget {
inheritedTarget: DeviceExecutionTarget;
/** Whether a task-level pin is what puts the run on {@link deviceId}. */
isDeviceTarget: boolean;
+ /**
+ * The target controls must wait: the preference is loading, or the device
+ * list is still the stored copy. Its rows may since have been deleted or
+ * unshared, and a pin stored from one would point the task's runs at a
+ * machine they cannot resolve.
+ */
isPending: boolean;
/**
* The task's own pin, and only when the assignee's policy lets it take
@@ -72,6 +103,8 @@ export interface TaskRunTarget {
* run side drops must not be shown as the target.
*/
pinnedDeviceId?: string;
+ /** Re-request the device list after {@link devicesFailed}. */
+ retryDevices: () => void;
}
/**
@@ -89,7 +122,14 @@ export interface TaskRunTarget {
*/
export const useTaskRunTarget = (agentId: string, pinnedDeviceId?: string): TaskRunTarget => {
const { t } = useTranslation('chat');
- const { data: devices, isLoading: isDevicesLoading } = useDeviceList();
+ const {
+ data: devices,
+ error: devicesError,
+ isConfirmed: isDevicesConfirmed,
+ isLoading: isDevicesLoading,
+ isValidating: isDevicesValidating,
+ mutate: refreshDevices,
+ } = useDeviceList();
const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
// Agent-level, not the active chat topic's: a task run carries no topic
// binding, so the conversation that happens to be open must not move it.
@@ -213,17 +253,22 @@ export const useTaskRunTarget = (agentId: string, pinnedDeviceId?: string): Task
return t(`heteroAgent.executionTarget.${inheritedTarget}`);
})();
+ const devicesFailed = !isDevicesConfirmed && !!devicesError && !isDevicesValidating;
+ const retryDevices = useCallback(() => void refreshDevices(), [refreshDevices]);
+
return {
canSelect: canSelectExecutionTarget,
deviceId,
devices: pool,
+ devicesFailed,
directoryKind,
effectiveTarget,
inheritedDirectory,
inheritedLabel,
inheritedTarget,
isDeviceTarget,
- isPending: isPreferenceLoading || isDevicesLoading,
+ isPending: isPreferenceLoading || isDevicesLoading || (!isDevicesConfirmed && !devicesFailed),
pinnedDeviceId: pinApplies ? pinnedDeviceId : undefined,
+ retryDevices,
};
};
diff --git a/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx
index f2eda4c1627..6c4d923e454 100644
--- a/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx
+++ b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import DeviceHoverPanel from '@/features/DeviceManager/DeviceHoverPanel';
import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';
+import { isDevicePresenceUnknown } from '@/store/device';
import { handleDeviceRowKeyDown } from './deviceRowKeyDown';
import OptionRow from './OptionRow';
@@ -56,6 +57,8 @@ const DeviceOptionRow = ({
tags,
}: DeviceOptionRowProps) => {
const { t } = useTranslation('chat');
+ // A row restored from the persisted list is neither online nor offline yet.
+ const presenceUnknown = isDevicePresenceUnknown(device);
return (
<Popover
@@ -85,12 +88,14 @@ const DeviceOptionRow = ({
<ExecutionTargetDeviceStatus
offlineLabel={t('heteroAgent.executionTarget.offline')}
online={device.online}
+ unknown={presenceUnknown}
+ unknownLabel={t('heteroAgent.executionTarget.presenceChecking')}
onlineLabel={t('heteroAgent.executionTarget.onlineConnections', {
count: device.channels.length,
})}
/>
)}
- {device.online ? null : (
+ {device.online || presenceUnknown ? null : (
<Button
className={styles.reconnectButton}
icon={<Icon icon={RefreshCwIcon} size={10} />}
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index c641183abb6..ee457a187b2 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -30,7 +30,6 @@ import { DOWNLOAD_URL } from '@/const/url';
import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
import { useLocalSandboxCapability } from '@/features/ChatInput/hooks/useLocalSandboxCapability';
import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import {
devicePoolForAgent,
ExecutionTargetIcon,
@@ -46,12 +45,13 @@ 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 { useDeviceList } from '@/store/device';
import { useElectronStore } from '@/store/electron';
import { useTopicId } from '../hooks/useTopicId';
import { formatLockedControlTooltip } from '../utils/lockedControlTooltip';
import DeviceOptionRow from './DeviceOptionRow';
+import { getDevicePoolStatus } from './devicePoolStatus';
import OptionRow from './OptionRow';
import { useSandboxNetworkToggle } from './useSandboxNetworkToggle';
import { useTopicAwareTargetSelect } from './useTopicAwareTargetSelect';
@@ -294,14 +294,15 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const isHetero = !!heteroType;
const supportsSandbox = isHeterogeneousSandboxExecutionAvailable(heteroType);
- // Workspace-keyed SWR fetch — the raw lambdaQuery key has no workspace
- // 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 device replica, partitioned by workspace: a reload paints the persisted
+ // list first, so the chip names the bound device instead of "Unknown device".
+ const {
+ data: devices,
+ error: deviceListError,
+ isConfirmed: isDeviceListConfirmed,
+ isValidating: isDeviceListValidating,
+ mutate: refreshDevices,
+ } = useDeviceList();
// 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
@@ -477,8 +478,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const boundDevice =
canShowExecutionTargetSelector && executionTarget === 'device'
- ? (devices?.find((d) => d.deviceId === boundDeviceId) ??
- (devices ? undefined : storedBoundDevice))
+ ? devices?.find((d) => d.deviceId === boundDeviceId)
: undefined;
// The picker splits by whether the caller is inside a workspace agent:
@@ -507,13 +507,21 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
// The pool rule itself lives in `devicePoolForAgent`, shared with every other
// surface that lists devices for an agent (e.g. the Task run-location chip).
const deviceRows = devicePoolForAgent(devices, isWorkspaceAgent);
- const hasNoDevices = deviceRows.length === 0;
+ // Only a server-confirmed list can say the pool is empty: a stored copy may
+ // lack this pool's rows (stale, or past the persisted-row cap).
+ const poolStatus = getDevicePoolStatus({
+ error: deviceListError,
+ isConfirmed: isDeviceListConfirmed,
+ isValidating: isDeviceListValidating,
+ rowCount: deviceRows.length,
+ });
+ const isPoolEmpty = poolStatus === 'empty';
// On web with no device, the prominent download card below replaces the small
// header link — avoid showing the same CTA twice. Workspace agents get the
// enroll hint instead: downloading the desktop app wouldn't help until the
// machine is enrolled into the workspace pool.
- const showWebDownloadCard = !isDesktop && !isWorkspaceAgent && hasNoDevices && !isLoading;
- const showWorkspaceEnrollHint = isWorkspaceAgent && hasNoDevices && !isLoading;
+ const showWebDownloadCard = !isDesktop && !isWorkspaceAgent && isPoolEmpty;
+ const showWorkspaceEnrollHint = isWorkspaceAgent && isPoolEmpty;
// Compute chip
let chipIcon: ReactNode = <ExecutionTargetIcon target={'sandbox'} />;
@@ -761,9 +769,22 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
</div>
)
) : null}
- {hasNoDevices && isLoading ? (
+ {poolStatus === 'loading' ? (
<div className={styles.empty}>{t('heteroAgent.executionTarget.loading')}</div>
) : null}
+ {poolStatus === 'error' ? (
+ <div className={styles.empty}>
+ {t('heteroAgent.executionTarget.loadFailed')}{' '}
+ <a
+ role="button"
+ onClick={() => {
+ void refreshDevices();
+ }}
+ >
+ {t('retry', { ns: 'common' })}
+ </a>
+ </div>
+ ) : null}
{/* Workspace agent with no workspace device: personal machines are
suppressed above, so guide the user to enroll one into the shared
pool instead of showing a bare menu. */}
@@ -797,7 +818,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
<Icon className={styles.downloadCardArrow} icon={ExternalLinkIcon} size={13} />
</a>
) : null}
- {hasNoDevices && !isLoading && isDesktop && !isWorkspaceAgent ? (
+ {isPoolEmpty && isDesktop && !isWorkspaceAgent ? (
<div className={styles.empty}>{t('heteroAgent.executionTarget.noDevices')}</div>
) : null}
</Flexbox>
diff --git a/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
index 2ed77b9f0ae..5e79582c4f2 100644
--- a/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
@@ -6,10 +6,10 @@ import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useDeviceList } from '@/store/device';
import { type ProjectDirectory } from '@/store/projectWorkingDirectory';
import OptionRow from './OptionRow';
@@ -117,6 +117,8 @@ const ProjectDeviceSwitcher = ({
offlineLabel={t('heteroAgent.executionTarget.offline')}
online={target.online}
onlineLabel={t('heteroAgent.executionTarget.online')}
+ unknown={target.onlineUnknown}
+ unknownLabel={t('heteroAgent.executionTarget.presenceChecking')}
/>
</span>
</>
diff --git a/src/features/ChatInput/ControlBar/devicePoolStatus.test.ts b/src/features/ChatInput/ControlBar/devicePoolStatus.test.ts
new file mode 100644
index 00000000000..aaaa6b0f7de
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/devicePoolStatus.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import { getDevicePoolStatus } from './devicePoolStatus';
+
+const base = { error: undefined, isConfirmed: false, isValidating: true, rowCount: 0 };
+
+describe('getDevicePoolStatus', () => {
+ it('reads a stored copy with no rows for this pool as loading, not empty', () => {
+ // e.g. a workspace agent whose stored copy only holds personal devices.
+ expect(getDevicePoolStatus(base)).toBe('loading');
+ });
+
+ it('surfaces a failed refresh of an unconfirmed pool instead of an empty hint', () => {
+ expect(getDevicePoolStatus({ ...base, error: new Error('boom'), isValidating: false })).toBe(
+ 'error',
+ );
+ });
+
+ it('shows the retry in flight as loading', () => {
+ expect(getDevicePoolStatus({ ...base, error: new Error('boom') })).toBe('loading');
+ });
+
+ it('reports empty once the server confirmed the pool has no device', () => {
+ expect(getDevicePoolStatus({ ...base, isConfirmed: true, isValidating: false })).toBe('empty');
+ });
+
+ it('shows rows straight away, stored or confirmed', () => {
+ expect(getDevicePoolStatus({ ...base, rowCount: 2 })).toBe('devices');
+ expect(getDevicePoolStatus({ ...base, isConfirmed: true, rowCount: 2 })).toBe('devices');
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/devicePoolStatus.ts b/src/features/ChatInput/ControlBar/devicePoolStatus.ts
new file mode 100644
index 00000000000..f01af564502
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/devicePoolStatus.ts
@@ -0,0 +1,30 @@
+/**
+ * What a device picker shows for the pool the current agent can pick from.
+ *
+ * Use when:
+ * - A picker filters the device list down to one pool (scope / visibility)
+ * and must decide between rows, a loading line, an error, or an empty hint
+ *
+ * Returns:
+ * - `devices` whenever the pool has rows, stored or confirmed
+ * - `empty` only once the server confirmed the list: a stored copy without
+ * rows for this pool may be stale or capped, so it is not proof of absence
+ * - `error` when that unconfirmed pool's refresh failed (and no retry is in flight)
+ * - `loading` otherwise
+ */
+export const getDevicePoolStatus = ({
+ error,
+ isConfirmed,
+ isValidating,
+ rowCount,
+}: {
+ error: unknown;
+ isConfirmed: boolean;
+ isValidating: boolean;
+ rowCount: number;
+}): 'devices' | 'empty' | 'error' | 'loading' => {
+ if (rowCount > 0) return 'devices';
+ if (isConfirmed) return 'empty';
+ if (error && !isValidating) return 'error';
+ return 'loading';
+};
diff --git a/src/features/ChatInput/ControlBar/projectDeviceTargets.ts b/src/features/ChatInput/ControlBar/projectDeviceTargets.ts
index a79492bc75d..6448e2250c4 100644
--- a/src/features/ChatInput/ControlBar/projectDeviceTargets.ts
+++ b/src/features/ChatInput/ControlBar/projectDeviceTargets.ts
@@ -9,6 +9,8 @@ export interface ProjectDeviceTarget {
directory: ProjectDirectory;
label: string;
online: boolean;
+ /** The device row is a persisted copy the server has not confirmed: presence unknown. */
+ onlineUnknown: boolean;
}
export const projectDirectoryDeviceName = (
@@ -35,10 +37,14 @@ export const listProjectDeviceTargets = (
): ProjectDeviceTarget[] =>
directories
.filter((d) => d.instanceId && d.permission === 'readWrite')
- .map((directory) => ({
- active: directory.id === currentDirectoryId,
- allowed: !fixedDeviceId || directory.deviceId === fixedDeviceId,
- directory,
- label: projectDirectoryDeviceName(directory, devices),
- online: !!devices?.find((item) => item.deviceId === directory.deviceId)?.online,
- }));
+ .map((directory) => {
+ const device = devices?.find((item) => item.deviceId === directory.deviceId);
+ return {
+ active: directory.id === currentDirectoryId,
+ allowed: !fixedDeviceId || directory.deviceId === fixedDeviceId,
+ directory,
+ label: projectDirectoryDeviceName(directory, devices),
+ online: !!device?.online,
+ onlineUnknown: !!device?.onlineUnknown,
+ };
+ });
diff --git a/src/features/ConnectAgent/deviceListState.test.ts b/src/features/ConnectAgent/deviceListState.test.ts
index b61f11ff98a..831fe69d177 100644
--- a/src/features/ConnectAgent/deviceListState.test.ts
+++ b/src/features/ConnectAgent/deviceListState.test.ts
@@ -4,14 +4,50 @@ import { getDeviceListState } from './deviceListState';
describe('getDeviceListState', () => {
it('keeps an empty device result in loading state while the request is in flight', () => {
- expect(getDeviceListState({ hasDevices: false, isFetching: true })).toBe('loading');
+ expect(getDeviceListState({ hasDevices: false, isConfirmed: true, isFetching: true })).toBe(
+ 'loading',
+ );
});
- it('reports empty only after the request settles', () => {
- expect(getDeviceListState({ hasDevices: false, isFetching: false })).toBe('empty');
+ it('reports empty only after the server confirmed the list', () => {
+ expect(getDeviceListState({ hasDevices: false, isConfirmed: true, isFetching: false })).toBe(
+ 'empty',
+ );
+ });
+
+ it('keeps an unconfirmed stored copy without rows loading while no request has failed', () => {
+ expect(getDeviceListState({ hasDevices: false, isConfirmed: false, isFetching: false })).toBe(
+ 'loading',
+ );
});
it('keeps cached devices visible during revalidation', () => {
- expect(getDeviceListState({ hasDevices: true, isFetching: true })).toBe('ready');
+ expect(getDeviceListState({ hasDevices: true, isConfirmed: false, isFetching: true })).toBe(
+ 'ready',
+ );
+ });
+});
+
+describe('getDeviceListState when the request fails', () => {
+ it('reports an error, not an endless skeleton, for an unconfirmed pool without rows', () => {
+ expect(
+ getDeviceListState({
+ error: new Error('network down'),
+ hasDevices: false,
+ isConfirmed: false,
+ isFetching: false,
+ }),
+ ).toBe('error');
+ });
+
+ it('shows a retry in flight as loading', () => {
+ expect(
+ getDeviceListState({
+ error: new Error('network down'),
+ hasDevices: false,
+ isConfirmed: false,
+ isFetching: true,
+ }),
+ ).toBe('loading');
});
});
diff --git a/src/features/ConnectAgent/deviceListState.ts b/src/features/ConnectAgent/deviceListState.ts
index 44452ba45ef..5cf5eeaf632 100644
--- a/src/features/ConnectAgent/deviceListState.ts
+++ b/src/features/ConnectAgent/deviceListState.ts
@@ -1,14 +1,26 @@
-export type DeviceListState = 'empty' | 'loading' | 'ready';
+export type DeviceListState = 'empty' | 'error' | 'loading' | 'ready';
interface GetDeviceListStateOptions {
+ /** The last device-list request failed. */
+ error?: unknown;
hasDevices: boolean;
+ /**
+ * The server answered this session. A stored copy without rows for this
+ * pool may be stale or capped, so it is not proof the pool is empty.
+ */
+ isConfirmed: boolean;
isFetching: boolean;
}
export const getDeviceListState = ({
+ error,
hasDevices,
+ isConfirmed,
isFetching,
}: GetDeviceListStateOptions): DeviceListState => {
if (hasDevices) return 'ready';
- return isFetching ? 'loading' : 'empty';
+ if (isFetching) return 'loading';
+ // Unconfirmed and the request failed: say so instead of an endless skeleton.
+ if (!isConfirmed) return error ? 'error' : 'loading';
+ return 'empty';
};
diff --git a/src/features/ConnectAgent/index.tsx b/src/features/ConnectAgent/index.tsx
index 9d59b203657..891b5252509 100644
--- a/src/features/ConnectAgent/index.tsx
+++ b/src/features/ConnectAgent/index.tsx
@@ -36,14 +36,15 @@ import { memo, type ReactNode, useCallback, useEffect, useMemo, useState } from
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import AsyncError from '@/components/AsyncError';
import CommandLine from '@/components/CommandLine';
import { DOWNLOAD_URL } from '@/const/url';
import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';
-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { deviceService } from '@/services/device';
import { useAgentStore } from '@/store/agent';
import { heteroAgentDefaultName } from '@/store/agent/utils/heteroAgentDefaultName';
+import { isDevicePresenceUnknown, useDeviceList } from '@/store/device';
import { useElectronStore } from '@/store/electron';
import { useHomeStore } from '@/store/home';
@@ -418,6 +419,8 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
const {
data: devices,
+ error: deviceListError,
+ isConfirmed: isDeviceListConfirmed,
isLoading: loadingDevices,
isValidating: fetchingDevices,
mutate: refetchDevices,
@@ -428,6 +431,9 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
[devices, restrictToWorkspaceDevices],
);
const onlineDevices = listedDevices.filter((d) => d.online);
+ // Rows painted from the persisted list until the server confirms presence:
+ // none of them is offline yet, so "no devices" would be a guess.
+ const presencePending = !isDeviceListConfirmed || listedDevices.some(isDevicePresenceUnknown);
const deviceLabel = useCallback(
(device: DeviceListItem) => device.friendlyName || device.hostname || device.deviceId,
@@ -635,10 +641,13 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
if (step === 0) {
const isRefreshing = loadingDevices || fetchingDevices;
const deviceListState = getDeviceListState({
+ error: deviceListError,
hasDevices: listedDevices.length > 0,
+ isConfirmed: isDeviceListConfirmed,
isFetching: isRefreshing,
});
- const showEmpty = !isDesktop && !isRefreshing && onlineDevices.length === 0;
+ const showEmpty =
+ !isDesktop && !isRefreshing && !presencePending && onlineDevices.length === 0;
return (
<Flexbox gap={16} paddingBlock={'16px 8px'}>
@@ -737,25 +746,35 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
</Button>
</Flexbox>
<div className={styles.groupList}>
- {deviceListState === 'loading'
- ? [96, 140, 112].map((width) => (
- <SkeletonRow squareIcon key={width} width={width} />
- ))
- : listedDevices.map((device) => (
- <DeviceRow
- icon={getDeviceIcon(device.platform, 18)}
- key={device.deviceId}
- offline={!device.online}
- subtitle={device.hostname || device.deviceId}
- title={deviceLabel(device)}
- statusText={
- device.online
+ {deviceListState === 'error' ? (
+ <AsyncError
+ error={deviceListError}
+ variant={'inline'}
+ onRetry={() => void refetchDevices()}
+ />
+ ) : deviceListState === 'loading' ? (
+ [96, 140, 112].map((width) => (
+ <SkeletonRow squareIcon key={width} width={width} />
+ ))
+ ) : (
+ listedDevices.map((device) => (
+ <DeviceRow
+ icon={getDeviceIcon(device.platform, 18)}
+ key={device.deviceId}
+ offline={!device.online}
+ subtitle={device.hostname || device.deviceId}
+ title={deviceLabel(device)}
+ statusText={
+ isDevicePresenceUnknown(device)
+ ? t('heteroAgent.executionTarget.presenceChecking')
+ : device.online
? t('connectAgent.create.online')
: t('connectAgent.create.offline')
- }
- onClick={() => pickTarget({ device, kind: 'device' })}
- />
- ))}
+ }
+ onClick={() => pickTarget({ device, kind: 'device' })}
+ />
+ ))
+ )}
</div>
</Flexbox>
)}
diff --git a/src/features/Conversation/WorkingSidebar/Overview/__tests__/useBoundDevice.test.ts b/src/features/Conversation/WorkingSidebar/Overview/__tests__/useBoundDevice.test.ts
index 31c16f59557..b1973e17f4f 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/__tests__/useBoundDevice.test.ts
+++ b/src/features/Conversation/WorkingSidebar/Overview/__tests__/useBoundDevice.test.ts
@@ -6,12 +6,16 @@ import { PRESENCE_REFRESH_INTERVAL_MS, useBoundDevice } from '../useBoundDevice'
const useDeviceList = vi.fn();
const mutate = vi.fn();
-vi.mock('@/features/DeviceManager/useDeviceList', () => ({
+vi.mock('@/store/device/useDeviceList', () => ({
useDeviceList: (...args: unknown[]) => useDeviceList(...args),
}));
-const listState = (state: { data?: unknown; error?: unknown; isLoading?: boolean }) =>
- useDeviceList.mockReturnValue({ isLoading: false, mutate, ...state });
+const listState = (state: {
+ data?: unknown;
+ error?: unknown;
+ isConfirmed?: boolean;
+ isLoading?: boolean;
+}) => useDeviceList.mockReturnValue({ isConfirmed: true, isLoading: false, mutate, ...state });
describe('useBoundDevice', () => {
beforeEach(() => {
@@ -69,4 +73,30 @@ describe('useBoundDevice', () => {
expect(result.current).toEqual({ device: { deviceId: 'dev-1' }, status: 'ready' });
});
+
+ // A reload restores the list from storage; a stale (or capped) copy may
+ // simply not include the device yet.
+ it('keeps a device missing from the stored copy pending until the server answers', () => {
+ listState({ data: [{ deviceId: 'dev-1' }], isConfirmed: false });
+
+ const { result } = renderHook(() => useBoundDevice('dev-2', true));
+
+ expect(result.current).toEqual({ status: 'loading' });
+ });
+
+ it('offers a retry when the refresh over a stored copy without the device fails', () => {
+ listState({ data: [{ deviceId: 'dev-1' }], error: new Error('network'), isConfirmed: false });
+
+ const { result } = renderHook(() => useBoundDevice('dev-2', true));
+
+ expect(result.current.status).toBe('error');
+ });
+
+ it('paints a device the stored copy already has', () => {
+ listState({ data: [{ deviceId: 'dev-1' }], isConfirmed: false });
+
+ const { result } = renderHook(() => useBoundDevice('dev-1', true));
+
+ expect(result.current).toEqual({ device: { deviceId: 'dev-1' }, status: 'ready' });
+ });
});
diff --git a/src/features/Conversation/WorkingSidebar/Overview/useBoundDevice.ts b/src/features/Conversation/WorkingSidebar/Overview/useBoundDevice.ts
index 8b793d68913..d38b2271e00 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/useBoundDevice.ts
+++ b/src/features/Conversation/WorkingSidebar/Overview/useBoundDevice.ts
@@ -1,6 +1,6 @@
import type { DeviceListItem } from '@lobechat/types';
-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
+import { useDeviceList } from '@/store/device';
/** Re-reads presence so a device that drops or reconnects shows it without a refocus. */
export const PRESENCE_REFRESH_INTERVAL_MS = 30_000;
@@ -8,7 +8,7 @@ export const PRESENCE_REFRESH_INTERVAL_MS = 30_000;
export type BoundDeviceState =
| { status: 'loading' }
| { retry: () => void; status: 'error' }
- /** Loaded, and the device is not in the list: it was removed or never shared. */
+ /** The server's list lacks the device: it was removed or never shared. */
| { status: 'absent' }
| { device: DeviceListItem; status: 'ready' };
@@ -19,24 +19,26 @@ export type BoundDeviceState =
*
* A failed read is kept apart from a missing device, so the section can offer
* a retry instead of silently disappearing. Cached data wins over a later
- * failed revalidation: the last known state beats an error row.
+ * failed revalidation: the last known state beats an error row. A stored copy
+ * that lacks the device proves nothing (it may be stale, or past the
+ * persisted-row cap), so "absent" waits for the server's list.
*/
export const useBoundDevice = (deviceId: string, active: boolean): BoundDeviceState => {
const {
data: devices,
error,
+ isConfirmed,
isLoading,
mutate,
} = useDeviceList({
refreshInterval: active ? PRESENCE_REFRESH_INTERVAL_MS : 0,
});
- if (devices) {
- const device = devices.find((item) => item.deviceId === deviceId);
- return device ? { device, status: 'ready' } : { status: 'absent' };
- }
+ const device = devices?.find((item) => item.deviceId === deviceId);
+ if (device) return { device, status: 'ready' };
+ if (devices && isConfirmed) return { status: 'absent' };
if (error) return { retry: () => void mutate(), status: 'error' };
- if (isLoading) return { status: 'loading' };
+ if (isLoading || devices) return { status: 'loading' };
return { status: 'absent' };
};
diff --git a/src/features/DeviceManager/Connections.tsx b/src/features/DeviceManager/Connections.tsx
index 6fb8c54307d..f826aded014 100644
--- a/src/features/DeviceManager/Connections.tsx
+++ b/src/features/DeviceManager/Connections.tsx
@@ -12,6 +12,7 @@ import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspace
import { AppUpdateAction, AppUpdateHint, useDeviceAppUpdate } from './AppUpdate';
import { getChannelKind, getChannelVersion } from './channelKind';
import { CliUpdate } from './CliUpdate';
+import { getIdleConnectionStatus } from './connectionCount';
import PresenceDot from './PresenceDot';
interface ConnectionCardProps {
@@ -80,7 +81,17 @@ const Connections = ({ canEdit, device }: ConnectionsProps) => {
// A restart drops the desktop app offline; keep following it in place of
// its card until it reconnects.
const restartInFlight =
- !hasDesktopChannel && update.view.kind !== 'loading' && update.view.kind !== 'unavailable';
+ !device.onlineUnknown &&
+ !hasDesktopChannel &&
+ update.view.kind !== 'loading' &&
+ update.view.kind !== 'unavailable';
+
+ // A persisted row has no channels until the server answers: that is "checking",
+ // not "offline".
+ const idleStatus =
+ getIdleConnectionStatus(device) === 'checking'
+ ? t('devices.status.checking')
+ : t('devices.status.offline');
const plainStatus = (text: string) => (
<Text ellipsis fontSize={12} type={'secondary'}>
@@ -140,7 +151,7 @@ const Connections = ({ canEdit, device }: ConnectionsProps) => {
? t('devices.channel.connected', {
time: dayjs(channels[kinds.indexOf('cli')].connectedAt).fromNow(),
})
- : t('devices.status.offline'),
+ : idleStatus,
)}
/>
)}
@@ -150,9 +161,11 @@ const Connections = ({ canEdit, device }: ConnectionsProps) => {
{channels.length === 0 &&
!restartInFlight &&
plainStatus(
- `${t('devices.status.offline')} · ${t('devices.lastSeen', {
- time: dayjs(device.lastSeen).fromNow(),
- })}`,
+ device.onlineUnknown
+ ? idleStatus
+ : `${idleStatus} · ${t('devices.lastSeen', {
+ time: dayjs(device.lastSeen).fromNow(),
+ })}`,
)}
</Flexbox>
);
diff --git a/src/features/DeviceManager/DeviceDetail.tsx b/src/features/DeviceManager/DeviceDetail.tsx
index 248e6547648..dc33a75ad91 100644
--- a/src/features/DeviceManager/DeviceDetail.tsx
+++ b/src/features/DeviceManager/DeviceDetail.tsx
@@ -101,6 +101,12 @@ const isDetailTab = (value: string | null): value is DetailTab =>
interface DeviceDetailProps {
device: DeviceListItem;
+ /**
+ * The row was confirmed by the server this session. A row restored from
+ * storage may be stale, and edits merge into it (the full `workingDirs` list,
+ * the drafts below), so it stays read-only until confirmed.
+ */
+ isConfirmed: boolean;
isCurrent?: boolean;
onBack: () => void;
}
@@ -110,10 +116,12 @@ interface DeviceDetailProps {
* (`/settings/devices/:sub`, `/:slug/settings/devices/:sub`). The list stays a
* plain card grid and every card opens here.
*/
-const DeviceDetail = memo<DeviceDetailProps>(({ device, isCurrent, onBack }) => {
+const DeviceDetail = memo<DeviceDetailProps>(({ device, isConfirmed, isCurrent, onBack }) => {
const { t } = useTranslation(['setting', 'device']);
- const canEdit = useCanEditDevice()(device);
- const canOperate = useCanOperateDevice()(device);
+ // Permission alone drives the read-only hint; confirmation only defers edits.
+ const isEditableRow = useCanEditDevice()(device);
+ const canEdit = isEditableRow && isConfirmed;
+ const canOperate = useCanOperateDevice()(device) && isConfirmed;
// Health monitoring and the directory settings are separate jobs; a tab each
// keeps the charts from pushing the directories below the fold. The active
// tab lives in `?tab=` so a view can be linked, reloaded and reached with
@@ -158,9 +166,11 @@ const DeviceDetail = memo<DeviceDetailProps>(({ device, isCurrent, onBack }) =>
// Only the machine you're on can browse its own filesystem natively.
const canBrowse = !!isCurrent && isDesktop;
- // An empty `device.channels` means offline.
+ // An empty `device.channels` means offline — unless the row is the
+ // persisted copy, whose presence the server has not confirmed yet.
const channels = device.channels ?? [];
const online = channels.length > 0;
+ const presenceUnknown = !!device.onlineUnknown;
// Every edit persists immediately — there is no Save button. Name and the
// default cwd commit on blur; recent-dir add / remove / reorder commit on the
@@ -282,9 +292,11 @@ const DeviceDetail = memo<DeviceDetailProps>(({ device, isCurrent, onBack }) =>
className={styles.presence}
style={{ background: online ? cssVar.colorSuccess : cssVar.colorTextQuaternary }}
title={
- online
- ? t('devices.status.onlineConnections', { count: channels.length })
- : t('devices.status.offline')
+ presenceUnknown
+ ? t('devices.status.checking')
+ : online
+ ? t('devices.status.onlineConnections', { count: channels.length })
+ : t('devices.status.offline')
}
/>
</span>
@@ -362,7 +374,7 @@ const DeviceDetail = memo<DeviceDetailProps>(({ device, isCurrent, onBack }) =>
fields below are read-only without the user needing to try and hit a
403. Only renders for workspace devices that aren't the caller's own
enrollment (personal scope is always editable). */}
- {!canEdit && (
+ {!isEditableRow && (
<Flexbox horizontal align={'center'} gap={8}>
<Icon icon={LockIcon} size={14} style={{ color: cssVar.colorTextTertiary }} />
<Text fontSize={12} type={'secondary'}>
diff --git a/src/features/DeviceManager/DeviceDetailPage.tsx b/src/features/DeviceManager/DeviceDetailPage.tsx
index 61a07a132c2..c6bc2dc9281 100644
--- a/src/features/DeviceManager/DeviceDetailPage.tsx
+++ b/src/features/DeviceManager/DeviceDetailPage.tsx
@@ -8,10 +8,11 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
+import { useDeviceList } from '@/store/device';
import { useElectronStore } from '@/store/electron';
import DeviceDetail from './DeviceDetail';
-import { useDeviceList } from './useDeviceList';
+import { deviceDetailKey, getDeviceListBoundary } from './deviceListBoundary';
const DetailSkeleton = memo(() => (
<Flexbox gap={24}>
@@ -41,8 +42,12 @@ interface DeviceDetailPageProps {
*/
const DeviceDetailPage = memo<DeviceDetailPageProps>(({ deviceId, onBack, scope }) => {
const { t } = useTranslation('setting');
- const { data, isLoading, error, mutate } = useDeviceList();
+ const deviceList = useDeviceList();
+ const { data, error, isConfirmed, mutate } = deviceList;
const device = data?.find((d) => d.deviceId === deviceId && d.scope === scope);
+ // A persisted copy missing this device may just be stale: only the server
+ // can say it is gone.
+ const boundary = getDeviceListBoundary(deviceList, !device);
// The machine the user is on right now (desktop only) — personal pool only.
const useFetchDeviceInfo = useElectronStore((s) => s.useFetchGatewayDeviceInfo);
@@ -70,21 +75,21 @@ const DeviceDetailPage = memo<DeviceDetailPageProps>(({ deviceId, onBack, scope
return (
<AsyncBoundary
- data={data}
+ data={boundary.data}
empty={notFound}
error={error}
errorVariant={'block'}
isEmpty={!device}
- isLoading={isLoading}
+ isLoading={boundary.isLoading}
loading={<DetailSkeleton />}
onRetry={() => mutate()}
>
{device && (
- // keyed on deviceId so the form drafts reset when the route moves to another device
<DeviceDetail
device={device}
+ isConfirmed={isConfirmed}
isCurrent={isCurrent}
- key={device.deviceId}
+ key={deviceDetailKey(device.deviceId, isConfirmed)}
onBack={() => onBack(device)}
/>
)}
diff --git a/src/features/DeviceManager/DeviceHoverPanel.tsx b/src/features/DeviceManager/DeviceHoverPanel.tsx
index 8cdac2adb06..e711a80a73c 100644
--- a/src/features/DeviceManager/DeviceHoverPanel.tsx
+++ b/src/features/DeviceManager/DeviceHoverPanel.tsx
@@ -132,7 +132,13 @@ const DeviceHoverPanel = ({ device }: DeviceHoverPanelProps) => {
width: 6,
}}
/>
- <span>{online ? t('devices.status.online') : t('devices.status.offline')}</span>
+ <span>
+ {summary.onlineUnknown
+ ? t('devices.status.checking')
+ : online
+ ? t('devices.status.online')
+ : t('devices.status.offline')}
+ </span>
</InfoRow>
{online && (
<InfoRow icon={CableIcon} label={t('devices.detail.connections')}>
diff --git a/src/features/DeviceManager/DeviceManager.tsx b/src/features/DeviceManager/DeviceManager.tsx
index cb6cb0e9df3..f191b8751fd 100644
--- a/src/features/DeviceManager/DeviceManager.tsx
+++ b/src/features/DeviceManager/DeviceManager.tsx
@@ -18,12 +18,13 @@ import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
+import { useDeviceList } from '@/store/device';
import { useElectronStore } from '@/store/electron';
import DeviceCard from './DeviceCard';
import DeviceGrid from './DeviceGrid';
+import { getDeviceListBoundary } from './deviceListBoundary';
import { DeviceGridSkeleton } from './Skeleton';
-import { useDeviceList } from './useDeviceList';
const styles = createStaticStyles(({ css }) => ({
// ─── Onboarding empty state ───
@@ -241,9 +242,10 @@ const DeviceManager = memo<DeviceManagerProps>((props) => {
const { t } = useTranslation('setting');
const isWorkspace = scope === 'workspace';
- // Workspace-keyed SWR fetch — the shared hook every device-listing surface
- // uses (see `useDeviceList` for why the raw TRPC React Query path is wrong).
- const { data, isLoading, isValidating, error, mutate } = useDeviceList();
+ // The device replica every device-listing surface reads (see `useDeviceList`):
+ // a reload paints the persisted cards first, presence pending.
+ const deviceList = useDeviceList();
+ const { data, isValidating, error, mutate } = deviceList;
// `listDevices` is workspace-aware and returns both pools — keep each surface
// to its own scope (and visibility tab). Ghost rows (`visibility: null`,
// online but unregistered) belong to the shared pool: the server already
@@ -252,6 +254,9 @@ const DeviceManager = memo<DeviceManagerProps>((props) => {
const devices = (data ?? []).filter(
(d) => d.scope === scope && (!visibility || (d.visibility ?? 'public') === visibility),
);
+ // A persisted copy with no row for this pool / tab is not proof the pool is
+ // empty: wait for the server (or its error) before showing onboarding.
+ const boundary = getDeviceListBoundary(deviceList, devices.length === 0);
// The machine the user is on right now (desktop only) — personal pool only;
// a workspace device is never "this machine" in the personal sense.
@@ -350,12 +355,12 @@ const DeviceManager = memo<DeviceManagerProps>((props) => {
const list = (
<AsyncBoundary
- data={data}
+ data={boundary.data}
empty={emptyState}
error={error}
errorVariant={'block'}
isEmpty={devices.length === 0}
- isLoading={isLoading}
+ isLoading={boundary.isLoading}
loading={<DeviceGridSkeleton />}
onRetry={() => mutate()}
>
diff --git a/src/features/DeviceManager/DeviceOverview.tsx b/src/features/DeviceManager/DeviceOverview.tsx
index f1f985b50cc..400bd089251 100644
--- a/src/features/DeviceManager/DeviceOverview.tsx
+++ b/src/features/DeviceManager/DeviceOverview.tsx
@@ -244,6 +244,8 @@ const DeviceOverview = ({ canOperate, device }: DeviceOverviewProps) => {
const channels = device.channels ?? [];
const online = channels.length > 0;
+ // The persisted copy carries no channels: presence is unknown, not offline.
+ const presenceUnknown = !!device.onlineUnknown;
const newest = data?.points.at(-1);
const cores = data?.cpuCount ?? null;
@@ -302,7 +304,11 @@ const DeviceOverview = ({ canOperate, device }: DeviceOverviewProps) => {
width: 6,
}}
/>
- {online ? t('devices.status.online') : t('devices.status.offline')}
+ {presenceUnknown
+ ? t('devices.status.checking')
+ : online
+ ? t('devices.status.online')
+ : t('devices.status.offline')}
</span>
</InfoRow>
<InfoRow icon={MonitorIcon} label={t('devices.detail.os')}>
diff --git a/src/features/DeviceManager/connectionCount.test.ts b/src/features/DeviceManager/connectionCount.test.ts
index 705600a46dc..a9beb3b55ac 100644
--- a/src/features/DeviceManager/connectionCount.test.ts
+++ b/src/features/DeviceManager/connectionCount.test.ts
@@ -1,7 +1,16 @@
import type { DeviceListItem } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { getScopedConnectionCount, getWorkspaceConnectionState } from './connectionCount';
+import {
+ getIdleConnectionStatus,
+ getScopedConnectionCount,
+ getWorkspaceConnectionState,
+} from './connectionCount';
+
+/** A `useDeviceList` result; unconfirmed (a stored copy, or nothing yet) unless stated. */
+const listState = (
+ state: { data?: DeviceListItem[]; error?: unknown; isConfirmed?: boolean } = {},
+) => ({ data: undefined, error: undefined, isConfirmed: false, isLoading: false, ...state });
const device = (
deviceId: string,
@@ -54,19 +63,75 @@ describe('getWorkspaceConnectionState', () => {
// The Electron title bar previously converted an undefined device list into a zero count after
// an SWR error, presenting an unverified result as "No workspace device connection is online".
// The unavailable state now preserves the distinction between a failed lookup and an empty list.
- expect(getWorkspaceConnectionState(undefined, false, new Error('network unavailable'))).toBe(
- 'unavailable',
- );
+ expect(
+ getWorkspaceConnectionState(listState({ error: new Error('network unavailable') })),
+ ).toBe('unavailable');
});
/** @example Cached presence remains useful when a background revalidation request fails. */
it('uses cached device presence during a revalidation error', () => {
expect(
getWorkspaceConnectionState(
- [device('workspace-device', 'workspace', 1)],
- false,
- new Error('revalidation failed'),
+ listState({
+ data: [device('workspace-device', 'workspace', 1)],
+ error: new Error('revalidation failed'),
+ isConfirmed: true,
+ }),
),
).toBe('connected');
});
+
+ it('reports disconnected once the server confirms no live workspace connection', () => {
+ expect(
+ getWorkspaceConnectionState(
+ listState({ data: [device('workspace-device', 'workspace', 0)], isConfirmed: true }),
+ ),
+ ).toBe('disconnected');
+ });
+});
+
+describe('persisted rows before the server confirms presence', () => {
+ const persisted = (deviceId: string, scope: DeviceListItem['scope']): DeviceListItem => ({
+ ...device(deviceId, scope, 0),
+ online: false,
+ onlineUnknown: true,
+ });
+
+ /** @example A reload paints the stored list with no channels; that is not "0 connections". */
+ it('reports no count while a matching row is still the persisted copy', () => {
+ expect(getScopedConnectionCount([persisted('workspace-a', 'workspace')], 'workspace')).toBe(
+ undefined,
+ );
+ // An unrelated scope's placeholder does not hide a confirmed count.
+ expect(
+ getScopedConnectionCount(
+ [persisted('workspace-a', 'workspace'), device('personal-a', 'personal', 1)],
+ 'personal',
+ ),
+ ).toBe(1);
+ });
+
+ it('reads the workspace as connecting, not disconnected, until presence is confirmed', () => {
+ const devices = [persisted('workspace-a', 'workspace')];
+
+ expect(getWorkspaceConnectionState(listState({ data: devices }))).toBe('connecting');
+ expect(
+ getWorkspaceConnectionState(listState({ data: devices, error: new Error('offline') })),
+ ).toBe('unavailable');
+ });
+
+ /** @example A stale (or capped) stored copy holding only personal rows is not an empty pool. */
+ it('keeps a stored copy without workspace rows pending until the server answers', () => {
+ const devices = [persisted('personal-a', 'personal')];
+
+ expect(getWorkspaceConnectionState(listState({ data: devices }))).toBe('connecting');
+ expect(
+ getWorkspaceConnectionState(listState({ data: devices, error: new Error('offline') })),
+ ).toBe('unavailable');
+ });
+
+ it('says checking, not offline, for a persisted row with no connection', () => {
+ expect(getIdleConnectionStatus(persisted('dev-a', 'personal'))).toBe('checking');
+ expect(getIdleConnectionStatus(device('dev-a', 'personal', 0))).toBe('offline');
+ });
});
diff --git a/src/features/DeviceManager/connectionCount.ts b/src/features/DeviceManager/connectionCount.ts
index a73381a034b..be57f94b9bb 100644
--- a/src/features/DeviceManager/connectionCount.ts
+++ b/src/features/DeviceManager/connectionCount.ts
@@ -1,5 +1,7 @@
import type { DeviceListItem, DeviceScope } from '@lobechat/types';
+import type { DeviceListResult } from '@/store/device';
+
/**
* Counts live connections within one principal scope.
*
@@ -11,7 +13,9 @@ import type { DeviceListItem, DeviceScope } from '@lobechat/types';
* - Device channels were already filtered by the server for the active principal
*
* Returns:
- * - The number of live connections in the requested scope and optional device
+ * - The number of live connections in the requested scope and optional device,
+ * or `undefined` while a matching row is still the persisted copy
+ * (`onlineUnknown`), whose empty channels are a placeholder, not a count
*/
export const getScopedConnectionCount = (
devices: DeviceListItem[] | undefined,
@@ -20,9 +24,12 @@ export const getScopedConnectionCount = (
): number | undefined => {
if (!devices) return undefined;
- return devices
- .filter((device) => device.scope === scope && (!deviceId || device.deviceId === deviceId))
- .reduce((count, device) => count + device.channels.length, 0);
+ const matched = devices.filter(
+ (device) => device.scope === scope && (!deviceId || device.deviceId === deviceId),
+ );
+ if (matched.some((device) => device.onlineUnknown)) return undefined;
+
+ return matched.reduce((count, device) => count + device.channels.length, 0);
};
/**
@@ -33,18 +40,38 @@ export const getScopedConnectionCount = (
* - Cached presence may remain available while background revalidation fails
*
* Expects:
- * - `devices` is already scoped to the active workspace by the caller's data hook
+ * - The `useDeviceList` result, already scoped to the active workspace
*
* Returns:
- * - A presentation state that distinguishes unavailable data from an authoritative empty list
+ * - A presentation state that distinguishes unavailable data from an authoritative empty list.
+ * Until the server confirms the list, a restored copy says nothing: its
+ * workspace rows carry unknown presence, and a copy without any (stale, or
+ * past the persisted-row cap) is not proof the pool is empty.
*/
-export const getWorkspaceConnectionState = (
- devices: DeviceListItem[] | undefined,
- isLoading: boolean,
- error: unknown,
-): 'connected' | 'connecting' | 'disconnected' | 'unavailable' => {
+export const getWorkspaceConnectionState = ({
+ data: devices,
+ error,
+ isConfirmed,
+ isLoading,
+}: Pick<DeviceListResult, 'data' | 'error' | 'isConfirmed' | 'isLoading'>):
+ 'connected' | 'connecting' | 'disconnected' | 'unavailable' => {
if (!devices && error) return 'unavailable';
if (!devices && isLoading) return 'connecting';
- return getScopedConnectionCount(devices, 'workspace') ? 'connected' : 'disconnected';
+ const count = getScopedConnectionCount(devices, 'workspace');
+ if (devices && (count === undefined || !isConfirmed)) return error ? 'unavailable' : 'connecting';
+
+ return count ? 'connected' : 'disconnected';
};
+
+/**
+ * What a device with no live connection says about it.
+ *
+ * Returns:
+ * - `checking` for a persisted row the server has not confirmed yet
+ * (`onlineUnknown`): its empty channels are a placeholder, not "offline"
+ * - `offline` once the server reported the device without a connection
+ */
+export const getIdleConnectionStatus = (
+ device: Pick<DeviceListItem, 'onlineUnknown'>,
+): 'checking' | 'offline' => (device.onlineUnknown ? 'checking' : 'offline');
diff --git a/src/features/DeviceManager/const.ts b/src/features/DeviceManager/const.ts
index 2799e3025c9..3215fe56a8f 100644
--- a/src/features/DeviceManager/const.ts
+++ b/src/features/DeviceManager/const.ts
@@ -1,13 +1,7 @@
-import { mutate } from '@/libs/swr';
+import { getDeviceStoreState } from '@/store/device';
/**
- * SWR cache key for the device list. Fetched via `useClientDataSWR`, which
- * augments the key with the active workspace id (`[KEY, workspaceId]`) so the
- * personal and per-workspace device pools never share a cache entry. Always an
- * array so the augmented and personal forms match the same prefix.
+ * Re-fetch the device list. It lives in the device store's replica, which is
+ * partitioned by user + workspace, so this refreshes whichever pool is active.
*/
-export const DEVICE_LIST_SWR_KEY = 'device/listDevices';
-
-/** Revalidate the device list across whichever workspace context is active. */
-export const refreshDeviceList = () =>
- mutate((key: unknown) => Array.isArray(key) && key[0] === DEVICE_LIST_SWR_KEY);
+export const refreshDeviceList = () => getDeviceStoreState().refreshDevices();
diff --git a/src/features/DeviceManager/deviceHoverSummary.test.ts b/src/features/DeviceManager/deviceHoverSummary.test.ts
index 07f66e7b926..5abf1bcc971 100644
--- a/src/features/DeviceManager/deviceHoverSummary.test.ts
+++ b/src/features/DeviceManager/deviceHoverSummary.test.ts
@@ -45,6 +45,7 @@ describe('buildDeviceHoverSummary', () => {
lastConnectedAt: '2026-10-15T10:00:00.000Z',
memoryTotalBytes: 32 * 1024 ** 3,
online: true,
+ onlineUnknown: false,
platformLabel: 'Linux',
workingDir: '/home/dev/project',
});
@@ -76,6 +77,14 @@ describe('buildDeviceHoverSummary', () => {
});
});
+ it('marks a persisted row presence-unknown instead of offline', () => {
+ const summary = buildDeviceHoverSummary(
+ makeDevice({ channels: [], online: false, onlineUnknown: true }),
+ );
+
+ expect(summary).toMatchObject({ online: false, onlineUnknown: true });
+ });
+
it('leaves specs empty before the metric series loads', () => {
const summary = buildDeviceHoverSummary(makeDevice());
diff --git a/src/features/DeviceManager/deviceHoverSummary.ts b/src/features/DeviceManager/deviceHoverSummary.ts
index 985efcaf701..e2196f8eaf0 100644
--- a/src/features/DeviceManager/deviceHoverSummary.ts
+++ b/src/features/DeviceManager/deviceHoverSummary.ts
@@ -17,6 +17,8 @@ export interface DeviceHoverSummary {
lastConnectedAt: string;
memoryTotalBytes?: number;
online: boolean;
+ /** A persisted row the server has not confirmed: `online` is a placeholder. */
+ onlineUnknown: boolean;
platformLabel?: string;
workingDir?: string;
}
@@ -43,6 +45,7 @@ export const buildDeviceHoverSummary = (
lastConnectedAt: channels[0]?.connectedAt ?? device.lastSeen,
memoryTotalBytes: series?.memoryTotalBytes || undefined,
online: device.online,
+ onlineUnknown: !!device.onlineUnknown,
platformLabel: getPlatformLabel(device.platform),
workingDir: device.defaultCwd || undefined,
};
diff --git a/src/features/DeviceManager/deviceListBoundary.test.ts b/src/features/DeviceManager/deviceListBoundary.test.ts
new file mode 100644
index 00000000000..a4f26497e5e
--- /dev/null
+++ b/src/features/DeviceManager/deviceListBoundary.test.ts
@@ -0,0 +1,69 @@
+import type { DeviceListItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { deviceDetailKey, getDeviceListBoundary } from './deviceListBoundary';
+
+const rows = [{ deviceId: 'dev-2', scope: 'personal' }] as DeviceListItem[];
+
+const list = (overrides: Partial<Parameters<typeof getDeviceListBoundary>[0]> = {}) => ({
+ data: rows,
+ error: undefined,
+ isConfirmed: false,
+ isLoading: false,
+ isValidating: true,
+ ...overrides,
+});
+
+describe('getDeviceListBoundary', () => {
+ it('keeps an unconfirmed copy with nothing to show loading, not empty', () => {
+ // e.g. the restored copy has no row for this pool, or misses the opened device.
+ expect(getDeviceListBoundary(list(), true)).toEqual({ data: undefined, isLoading: true });
+ });
+
+ it('lets a failed refresh over an unconfirmed empty copy reach the error state', () => {
+ expect(
+ getDeviceListBoundary(list({ error: new Error('boom'), isValidating: false }), true),
+ ).toEqual({ data: undefined, isLoading: false });
+ });
+
+ it('shows the retry in flight as loading', () => {
+ expect(getDeviceListBoundary(list({ error: new Error('boom') }), true)).toEqual({
+ data: undefined,
+ isLoading: true,
+ });
+ });
+
+ it('treats an empty result as empty once the server confirmed the list', () => {
+ expect(getDeviceListBoundary(list({ isConfirmed: true, isValidating: false }), true)).toEqual({
+ data: rows,
+ isLoading: false,
+ });
+ });
+
+ it('paints restored rows straight away', () => {
+ expect(getDeviceListBoundary(list(), false)).toEqual({ data: rows, isLoading: false });
+ });
+
+ it('keeps settled rows when a background refresh fails', () => {
+ expect(
+ getDeviceListBoundary(
+ list({ error: new Error('boom'), isConfirmed: true, isValidating: false }),
+ false,
+ ),
+ ).toEqual({ data: rows, isLoading: false });
+ });
+});
+
+describe('deviceDetailKey', () => {
+ it('remounts the detail once the server confirms a stored row', () => {
+ expect(deviceDetailKey('dev-1', false)).not.toBe(deviceDetailKey('dev-1', true));
+ });
+
+ it('keeps one mount across refreshes of a confirmed row', () => {
+ expect(deviceDetailKey('dev-1', true)).toBe(deviceDetailKey('dev-1', true));
+ });
+
+ it('remounts when the route moves to another device', () => {
+ expect(deviceDetailKey('dev-1', true)).not.toBe(deviceDetailKey('dev-2', true));
+ });
+});
diff --git a/src/features/DeviceManager/deviceListBoundary.ts b/src/features/DeviceManager/deviceListBoundary.ts
new file mode 100644
index 00000000000..cd2979247fc
--- /dev/null
+++ b/src/features/DeviceManager/deviceListBoundary.ts
@@ -0,0 +1,39 @@
+import type { DeviceListItem } from '@lobechat/types';
+
+import type { DeviceListResult } from '@/store/device';
+
+type BoundaryInput = Pick<
+ DeviceListResult,
+ 'data' | 'error' | 'isConfirmed' | 'isLoading' | 'isValidating'
+>;
+
+/**
+ * `AsyncBoundary`'s `data` / `isLoading` for a device page that shows part of
+ * the list (one pool, one device).
+ *
+ * A reload restores the list from storage before the server answers, and that
+ * copy may be stale or miss rows — so `isEmpty` (no device in this pool, the
+ * opened device missing) only counts once the server confirmed the list.
+ * Before that the surface stays loading, and a failed refresh reaches the
+ * error state instead of settling on onboarding or "not found".
+ */
+export const getDeviceListBoundary = (
+ list: BoundaryInput,
+ isEmpty: boolean,
+): { data: DeviceListItem[] | undefined; isLoading: boolean } => {
+ const isPending = !list.isConfirmed && isEmpty;
+
+ return {
+ data: isPending ? undefined : list.data,
+ isLoading: list.isLoading || (isPending && (!list.error || list.isValidating)),
+ };
+};
+
+/**
+ * React key for the device detail. It seeds its rename / cwd drafts from the
+ * row on mount, so it remounts when the route moves to another device and once
+ * the server confirms a row that was painted from storage — drafts seeded from
+ * a stale stored row would otherwise write the old name or `workingDirs` back.
+ */
+export const deviceDetailKey = (deviceId: string, isConfirmed: boolean): string =>
+ `${deviceId}:${isConfirmed ? 'server' : 'stored'}`;
diff --git a/src/features/DeviceManager/index.ts b/src/features/DeviceManager/index.ts
index 8bf06f170e8..96b7354c3ef 100644
--- a/src/features/DeviceManager/index.ts
+++ b/src/features/DeviceManager/index.ts
@@ -1,4 +1,3 @@
export { default as DeviceConnectModal } from './DeviceConnectModal';
export { default as DeviceDetailPage } from './DeviceDetailPage';
export { default as DeviceManager } from './DeviceManager';
-export { useDeviceList } from './useDeviceList';
diff --git a/src/features/DeviceManager/useDeviceActivityText.ts b/src/features/DeviceManager/useDeviceActivityText.ts
index 450416eeb09..f11bce8c3d3 100644
--- a/src/features/DeviceManager/useDeviceActivityText.ts
+++ b/src/features/DeviceManager/useDeviceActivityText.ts
@@ -19,11 +19,16 @@ import { useTranslation } from 'react-i18next';
*
* A single connection drops the "1 connection" count — it is the common case
* and would truncate a narrow line.
+ *
+ * A row restored from the persisted list (`onlineUnknown`) has no channels by
+ * construction, so it reads as "checking" rather than as offline.
*/
export const useDeviceActivityText = (device: DeviceListItem) => {
const { t } = useTranslation('setting');
const channels = device.channels ?? [];
+ if (device.onlineUnknown) return t('devices.status.checking');
+
if (channels.length === 0)
return t('devices.lastSeen', { time: dayjs(device.lastSeen).fromNow() });
diff --git a/src/features/DeviceManager/useDeviceList.ts b/src/features/DeviceManager/useDeviceList.ts
deleted file mode 100644
index e118fbab98a..00000000000
--- a/src/features/DeviceManager/useDeviceList.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { isDesktop } from '@lobechat/const';
-import type { DeviceListItem } from '@lobechat/types';
-import type { SWRConfiguration, SWRResponse } from 'swr';
-
-import { useClientDataSWR } from '@/libs/swr';
-import { deviceService } from '@/services/device';
-import { useUserStore } from '@/store/user';
-import { authSelectors } from '@/store/user/selectors';
-
-import { DEVICE_LIST_SWR_KEY } from './const';
-
-/**
- * Workspace-aware device list. ALWAYS use this (not
- * `lambdaQuery.device.listDevices.useQuery`) for any surface that lists or
- * resolves devices: `useClientDataSWR` augments the cache key with the active
- * workspace id, so switching workspaces re-fetches into a fresh cache entry.
- * The raw TRPC React Query key has no workspace dimension — a list primed in
- * one workspace kept serving a stale pool after switching, and a
- * fetch primed while the workspace was still resolving stuck for the whole
- * session (the DeviceManager fix this generalizes).
- *
- * Devices come from an authed lambda procedure, so only query once signed in
- * (desktop always queries — it lists the local device's registered cwd).
- *
- * Refresh: `refreshDeviceList()` (`./const`) revalidates every workspace
- * context's entry; the returned `mutate` revalidates just the active one.
- * A live surface that must track presence passes its own `refreshInterval`.
- */
-export const useDeviceList = (
- config?: Pick<SWRConfiguration, 'refreshInterval'>,
-): SWRResponse<DeviceListItem[]> => {
- const isLogin = useUserStore(authSelectors.isLogin);
- return useClientDataSWR<DeviceListItem[]>(
- isLogin || isDesktop ? [DEVICE_LIST_SWR_KEY] : null,
- () => deviceService.listDevices(),
- config,
- );
-};
diff --git a/src/features/Electron/connection/DeviceGateway.tsx b/src/features/Electron/connection/DeviceGateway.tsx
index 320d8a8da79..2c4e10b0ca5 100644
--- a/src/features/Electron/connection/DeviceGateway.tsx
+++ b/src/features/Electron/connection/DeviceGateway.tsx
@@ -9,8 +9,8 @@ import {
getScopedConnectionCount,
getWorkspaceConnectionState,
} from '@/features/DeviceManager/connectionCount';
-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useDeviceList } from '@/store/device';
import { useElectronStore } from '@/store/electron';
import { electronSyncSelectors } from '@/store/electron/selectors';
@@ -67,7 +67,8 @@ const DeviceGateway = memo<DeviceGatewayProps>(({ workspaceScoped }) => {
useFetchGatewayStatus();
useElectronStore((s) => s.useFetchGatewayDeviceInfo)();
const gatewayDeviceInfo = useElectronStore((s) => s.gatewayDeviceInfo);
- const { data: devices, error: deviceListError, isLoading: isDeviceListLoading } = useDeviceList();
+ const deviceList = useDeviceList();
+ const devices = deviceList.data;
useWatchBroadcast('gatewayConnectionStatusChanged', ({ status }) => {
setGatewayConnectionStatus(status);
@@ -97,11 +98,7 @@ const DeviceGateway = memo<DeviceGatewayProps>(({ workspaceScoped }) => {
workspaceScoped ? 'workspace' : 'personal',
workspaceScoped ? undefined : gatewayDeviceInfo?.deviceId,
);
- const workspaceConnectionState = getWorkspaceConnectionState(
- devices,
- isDeviceListLoading,
- deviceListError,
- );
+ const workspaceConnectionState = getWorkspaceConnectionState(deviceList);
const scopeConnected = workspaceScoped ? workspaceConnectionState === 'connected' : isConnected;
const connectionHint = workspaceScoped
? workspaceConnectionState === 'unavailable'
diff --git a/src/features/ExecutionTargetPicker/index.tsx b/src/features/ExecutionTargetPicker/index.tsx
index 07f551d9044..b542272b82f 100644
--- a/src/features/ExecutionTargetPicker/index.tsx
+++ b/src/features/ExecutionTargetPicker/index.tsx
@@ -185,13 +185,23 @@ interface ExecutionTargetDeviceStatusProps {
offlineLabel: string;
online: boolean;
onlineLabel: string;
+ /**
+ * Shown instead of offline for a row restored from the persisted device list
+ * (`onlineUnknown`): its `online: false` is a placeholder until the server
+ * confirms presence.
+ */
+ unknown?: boolean;
+ unknownLabel: string;
}
export const ExecutionTargetDeviceStatus = memo<ExecutionTargetDeviceStatusProps>(
- ({ offlineLabel, online, onlineLabel }) => (
+ ({ offlineLabel, online, onlineLabel, unknown, unknownLabel }) => (
<span className={styles.status}>
- <span aria-hidden className={online ? styles.dotOnline : styles.dotOffline} />
- <span>{online ? onlineLabel : offlineLabel}</span>
+ <span
+ aria-hidden
+ className={unknown ? styles.dotOffline : online ? styles.dotOnline : styles.dotOffline}
+ />
+ <span>{unknown ? unknownLabel : online ? onlineLabel : offlineLabel}</span>
</span>
),
);
diff --git a/src/features/ResourcePermission/useAgentSelectionPolicies.test.ts b/src/features/ResourcePermission/useAgentSelectionPolicies.test.ts
new file mode 100644
index 00000000000..b0db3dea0a4
--- /dev/null
+++ b/src/features/ResourcePermission/useAgentSelectionPolicies.test.ts
@@ -0,0 +1,99 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useAgentSelectionPolicies } from './useAgentSelectionPolicies';
+
+const state = vi.hoisted(() => ({
+ agent: {
+ agencyConfig: {
+ boundDeviceId: 'ws-device',
+ executionTarget: 'device',
+ executionTargetSelectionPolicy: 'member',
+ },
+ id: 'agent-1',
+ userId: 'user-1',
+ } as Record<string, unknown>,
+ deviceList: { data: [] as unknown[], isConfirmed: false },
+ updateAgentConfigById: vi.fn(),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: unknown) => unknown) =>
+ selector({ agentMap: {}, updateAgentConfigById: state.updateAgentConfigById }),
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: { getAgentById: () => () => state.agent },
+}));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/user/selectors', () => ({
+ userProfileSelectors: { userId: () => 'user-1' },
+}));
+vi.mock('@/store/device', () => ({ useDeviceList: () => state.deviceList }));
+
+const workspaceDevice = {
+ channels: [],
+ deviceId: 'ws-device',
+ online: true,
+ scope: 'workspace',
+ visibility: 'public',
+};
+
+describe('useAgentSelectionPolicies', () => {
+ beforeEach(() => {
+ state.updateAgentConfigById.mockReset();
+ });
+
+ it('does not fix the execution target from an unconfirmed device list', () => {
+ // The stored copy still lists a device that may since have been removed.
+ state.deviceList = { data: [workspaceDevice], isConfirmed: false };
+
+ const { result } = renderHook(() => useAgentSelectionPolicies('agent-1'));
+
+ expect(result.current.canFixExecutionTarget).toBe(false);
+ result.current.setExecutionTargetPolicy('fixed');
+ expect(state.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+
+ it('fixes the resolved device once the server confirmed the list', () => {
+ state.deviceList = { data: [workspaceDevice], isConfirmed: true };
+
+ const { result } = renderHook(() => useAgentSelectionPolicies('agent-1'));
+
+ expect(result.current.canFixExecutionTarget).toBe(true);
+ result.current.setExecutionTargetPolicy('fixed');
+ expect(state.updateAgentConfigById).toHaveBeenCalledWith('agent-1', {
+ agencyConfig: expect.objectContaining({
+ boundDeviceId: 'ws-device',
+ executionTargetSelectionPolicy: 'fixed',
+ }),
+ });
+ });
+});
+
+describe('useAgentSelectionPolicies with a non-device target', () => {
+ it('fixes a cloud / no-environment target without waiting for the device list', () => {
+ state.agent = {
+ ...state.agent,
+ agencyConfig: { executionTarget: 'none', executionTargetSelectionPolicy: 'member' },
+ };
+ state.deviceList = { data: [], isConfirmed: false };
+ state.updateAgentConfigById.mockReset();
+
+ const { result } = renderHook(() => useAgentSelectionPolicies('agent-1'));
+
+ expect(result.current.canFixExecutionTarget).toBe(true);
+ result.current.setExecutionTargetPolicy('fixed');
+ expect(state.updateAgentConfigById).toHaveBeenCalledWith('agent-1', {
+ agencyConfig: expect.objectContaining({
+ executionTarget: 'none',
+ executionTargetSelectionPolicy: 'fixed',
+ }),
+ });
+ });
+});
diff --git a/src/features/ResourcePermission/useAgentSelectionPolicies.ts b/src/features/ResourcePermission/useAgentSelectionPolicies.ts
index 77e2cbca4e5..9b370fb352c 100644
--- a/src/features/ResourcePermission/useAgentSelectionPolicies.ts
+++ b/src/features/ResourcePermission/useAgentSelectionPolicies.ts
@@ -7,7 +7,6 @@ import type {
} from '@lobechat/types';
import { useCallback, useMemo } from 'react';
-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import {
groupExecutionTargetDevices,
resolveExecutionTargetSelection,
@@ -16,6 +15,7 @@ import { isHeterogeneousSandboxExecutionAvailable } from '@/helpers/executionTar
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useDeviceList } from '@/store/device';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
@@ -68,7 +68,7 @@ export const useAgentSelectionPolicies = (agentId: string): AgentSelectionPolici
const { allowed: isWorkspaceOwner } = usePermission('edit_others_content');
const viewerId = useUserStore(userProfileSelectors.userId);
- const { data: devices } = useDeviceList();
+ const { data: devices, isConfirmed: isDeviceListConfirmed } = useDeviceList();
const publicWorkspaceDevices = useMemo(
() => groupExecutionTargetDevices(devices).publicWorkspace,
[devices],
@@ -83,6 +83,15 @@ export const useAgentSelectionPolicies = (agentId: string): AgentSelectionPolici
isHeterogeneous: !!heterogeneousType,
});
+ // The selection resolves against the device list; a stored copy may still
+ // hold devices that were since deleted or unshared, so fixing waits for the
+ // server's list rather than pin an unresolvable machine for every member.
+ const canFixSelection =
+ !!executionSelection &&
+ (executionSelection.target !== 'device' || isDeviceListConfirmed) &&
+ (executionSelection.target !== 'sandbox' ||
+ isHeterogeneousSandboxExecutionAvailable(heterogeneousType));
+
const saveAgencyConfig = useCallback(
(patch: Partial<LobeAgentAgencyConfig>) =>
updateAgentConfigById(agentId, { agencyConfig: patch }),
@@ -97,7 +106,7 @@ export const useAgentSelectionPolicies = (agentId: string): AgentSelectionPolici
}
// Fixing pins whatever is selected right now, so a run can't fall back to
// a target the author never chose.
- if (!executionSelection) return;
+ if (!canFixSelection) return;
void saveAgencyConfig({
...(executionSelection.deviceId ? { boundDeviceId: executionSelection.deviceId } : {}),
@@ -105,7 +114,7 @@ export const useAgentSelectionPolicies = (agentId: string): AgentSelectionPolici
executionTargetSelectionPolicy: 'fixed',
});
},
- [executionSelection, saveAgencyConfig],
+ [canFixSelection, executionSelection, saveAgencyConfig],
);
const setModelPolicy = useCallback(
@@ -123,10 +132,7 @@ export const useAgentSelectionPolicies = (agentId: string): AgentSelectionPolici
// the values shown above come from the same row, so there is nothing
// meaningful to edit until it loads.
canEditPolicies: isWorkspaceOwner || (!!agent?.userId && agent.userId === viewerId),
- canFixExecutionTarget:
- !!executionSelection &&
- (executionSelection.target !== 'sandbox' ||
- isHeterogeneousSandboxExecutionAvailable(heterogeneousType)),
+ canFixExecutionTarget: canFixSelection,
executionTargetPolicy: agencyConfig?.executionTargetSelectionPolicy ?? 'member',
modelPolicy: agencyConfig?.modelSelectionPolicy ?? 'member',
setExecutionTargetPolicy,
diff --git a/src/hooks/useRemoteAgentDeviceGuard.test.ts b/src/hooks/useRemoteAgentDeviceGuard.test.ts
index eced2272818..9303f9a3867 100644
--- a/src/hooks/useRemoteAgentDeviceGuard.test.ts
+++ b/src/hooks/useRemoteAgentDeviceGuard.test.ts
@@ -1,8 +1,22 @@
-import { renderHook, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+/**
+ * @vitest-environment happy-dom
+ */
+import { randomUUID } from 'node:crypto';
+
+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 { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
import { deviceService } from '@/services/device';
+import { useDeviceStore } from '@/store/device';
+import { initialState } from '@/store/device/initialState';
+import { deviceListResource } from '@/store/device/projection';
+import { useUserStore } from '@/store/user';
import { useRemoteAgentDeviceGuard } from './useRemoteAgentDeviceGuard';
@@ -15,9 +29,131 @@ const mockedUseEffectiveAgencyConfig = vi.mocked(useEffectiveAgencyConfig);
const mockedCheckCapability = vi.mocked(deviceService.checkCapability);
const mockedListDevices = vi.mocked(deviceService.listDevices);
+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 ROW_KEY = deviceListResource.storageKey({});
+
+const bindCodexTo = (boundDeviceId: string) =>
+ mockedUseEffectiveAgencyConfig.mockReturnValue({
+ agencyConfig: {
+ boundDeviceId,
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'codex' },
+ },
+ canDisplayExecutionTarget: true,
+ canSelectExecutionTarget: true,
+ isPreferenceLoading: false,
+ workspaceScoped: false,
+ });
+
describe('useRemoteAgentDeviceGuard', () => {
+ let scope = '';
+
beforeEach(() => {
vi.clearAllMocks();
+ scope = `guard-user-${randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ act(() => {
+ useDeviceStore.setState(initialState);
+ useUserStore.setState({ isSignedIn: true });
+ });
+ });
+
+ afterEach(async () => {
+ await deviceListResource.storage!.remove({ queryKey: ROW_KEY, scope });
+ vi.restoreAllMocks();
+ });
+
+ it('reads the shared device list instead of requesting it again', async () => {
+ bindCodexTo('my-device');
+ mockedListDevices.mockResolvedValue([{ deviceId: 'my-device', online: true }] as never);
+
+ const { result } = renderHook(
+ () => {
+ // The chat input's device switcher reads the same list next to the guard.
+ useDeviceStore((s) => s.useFetchDevices)(true);
+ return useRemoteAgentDeviceGuard({ agentId: 'agent-1' });
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.status).toBe('ok'));
+ expect(mockedListDevices).toHaveBeenCalledTimes(1);
+ });
+
+ it('treats a persisted row as unknown, not offline, until the server confirms it', async () => {
+ bindCodexTo('my-device');
+ await deviceListResource.storage!.set(
+ { queryKey: ROW_KEY, scope },
+ { data: [{ channels: [], deviceId: 'my-device', online: true }] as never, updatedAt: 1 },
+ );
+ let answer: (devices: never) => void = () => {};
+ mockedListDevices.mockImplementation(() => new Promise((resolve) => (answer = resolve)));
+
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }), {
+ wrapper,
+ });
+
+ // The stored row reads `online: false`; that must not raise the offline banner.
+ await waitFor(() =>
+ expect(useDeviceStore.getState().deviceListMap.all?.[0]?.onlineUnknown).toBe(true),
+ );
+ expect(result.current.status).toBe('checking');
+
+ act(() => answer([{ deviceId: 'my-device', online: true }] as never));
+ await waitFor(() => expect(result.current.status).toBe('ok'));
+ });
+
+ it('allows sending when the device list cannot be read', async () => {
+ bindCodexTo('my-device');
+ mockedListDevices.mockRejectedValue(new Error('network down'));
+
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(result.current.status).toBe('ok'));
+ });
+
+ it('allows sending when a refresh fails over a confirmed offline row', async () => {
+ mockedUseEffectiveAgencyConfig.mockReturnValue({
+ agencyConfig: {
+ boundDeviceId: 'my-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ },
+ canDisplayExecutionTarget: true,
+ canSelectExecutionTarget: true,
+ isPreferenceLoading: false,
+ workspaceScoped: false,
+ });
+ mockedListDevices.mockResolvedValue([{ deviceId: 'my-device', online: false }] as never);
+
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }), {
+ wrapper,
+ });
+ await waitFor(() => expect(result.current.status).toBe('device-offline'));
+
+ // A focus / manual re-check that cannot reach the server must not keep the
+ // composer blocked on the earlier answer.
+ mockedListDevices.mockRejectedValue(new Error('network down'));
+ act(() => result.current.refresh());
+
+ await waitFor(() => expect(result.current.status).toBe('ok'));
});
it('checks the EFFECTIVE bound device (with the caller override merged)', async () => {
@@ -40,7 +176,9 @@ describe('useRemoteAgentDeviceGuard', () => {
{ deviceId: 'my-device', online: true },
] as never);
- const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }), {
+ wrapper,
+ });
await waitFor(() => expect(result.current.status).toBe('ok'));
});
@@ -59,7 +197,9 @@ describe('useRemoteAgentDeviceGuard', () => {
});
mockedListDevices.mockResolvedValue([{ deviceId: 'my-device', online: false }] as never);
- const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }), {
+ wrapper,
+ });
await waitFor(() => expect(result.current.status).toBe('device-offline'));
});
@@ -77,7 +217,9 @@ describe('useRemoteAgentDeviceGuard', () => {
});
mockedListDevices.mockResolvedValue([]);
- const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }), {
+ wrapper,
+ });
await waitFor(() => expect(result.current.status).toBe('ok'));
expect(mockedCheckCapability).not.toHaveBeenCalled();
@@ -100,7 +242,9 @@ describe('useRemoteAgentDeviceGuard', () => {
] as never);
mockedCheckCapability.mockResolvedValue({ available: true });
- const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }), {
+ wrapper,
+ });
await waitFor(() => expect(result.current.status).toBe('ok'));
expect(mockedCheckCapability).toHaveBeenCalledWith({
@@ -122,11 +266,16 @@ describe('useRemoteAgentDeviceGuard', () => {
isPreferenceLoading: true,
workspaceScoped: true,
});
+ // The shared row's device reads offline — not this member's pick, so no banner.
+ mockedListDevices.mockResolvedValue([{ deviceId: 'creator-device', online: false }] as never);
- const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }), {
+ wrapper,
+ });
+ await waitFor(() => expect(mockedListDevices).toHaveBeenCalled());
await waitFor(() => expect(result.current.status).toBe('checking'));
- expect(mockedListDevices).not.toHaveBeenCalled();
+ expect(mockedCheckCapability).not.toHaveBeenCalled();
});
it('reports no-device when nothing is bound', async () => {
@@ -138,7 +287,9 @@ describe('useRemoteAgentDeviceGuard', () => {
workspaceScoped: false,
});
- const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }), {
+ wrapper,
+ });
await waitFor(() => expect(result.current.status).toBe('no-device'));
});
@@ -162,8 +313,9 @@ describe('useRemoteAgentDeviceGuard', () => {
{ deviceId: 'pane-device', online: true },
] as never);
- const { result } = renderHook(() =>
- useRemoteAgentDeviceGuard({ agentId: 'agent-1', topicId: 'pane-topic' }),
+ const { result } = renderHook(
+ () => useRemoteAgentDeviceGuard({ agentId: 'agent-1', topicId: 'pane-topic' }),
+ { wrapper },
);
await waitFor(() => expect(result.current.status).toBe('ok'));
diff --git a/src/hooks/useRemoteAgentDeviceGuard.ts b/src/hooks/useRemoteAgentDeviceGuard.ts
index 9337422e4bd..504b2a23dd9 100644
--- a/src/hooks/useRemoteAgentDeviceGuard.ts
+++ b/src/hooks/useRemoteAgentDeviceGuard.ts
@@ -3,6 +3,12 @@ import { useCallback, useEffect, useState } from 'react';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { deviceService } from '@/services/device';
+import {
+ deviceSelectors,
+ isDevicePresenceUnknown,
+ useDeviceList,
+ useDeviceStore,
+} from '@/store/device';
export type RemoteAgentDeviceStatus =
'checking' | 'device-offline' | 'no-device' | 'ok' | 'platform-unavailable';
@@ -43,71 +49,84 @@ export const useRemoteAgentDeviceGuard = ({
const boundDeviceId = agencyConfig?.boundDeviceId;
const providerType = agencyConfig?.heterogeneousProvider?.type;
- const [status, setStatus] = useState<RemoteAgentDeviceStatus>('checking');
-
- const check = useCallback(async () => {
- if (!enabled) return;
-
- // The override hasn't loaded yet — `boundDeviceId` may still be the shared
- // row's device. Stay in `checking` (non-blocking) rather than flash an
- // offline banner for a device this member never picked; the load flips
- // `isPreferenceLoading` and re-runs the check.
- if (isPreferenceLoading) {
- setStatus('checking');
- return;
- }
-
- if (!boundDeviceId) {
- setStatus('no-device');
- return;
- }
-
- setStatus('checking');
-
- try {
- const devices = await deviceService.listDevices();
- const device = devices.find((d) => d.deviceId === boundDeviceId);
-
- // A shared/legacy binding may point at the author's personal principal,
- // which is intentionally absent from the caller-scoped device list. The
- // server owns that routing decision; absence here is not proof of offline.
- if (!device) {
- setStatus('ok');
- return;
- }
-
- if (!device.online) {
- setStatus('device-offline');
- return;
- }
-
- if (providerType && isRemoteHeterogeneousType(providerType)) {
- const capability = await deviceService.checkCapability({
- deviceId: boundDeviceId,
- platform: providerType,
- scope: device.scope,
- });
- setStatus(capability.available ? 'ok' : 'platform-unavailable');
- } else {
- setStatus('ok');
- }
- } catch {
- // On error, allow sending — don't block user on network issues
- setStatus('ok');
- }
- }, [enabled, isPreferenceLoading, boundDeviceId, providerType]);
+ // The device list is the shared replica every device surface reads — one
+ // request per scope, revalidated on focus — not a request of this guard's own.
+ const { data: devices, error: deviceListError, mutate: refreshDevices } = useDeviceList();
+ const device = boundDeviceId ? devices?.find((d) => d.deviceId === boundDeviceId) : undefined;
+ // A persisted copy painted before the server answered: its rows say nothing
+ // about presence, and a device missing from it may simply be newer than it.
+ const isListConfirmed = useDeviceStore(deviceSelectors.isDeviceListConfirmed);
+ // Notify-based platforms must also be available on the device.
+ const remoteType =
+ providerType && isRemoteHeterogeneousType(providerType) ? providerType : undefined;
+
+ const listStatus = ((): RemoteAgentDeviceStatus | 'capability' => {
+ // Disabled, or the override hasn't loaded yet — `boundDeviceId` may still
+ // be the shared row's device. Stay in `checking` (non-blocking) rather than
+ // flash an offline banner for a device this member never picked.
+ if (!enabled || isPreferenceLoading) return 'checking';
+ if (!boundDeviceId) return 'no-device';
+ // The last list request failed: whatever presence the store still holds
+ // (stored copy or an earlier answer) may be stale. Allow sending rather
+ // than block the user on a network issue.
+ if (deviceListError) return 'ok';
+ if (!isListConfirmed || (device && isDevicePresenceUnknown(device))) return 'checking';
+ // A shared/legacy binding may point at the author's personal principal,
+ // which is intentionally absent from the caller-scoped device list. The
+ // server owns that routing decision; absence here is not proof of offline.
+ if (!device) return 'ok';
+ if (!device.online) return 'device-offline';
+ return remoteType ? 'capability' : 'ok';
+ })();
+
+ // Platform availability is a live probe of the device, so it stays a request
+ // of its own, re-run when the window regains focus.
+ const [capability, setCapability] = useState<{ available: boolean; key: string }>();
+ const [probeRound, setProbeRound] = useState(0);
+ const probe = listStatus === 'capability' ? device : undefined;
+ const probeDeviceId = probe?.deviceId;
+ const probeScope = probe?.scope;
+ const capabilityKey = probe ? `${probeDeviceId}:${probeScope}:${remoteType}` : '';
useEffect(() => {
- void check();
- }, [check]);
+ if (!probeDeviceId || !remoteType) return;
+ let cancelled = false;
+ const key = `${probeDeviceId}:${probeScope}:${remoteType}`;
+ deviceService
+ .checkCapability({ deviceId: probeDeviceId, platform: remoteType, scope: probeScope })
+ .then(
+ (result) => !cancelled && setCapability({ available: result.available, key }),
+ // On error, allow sending — don't block the user on network issues.
+ () => !cancelled && setCapability({ available: true, key }),
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, [probeDeviceId, probeScope, remoteType, probeRound]);
+
+ const refresh = useCallback(() => {
+ void refreshDevices();
+ setProbeRound((round) => round + 1);
+ }, [refreshDevices]);
// Re-check when window regains focus
useEffect(() => {
if (!enabled) return;
- const handler = () => void check();
+ const handler = () => {
+ if (document.visibilityState === 'visible') refresh();
+ };
document.addEventListener('visibilitychange', handler);
return () => document.removeEventListener('visibilitychange', handler);
- }, [enabled, check]);
-
- return { refresh: () => void check(), status };
+ }, [enabled, refresh]);
+
+ const status: RemoteAgentDeviceStatus =
+ listStatus !== 'capability'
+ ? listStatus
+ : capability?.key !== capabilityKey
+ ? 'checking'
+ : capability.available
+ ? 'ok'
+ : 'platform-unavailable';
+
+ return { refresh, status };
};
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
index 400a14c89fa..ed8f51a6029 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
@@ -25,9 +25,12 @@ import { BotIcon, CheckCircle2, MonitorSmartphone, RefreshCw, XCircle } from 'lu
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
+import AsyncError from '@/components/AsyncError';
import { deviceService } from '@/services/device';
import { useAgentStore } from '@/store/agent';
+import { isDevicePresenceUnknown, useDeviceList } from '@/store/device';
+
+import { getBoundDevicePresence, getDeviceSelectState } from './boundDevicePresence';
const styles = createStaticStyles(({ css }) => ({
card: css`
@@ -110,10 +113,25 @@ const ChangeDeviceContent = memo<ChangeDeviceContentProps>(
setCanDismissByClickOutside(!saving);
}, [saving, setCanDismissByClickOutside]);
- // Workspace-keyed SWR fetch (see useDeviceList) — the raw lambdaQuery key
- // has no workspace dimension, so the list went stale across workspace
- // switches.
- const { data: devices, isLoading: loadingDevices } = useDeviceList();
+ // The shared device replica (see useDeviceList), partitioned by workspace.
+ const {
+ data: devices,
+ error: deviceListError,
+ isConfirmed,
+ isLoading: loadingDevices,
+ isValidating: validatingDevices,
+ mutate: refreshDevices,
+ } = useDeviceList();
+ // Only online devices are offered, and neither a stored row's presence nor
+ // a stored copy's missing rows are known until the server confirms the list
+ // — keep the picker loading until then.
+ const selectState = getDeviceSelectState({
+ error: deviceListError,
+ hasUnknownPresence: (devices ?? []).some(isDevicePresenceUnknown),
+ isConfirmed,
+ isLoading: loadingDevices,
+ isValidating: validatingDevices,
+ });
const onlineDevices = (devices ?? []).filter(
(d) =>
@@ -165,7 +183,7 @@ const ChangeDeviceContent = memo<ChangeDeviceContentProps>(
<Flexbox gap={16}>
<Flexbox gap={12} paddingBlock={'12px 4px'}>
<Select
- loading={loadingDevices}
+ loading={selectState === 'loading'}
placeholder={t('platformAgentConfig.selectDevice')}
style={{ width: '100%' }}
value={selectedDeviceId}
@@ -183,6 +201,13 @@ const ChangeDeviceContent = memo<ChangeDeviceContentProps>(
}))}
onChange={handleDeviceSelect}
/>
+ {selectState === 'error' && (
+ <AsyncError
+ error={deviceListError}
+ variant={'inline'}
+ onRetry={() => void refreshDevices()}
+ />
+ )}
{checkingCapability && (
<Tag style={{ marginInlineEnd: 0 }}>
{t('platformAgentConfig.availability.checking')}
@@ -276,10 +301,12 @@ const RemoteAgentConfigCard = memo<RemoteAgentConfigCardProps>(
const platformName = HETEROGENEOUS_TYPE_LABELS[provider.type] ?? provider.type;
- // Workspace-keyed SWR fetch — see the comment on the sibling call above.
- const { data: devices } = useDeviceList();
+ // The shared device replica — see the comment on the sibling call above.
+ const { data: devices, isConfirmed } = useDeviceList();
const boundDevice = devices?.find((d) => d.deviceId === boundDeviceId);
+ const boundPresence = getBoundDevicePresence(boundDeviceId, boundDevice, isConfirmed);
+ const boundPresenceUnknown = boundPresence === 'checking';
const checkCapability = useCallback(
async (deviceId: string) => {
@@ -323,6 +350,11 @@ const RemoteAgentConfigCard = memo<RemoteAgentConfigCardProps>(
<Tag style={{ marginInlineEnd: 0 }}>{t('platformAgentConfig.availability.noDevice')}</Tag>
);
}
+ if (boundPresenceUnknown) {
+ return (
+ <Tag style={{ marginInlineEnd: 0 }}>{t('platformAgentConfig.availability.checking')}</Tag>
+ );
+ }
if (!boundDevice?.online) {
return (
<Tag color="warning" style={{ marginInlineEnd: 0 }}>
@@ -395,13 +427,19 @@ const RemoteAgentConfigCard = memo<RemoteAgentConfigCardProps>(
color={boundDevice.online ? 'success' : 'default'}
style={{ marginInlineEnd: 0 }}
>
- {boundDevice.online
- ? t('platformAgentConfig.device.online')
- : t('platformAgentConfig.device.offline')}
+ {boundPresenceUnknown
+ ? t('devices.status.checking')
+ : boundDevice.online
+ ? t('platformAgentConfig.device.online')
+ : t('platformAgentConfig.device.offline')}
</Tag>
</Flexbox>
) : (
- <Tag style={{ marginInlineEnd: 0 }}>{t('platformAgentConfig.device.none')}</Tag>
+ <Tag style={{ marginInlineEnd: 0 }}>
+ {boundPresenceUnknown
+ ? t('devices.status.checking')
+ : t('platformAgentConfig.device.none')}
+ </Tag>
)}
</div>
</div>
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx
index ef9f99634d2..5aa492f332b 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx
@@ -19,6 +19,11 @@ const testState = vi.hoisted(() => ({
},
updateAgentConfigById: vi.fn(),
},
+ deviceList: {
+ data: undefined as unknown[] | undefined,
+ isConfirmed: false,
+ isLoading: true,
+ },
mutateDevices: vi.fn(),
}));
@@ -36,11 +41,10 @@ vi.mock('@lobehub/ui', async (importOriginal) => {
};
});
-vi.mock('@/features/DeviceManager/useDeviceList', () => ({
+vi.mock('@/store/device/useDeviceList', () => ({
useDeviceList: () => ({
- data: undefined,
+ ...testState.deviceList,
error: undefined,
- isLoading: true,
mutate: testState.mutateDevices,
}),
}));
@@ -56,6 +60,7 @@ describe('WorkspaceAgentDevicePolicy', () => {
testState.agent.updateAgentConfigById.mockReset();
testState.mutateDevices.mockReset();
selectPropsSpy.mockClear();
+ testState.deviceList = { data: undefined, isConfirmed: false, isLoading: true };
});
it('renders the environment picker without a member-switch control', () => {
@@ -94,3 +99,56 @@ describe('WorkspaceAgentDevicePolicy', () => {
await act(async () => finishSave?.());
});
});
+
+describe('WorkspaceAgentDevicePolicy over an unconfirmed device list', () => {
+ const workspaceDevice = {
+ channels: [],
+ deviceId: 'ws-device',
+ friendlyName: 'Build Server',
+ online: false,
+ onlineUnknown: true,
+ scope: 'workspace',
+ visibility: 'public',
+ };
+
+ const workspaceGroup = () => {
+ const options = (selectPropsSpy.mock.lastCall?.[0] as { options: unknown[] }).options as {
+ options?: { disabled?: boolean; value: string }[];
+ }[];
+ return options.find((option) => option.options)?.options ?? [];
+ };
+
+ beforeEach(() => {
+ selectPropsSpy.mockClear();
+ });
+
+ it('shows stored workspace devices but does not let them be bound yet', () => {
+ testState.deviceList = { data: [workspaceDevice], isConfirmed: false, isLoading: false };
+
+ render(<WorkspaceAgentDevicePolicy agentId="agent-1" />);
+
+ const [option] = workspaceGroup();
+ expect(option.value).toContain('ws-device');
+ expect(option.disabled).toBe(true);
+ });
+
+ it('reads a stored copy without workspace devices as loading, not empty', () => {
+ testState.deviceList = { data: [], isConfirmed: false, isLoading: false };
+
+ render(<WorkspaceAgentDevicePolicy agentId="agent-1" />);
+
+ expect(workspaceGroup().map((option) => option.value)).toEqual(['status:loading']);
+ });
+
+ it('lets a confirmed device be bound', () => {
+ testState.deviceList = {
+ data: [{ ...workspaceDevice, onlineUnknown: undefined }],
+ isConfirmed: true,
+ isLoading: false,
+ };
+
+ render(<WorkspaceAgentDevicePolicy agentId="agent-1" />);
+
+ expect(workspaceGroup()[0].disabled).toBeFalsy();
+ });
+});
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx
index 75c50dbc996..863f48042c9 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.tsx
@@ -9,7 +9,6 @@ import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
-import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import {
ExecutionTargetDeviceStatus,
ExecutionTargetIcon,
@@ -20,6 +19,7 @@ import {
} from '@/features/ExecutionTargetPicker';
import { isHeterogeneousSandboxExecutionAvailable } from '@/helpers/executionTarget';
import { useAgentStore } from '@/store/agent';
+import { useDeviceList } from '@/store/device';
import { WorkspaceAgentPolicyCard } from './WorkspaceAgentPolicyCard';
@@ -112,16 +112,19 @@ interface ExecutionTargetLabelProps {
offlineLabel: string;
onlineLabel: string;
target: DeviceExecutionTarget;
+ unknownLabel: string;
}
const ExecutionTargetLabel = memo<ExecutionTargetLabelProps>(
- ({ compact, description, device, label, offlineLabel, onlineLabel, target }) => {
+ ({ compact, description, device, label, offlineLabel, onlineLabel, target, unknownLabel }) => {
const icon = <ExecutionTargetIcon devicePlatform={device?.platform} target={target} />;
const secondary = device ? (
<ExecutionTargetDeviceStatus
offlineLabel={offlineLabel}
online={device.online}
onlineLabel={onlineLabel}
+ unknown={device.onlineUnknown}
+ unknownLabel={unknownLabel}
/>
) : (
description
@@ -166,7 +169,7 @@ const WorkspaceAgentDevicePolicy = memo<WorkspaceAgentDevicePolicyProps>(
const config = useAgentStore((s) => s.agentMap[agentId]);
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
- const { data: devices, error, isLoading, mutate } = useDeviceList();
+ const { data: devices, error, isConfirmed, isLoading, mutate } = useDeviceList();
const { publicWorkspace: publicWorkspaceDevices } = useMemo(
() => groupExecutionTargetDevices(devices),
[devices],
@@ -210,6 +213,7 @@ const WorkspaceAgentDevicePolicy = memo<WorkspaceAgentDevicePolicyProps>(
offlineLabel={t('chat:heteroAgent.executionTarget.offline')}
onlineLabel={t('chat:heteroAgent.executionTarget.online')}
target={target}
+ unknownLabel={t('chat:heteroAgent.executionTarget.presenceChecking')}
/>
),
[t, targetLabels],
@@ -225,6 +229,7 @@ const WorkspaceAgentDevicePolicy = memo<WorkspaceAgentDevicePolicyProps>(
offlineLabel={t('chat:heteroAgent.executionTarget.offline')}
onlineLabel={t('chat:heteroAgent.executionTarget.online')}
target={'device'}
+ unknownLabel={t('chat:heteroAgent.executionTarget.presenceChecking')}
/>
),
[t],
@@ -254,27 +259,33 @@ const WorkspaceAgentDevicePolicy = memo<WorkspaceAgentDevicePolicyProps>(
},
];
- const workspaceOptions = isLoading
- ? [
- {
- disabled: true,
- label: t('chat:heteroAgent.executionTarget.loading'),
- value: 'status:loading',
- },
- ]
- : publicWorkspaceDevices.length > 0
- ? publicWorkspaceDevices.map((device) => ({
- label: renderDeviceLabel(device),
- title: device.friendlyName || device.hostname || device.deviceId,
- value: executionTargetValue('device', device.deviceId),
- }))
- : [
+ // Until the server confirms the list, the stored copy may hold devices that
+ // were since deleted or unshared (binding one would point the agent at an
+ // unresolvable machine) or lack ones that exist: show its rows, but only
+ // the confirmed list can be picked from or reported empty.
+ const workspaceOptions =
+ isLoading || (!isConfirmed && publicWorkspaceDevices.length === 0)
+ ? [
{
disabled: true,
- label: t('settingAgent.devicePolicy.noPublicDevice'),
- value: 'status:empty',
+ label: t('chat:heteroAgent.executionTarget.loading'),
+ value: 'status:loading',
},
- ];
+ ]
+ : publicWorkspaceDevices.length > 0
+ ? publicWorkspaceDevices.map((device) => ({
+ disabled: !isConfirmed,
+ label: renderDeviceLabel(device),
+ title: device.friendlyName || device.hostname || device.deviceId,
+ value: executionTargetValue('device', device.deviceId),
+ }))
+ : [
+ {
+ disabled: true,
+ label: t('settingAgent.devicePolicy.noPublicDevice'),
+ value: 'status:empty',
+ },
+ ];
return [
...sharedTargets,
@@ -289,6 +300,7 @@ const WorkspaceAgentDevicePolicy = memo<WorkspaceAgentDevicePolicyProps>(
];
}, [
error,
+ isConfirmed,
isLoading,
isHeterogeneous,
publicWorkspaceDevices,
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/boundDevicePresence.test.ts b/src/routes/(main)/agent/profile/features/ProfileEditor/boundDevicePresence.test.ts
new file mode 100644
index 00000000000..60f677d8841
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/boundDevicePresence.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest';
+
+import { getBoundDevicePresence, getDeviceSelectState } from './boundDevicePresence';
+
+describe('getBoundDevicePresence', () => {
+ it('says checking, not offline, while the stored copy lacks the bound device', () => {
+ expect(getBoundDevicePresence('dev-1', undefined, false)).toBe('checking');
+ });
+
+ it('reports the device missing only once the server confirmed the list', () => {
+ expect(getBoundDevicePresence('dev-1', undefined, true)).toBe('missing');
+ });
+
+ it('says checking for a stored row with unknown presence', () => {
+ expect(getBoundDevicePresence('dev-1', { online: false, onlineUnknown: true }, false)).toBe(
+ 'checking',
+ );
+ });
+
+ it('reads presence from a confirmed row', () => {
+ expect(getBoundDevicePresence('dev-1', { online: true }, true)).toBe('online');
+ expect(getBoundDevicePresence('dev-1', { online: false }, true)).toBe('offline');
+ });
+
+ it('reports nothing bound', () => {
+ expect(getBoundDevicePresence(undefined, undefined, true)).toBe('none');
+ });
+});
+
+describe('getDeviceSelectState', () => {
+ const base = {
+ error: undefined,
+ hasUnknownPresence: true,
+ isConfirmed: false,
+ isLoading: false,
+ isValidating: true,
+ };
+
+ it('loads while the list is the stored copy', () => {
+ expect(getDeviceSelectState(base)).toBe('loading');
+ });
+
+ it('surfaces a failed request of the unconfirmed list instead of loading forever', () => {
+ expect(getDeviceSelectState({ ...base, error: new Error('boom'), isValidating: false })).toBe(
+ 'error',
+ );
+ });
+
+ it('shows a retry in flight as loading', () => {
+ expect(getDeviceSelectState({ ...base, error: new Error('boom') })).toBe('loading');
+ });
+
+ it('is ready once the server confirmed the list', () => {
+ expect(
+ getDeviceSelectState({
+ ...base,
+ hasUnknownPresence: false,
+ isConfirmed: true,
+ isValidating: false,
+ }),
+ ).toBe('ready');
+ });
+});
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/boundDevicePresence.ts b/src/routes/(main)/agent/profile/features/ProfileEditor/boundDevicePresence.ts
new file mode 100644
index 00000000000..2b5e181ce59
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/boundDevicePresence.ts
@@ -0,0 +1,53 @@
+import type { DeviceListItem } from '@lobechat/types';
+
+import { isDevicePresenceUnknown } from '@/store/device';
+
+/**
+ * What the remote agent card says about its bound device.
+ *
+ * Returns:
+ * - `none` when nothing is bound
+ * - `checking` while the device list is still the stored copy and either
+ * lacks the device (it may be newer than the copy, or past its row cap) or
+ * holds it with unknown presence
+ * - `missing` once the server confirmed the list without the device
+ * - `online` / `offline` from a confirmed row
+ */
+export const getBoundDevicePresence = (
+ boundDeviceId: string | undefined,
+ boundDevice: Pick<DeviceListItem, 'online' | 'onlineUnknown'> | undefined,
+ isConfirmed: boolean,
+): 'checking' | 'missing' | 'none' | 'offline' | 'online' => {
+ if (!boundDeviceId) return 'none';
+ if (!boundDevice) return isConfirmed ? 'missing' : 'checking';
+ if (isDevicePresenceUnknown(boundDevice)) return 'checking';
+ return boundDevice.online ? 'online' : 'offline';
+};
+
+/**
+ * State of the change-device select, which only offers online devices.
+ *
+ * Returns:
+ * - `error` when the unconfirmed list's request failed and no retry is in
+ * flight — show why and offer a retry instead of an endless spinner
+ * - `loading` while the list is still the stored copy (its presence is not
+ * known, and it may lack devices) or any stored row has unknown presence
+ * - `ready` once the server confirmed the list
+ */
+export const getDeviceSelectState = ({
+ error,
+ hasUnknownPresence,
+ isConfirmed,
+ isLoading,
+ isValidating,
+}: {
+ error: unknown;
+ hasUnknownPresence: boolean;
+ isConfirmed: boolean;
+ isLoading: boolean;
+ isValidating: boolean;
+}): 'error' | 'loading' | 'ready' => {
+ if (!isConfirmed && error && !isValidating) return 'error';
+ if (isLoading || !isConfirmed || hasUnknownPresence) return 'loading';
+ return 'ready';
+};
diff --git a/src/store/device/action.test.ts b/src/store/device/action.test.ts
index 994d7184604..a9d03665e35 100644
--- a/src/store/device/action.test.ts
+++ b/src/store/device/action.test.ts
@@ -1,7 +1,6 @@
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 { deviceService } from '@/services/device';
@@ -92,18 +91,6 @@ describe('DeviceAction', () => {
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 () => {
- seedDevices([buildDevice()]);
-
- await useDeviceStore.getState().clearDeviceDefaultCwd('dev-1');
-
- 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 () => {
seedDevices([buildDevice()]);
diff --git a/src/store/device/action.ts b/src/store/device/action.ts
index 35ee7ba9abc..76c8be7cb8f 100644
--- a/src/store/device/action.ts
+++ b/src/store/device/action.ts
@@ -1,6 +1,5 @@
import type { DeviceListItem, WorkingDirEntry } from '@lobechat/types';
-import { refreshDeviceList } from '@/features/DeviceManager/const';
import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
import { deviceService } from '@/services/device';
import { type StoreSetter } from '@/store/types';
@@ -14,6 +13,14 @@ type Setter = StoreSetter<DeviceStore>;
const LIST_PARAMS = {} as DeviceListParams;
+/**
+ * Pickers, chips and guards across a page mount the list at different times.
+ * The app's SWR default (no dedupe) would let each late mount re-request it;
+ * inside this window they join the last request instead. Explicit refreshes,
+ * post-write revalidation and polling still go out.
+ */
+const DEVICE_LIST_DEDUPING_INTERVAL = 10_000;
+
type UpdateDeviceInput = Parameters<typeof deviceService.updateDevice>[0];
/**
@@ -60,12 +67,14 @@ export class DeviceActionImpl {
serverCall,
);
+ /** Re-fetch the truth (server-normalized fields, other tabs' writes). */
+ #revalidateDeviceLists = () => this.#list.revalidate(DEVICE_LIST_KEY);
+
/**
- * Revalidate both device lists: this store's replica and the canonical
- * workspace-scoped `useDeviceList` entry, which task controls read.
+ * Re-run the device list request of every mounted reader. Resolves once the
+ * response is folded into the store; read the rows with `deviceSelectors`.
*/
- #revalidateDeviceLists = () =>
- Promise.all([this.#list.revalidate(DEVICE_LIST_KEY), refreshDeviceList()]);
+ refreshDevices = (): Promise<unknown> => this.#list.revalidate(DEVICE_LIST_KEY);
/**
* Seed the persisted device list before the route commits, so the bound
@@ -203,10 +212,15 @@ export class DeviceActionImpl {
/**
* Fetch orchestration only; read the rows with `deviceSelectors.deviceList`.
* The persisted copy paints first (presence unknown), then the server
- * confirms it in the background.
+ * confirms it in the background. A surface that tracks presence live passes
+ * its own `refreshInterval`.
*/
- useFetchDevices = (enabled = false): ReplicaSyncResult =>
- this.#list.useSync(LIST_PARAMS, { enabled });
+ useFetchDevices = (enabled = false, schedule?: { refreshInterval?: number }): ReplicaSyncResult =>
+ this.#list.useSync(LIST_PARAMS, {
+ dedupingInterval: DEVICE_LIST_DEDUPING_INTERVAL,
+ enabled,
+ ...schedule,
+ });
}
export type DeviceAction = Pick<DeviceActionImpl, keyof DeviceActionImpl>;
diff --git a/src/store/device/index.ts b/src/store/device/index.ts
index c9b9abd6101..60305357405 100644
--- a/src/store/device/index.ts
+++ b/src/store/device/index.ts
@@ -3,3 +3,4 @@ export * from './gitHooks';
export * from './selectors';
export * from './store';
export * from './tunnelHooks';
+export * from './useDeviceList';
diff --git a/src/store/device/useDeviceList.test.ts b/src/store/device/useDeviceList.test.ts
new file mode 100644
index 00000000000..949cd0f72dd
--- /dev/null
+++ b/src/store/device/useDeviceList.test.ts
@@ -0,0 +1,236 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * `useDeviceList` reads the device store's replica: every device surface shares
+ * one request per scope, and a reload paints the persisted list (presence
+ * unknown) before the server answers.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { DeviceListItem } from '@lobechat/types';
+import { act, render, 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 { useUserStore } from '@/store/user';
+
+import { initialState } from './initialState';
+import { deviceListResource } from './projection';
+import { useDeviceStore } from './store';
+import { isDevicePresenceUnknown, useDeviceList } from './useDeviceList';
+
+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({});
+
+describe('useDeviceList', () => {
+ let scope = '';
+
+ beforeEach(() => {
+ scope = `device-list-user-${randomUUID()}:personal`;
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ act(() => {
+ useDeviceStore.setState(initialState);
+ useUserStore.setState({ isSignedIn: true });
+ });
+ });
+
+ afterEach(async () => {
+ await deviceListResource.storage!.remove({ queryKey: ROW_KEY, scope });
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('shares one request with the device store instead of fetching the list twice', async () => {
+ vi.mocked(deviceService.listDevices).mockResolvedValue([device('dev-1')]);
+
+ const { result } = renderHook(
+ () => {
+ // A picker and a working-directory chip mounted side by side.
+ const list = useDeviceList();
+ useDeviceStore((s) => s.useFetchDevices)(true);
+ return list;
+ },
+ { wrapper },
+ );
+
+ await waitFor(() => expect(result.current.data).toEqual([device('dev-1')]));
+ expect(deviceService.listDevices).toHaveBeenCalledTimes(1);
+ });
+
+ it('lets a reader that mounts after the first answer reuse it', async () => {
+ vi.mocked(deviceService.listDevices).mockResolvedValue([device('dev-1')]);
+ let lateData: DeviceListItem[] | undefined;
+ const Reader = () => {
+ useDeviceList();
+ return null;
+ };
+ const LateReader = () => {
+ lateData = useDeviceList().data;
+ return null;
+ };
+ const page = (late: boolean) =>
+ wrapper({
+ children: [
+ createElement(Reader, { key: 'a' }),
+ late && createElement(LateReader, { key: 'b' }),
+ ],
+ });
+
+ const view = render(page(false));
+ await waitFor(() => expect(deviceService.listDevices).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(useDeviceStore.getState().deviceListMap.all).toHaveLength(1));
+
+ // A popover / chip opening a moment later on the same page.
+ view.rerender(page(true));
+
+ expect(lateData).toEqual([device('dev-1')]);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(deviceService.listDevices).toHaveBeenCalledTimes(1);
+ });
+
+ it('paints the persisted list without a loading state, presence unknown', async () => {
+ await deviceListResource.storage!.set(
+ { queryKey: ROW_KEY, scope },
+ { data: [device('dev-1')], updatedAt: 1 },
+ );
+ vi.mocked(deviceService.listDevices).mockImplementation(pending);
+
+ const { result } = renderHook(() => useDeviceList(), { wrapper });
+
+ await waitFor(() => expect(result.current.data).toHaveLength(1));
+ expect(result.current.isLoading).toBe(false);
+ const [row] = result.current.data!;
+ expect(row).toMatchObject({ friendlyName: 'Mac dev-1', online: false });
+ // The stored `online: false` is a placeholder, not an offline device.
+ expect(isDevicePresenceUnknown(row)).toBe(true);
+ });
+
+ it('keeps a restored empty list pending until the server confirms it', async () => {
+ await deviceListResource.storage!.set({ queryKey: ROW_KEY, scope }, { data: [], updatedAt: 1 });
+ let answer!: (rows: DeviceListItem[]) => void;
+ vi.mocked(deviceService.listDevices).mockImplementation(
+ () => new Promise((resolve) => (answer = resolve)),
+ );
+
+ const { result } = renderHook(() => useDeviceList(), { wrapper });
+
+ await waitFor(() => expect(useDeviceStore.getState().deviceListMap.all).toEqual([]));
+ // The empty copy is no proof the user has no device.
+ expect(result.current).toMatchObject({ data: undefined, isConfirmed: false, isLoading: true });
+
+ await waitFor(() => expect(deviceService.listDevices).toHaveBeenCalled());
+ await act(async () => answer([]));
+
+ await waitFor(() =>
+ expect(result.current).toMatchObject({ data: [], isConfirmed: true, isLoading: false }),
+ );
+ });
+
+ it('surfaces a failed refresh over a restored empty list', async () => {
+ await deviceListResource.storage!.set({ queryKey: ROW_KEY, scope }, { data: [], updatedAt: 1 });
+ vi.mocked(deviceService.listDevices).mockRejectedValue(new Error('boom'));
+
+ const { result } = renderHook(() => useDeviceList(), { wrapper });
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current).toMatchObject({ data: undefined, isConfirmed: false, isLoading: false });
+ });
+
+ it('keeps the restored rows when the refresh fails', async () => {
+ await deviceListResource.storage!.set(
+ { queryKey: ROW_KEY, scope },
+ { data: [device('dev-1')], updatedAt: 1 },
+ );
+ vi.mocked(deviceService.listDevices).mockRejectedValue(new Error('boom'));
+
+ const { result } = renderHook(() => useDeviceList(), { wrapper });
+
+ await waitFor(() => expect(result.current.error).toBeTruthy());
+ expect(result.current.data).toHaveLength(1);
+ expect(result.current.isConfirmed).toBe(false);
+ });
+
+ it('shows a cwd written through the store without waiting for a refetch', async () => {
+ vi.mocked(deviceService.listDevices).mockResolvedValue([device('dev-1')]);
+ // Hold the write open: the optimistic row is what the list must show.
+ vi.mocked(deviceService.updateDevice).mockImplementation(pending);
+
+ const { result } = renderHook(() => useDeviceList(), { wrapper });
+ await waitFor(() => expect(result.current.data).toHaveLength(1));
+
+ act(() => {
+ void useDeviceStore.getState().updateDeviceCwd('dev-1', { path: '/elsewhere' });
+ });
+
+ await waitFor(() => expect(result.current.data?.[0]?.defaultCwd).toBe('/elsewhere'));
+ });
+
+ it('resolves mutate with the refreshed rows', async () => {
+ vi.mocked(deviceService.listDevices).mockResolvedValue([device('dev-1', { online: false })]);
+
+ const { result } = renderHook(() => useDeviceList(), { wrapper });
+ await waitFor(() => expect(result.current.data).toHaveLength(1));
+
+ vi.mocked(deviceService.listDevices).mockResolvedValue([device('dev-1')]);
+ let next: DeviceListItem[] | undefined;
+ await act(async () => {
+ next = await result.current.mutate();
+ });
+
+ expect(next?.[0]?.online).toBe(true);
+ });
+
+ it('stays idle while signed out', () => {
+ act(() => useUserStore.setState({ isSignedIn: false }));
+
+ const { result } = renderHook(() => useDeviceList(), { wrapper });
+
+ expect(result.current).toMatchObject({ data: undefined, isLoading: false });
+ expect(deviceService.listDevices).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/device/useDeviceList.ts b/src/store/device/useDeviceList.ts
new file mode 100644
index 00000000000..f4116395daf
--- /dev/null
+++ b/src/store/device/useDeviceList.ts
@@ -0,0 +1,82 @@
+import { isDesktop } from '@lobechat/const';
+import type { DeviceListItem } from '@lobechat/types';
+import { useCallback } from 'react';
+
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+import { deviceSelectors } from './selectors';
+import { useDeviceStore } from './store';
+
+export interface DeviceListResult {
+ /** Every device of the active scope, or `undefined` until storage or the server answers. */
+ data: DeviceListItem[] | undefined;
+ error: unknown;
+ /**
+ * The server answered this session. Until then `data` is a persisted copy
+ * that may be stale or miss rows, so "no device" / "not found" is pending,
+ * not a fact.
+ */
+ isConfirmed: boolean;
+ /** Nothing to show yet: no usable copy and the request is in flight. */
+ isLoading: boolean;
+ /** A request is in flight. Never a reason to hide `data`. */
+ isValidating: boolean;
+ /** Re-fetch, then resolve with the rows now in the store. */
+ mutate: () => Promise<DeviceListItem[] | undefined>;
+}
+
+/**
+ * The device list, read from the device store's replica. ALWAYS use this (or
+ * `useFetchDevices` + `deviceSelectors`) for any surface that lists or
+ * resolves devices — never `lambdaQuery.device.listDevices` or a second fetch.
+ * One request per scope feeds every reader, and the replica is partitioned by
+ * user + workspace, so switching workspaces never serves the previous pool.
+ *
+ * A reload paints the persisted copy first. Its rows carry `onlineUnknown`
+ * (stored as offline, no channels) until the server confirms them, so a
+ * surface that shows or acts on presence must treat those rows as unknown
+ * rather than offline (`isDevicePresenceUnknown`).
+ *
+ * Devices come from an authed lambda procedure, so only query once signed in
+ * (desktop always queries — it lists the local device's registered cwd).
+ * A live surface that must track presence passes its own `refreshInterval`.
+ */
+export const useDeviceList = (config?: { refreshInterval?: number }): DeviceListResult => {
+ const isLogin = useUserStore(authSelectors.isLogin);
+ const enabled = isLogin || isDesktop;
+ const { error, isValidating } = useDeviceStore((s) => s.useFetchDevices)(enabled, config);
+ const isLoaded = useDeviceStore(deviceSelectors.isDeviceListLoaded);
+ const isConfirmed = useDeviceStore(deviceSelectors.isDeviceListConfirmed);
+ const devices = useDeviceStore(deviceSelectors.deviceList);
+ const refreshDevices = useDeviceStore((s) => s.refreshDevices);
+
+ const mutate = useCallback(async () => {
+ await refreshDevices();
+ const state = useDeviceStore.getState();
+ return deviceSelectors.isDeviceListLoaded(state)
+ ? deviceSelectors.deviceList(state)
+ : undefined;
+ }, [refreshDevices]);
+
+ // A restored empty list says nothing about the server: keep it pending so no
+ // surface renders onboarding off it, and a failed refresh still surfaces its
+ // error instead of settling on the empty snapshot.
+ const hasData = isLoaded && (isConfirmed || devices.length > 0);
+
+ return {
+ data: hasData ? devices : undefined,
+ error,
+ isConfirmed,
+ isLoading: enabled && !hasData && (!error || isValidating),
+ isValidating,
+ mutate,
+ };
+};
+
+/**
+ * The row came from the persisted copy and the server has not confirmed it
+ * yet: its `online: false` is a placeholder, not a fact.
+ */
+export const isDevicePresenceUnknown = (device: Pick<DeviceListItem, 'onlineUnknown'>): boolean =>
+ !!device.onlineUnknown;