Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(device): show device details on hover in the environment picker (#21017)

Rdmclin2dc2320316697
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 09178baf0ce..e9df265cf7b 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -3142,6 +3142,7 @@
"workingPanel.overview.changes.none": "No changes",
"workingPanel.overview.ci.failure": "Failed",
"workingPanel.overview.ci.pending": "Running",
+ "workingPanel.overview.deviceError": "Could not load the device status",
"workingPanel.overview.empty": "Workspace activity and outputs will appear here as the agent works.",
"workingPanel.overview.emptyTitle": "Ready to work",
"workingPanel.overview.environmentError": "Could not load the repository status",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 7aaf58e56c9..c4089d9405b 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -3142,6 +3142,7 @@
"workingPanel.overview.changes.none": "无改动",
"workingPanel.overview.ci.failure": "失败",
"workingPanel.overview.ci.pending": "运行中",
+ "workingPanel.overview.deviceError": "无法加载设备状态",
"workingPanel.overview.empty": "Agent 开始工作后,工作区活动和产物会显示在这里。",
"workingPanel.overview.emptyTitle": "准备就绪",
"workingPanel.overview.environmentError": "无法加载仓库状态",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 985970d397c..98f26abb140 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3336,6 +3336,7 @@ export default {
'workingPanel.overview.empty':
'Workspace activity and outputs will appear here as the agent works.',
'workingPanel.overview.emptyTitle': 'Ready to work',
+ 'workingPanel.overview.deviceError': 'Could not load the device status',
'workingPanel.overview.environmentError': 'Could not load the repository status',
'workingPanel.overview.execution.device': 'Connected device',
'workingPanel.overview.execution.local': 'This device',
diff --git a/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx
new file mode 100644
index 00000000000..ec7628ae975
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/DeviceOptionRow.tsx
@@ -0,0 +1,112 @@
+'use client';
+
+import type { DeviceListItem } from '@lobechat/types';
+import { Icon } from '@lobehub/ui';
+import { Button, Popover } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { RefreshCwIcon } from 'lucide-react';
+import type { ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import DeviceHoverPanel from '@/features/DeviceManager/DeviceHoverPanel';
+import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';
+
+import { handleDeviceRowKeyDown } from './deviceRowKeyDown';
+import OptionRow from './OptionRow';
+
+const styles = createStaticStyles(({ css }) => ({
+ reconnectButton: css`
+ min-height: 18px;
+ padding-block: 0;
+ padding-inline: 2px;
+ font-size: 11px;
+ `,
+}));
+
+/** Long enough that sweeping the pointer down the list doesn't flash a panel per row. */
+const DETAIL_OPEN_DELAY_MS = 300;
+
+interface DeviceOptionRowProps {
+ active: boolean;
+ device: DeviceListItem;
+ /** This app's own machine: described as the local process instead of by status. */
+ isCurrentMachine: boolean;
+ onReconnect: () => void;
+ onSelect: () => void;
+ reconnecting: boolean;
+ tags: ReactNode[];
+}
+
+/**
+ * One device in the execution environment picker. Hovering it opens the
+ * device's details beside the menu — offline rows too, since "why can't I pick
+ * this" is exactly when the specs and last-seen time matter.
+ */
+const DeviceOptionRow = ({
+ active,
+ device,
+ isCurrentMachine,
+ onReconnect,
+ onSelect,
+ reconnecting,
+ tags,
+}: DeviceOptionRowProps) => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <Popover
+ arrow={false}
+ content={<DeviceHoverPanel device={device} />}
+ openDelay={DETAIL_OPEN_DELAY_MS}
+ placement={'rightTop'}
+ styles={{ content: { padding: 4 } }}
+ trigger={'hover'}
+ >
+ <div
+ data-testid={`device-option-${device.deviceId}`}
+ onKeyDown={(event) => handleDeviceRowKeyDown(event, { disabled: !device.online, onSelect })}
+ >
+ <OptionRow
+ active={active}
+ disabled={!device.online}
+ icon={<ExecutionTargetIcon devicePlatform={device.platform} target={'device'} />}
+ label={device.friendlyName || device.hostname || device.deviceId}
+ tags={tags}
+ desc={
+ <>
+ {isCurrentMachine ? (
+ t('heteroAgent.executionTarget.gatewayDesc')
+ ) : (
+ <ExecutionTargetDeviceStatus
+ offlineLabel={t('heteroAgent.executionTarget.offline')}
+ online={device.online}
+ onlineLabel={t('heteroAgent.executionTarget.onlineConnections', {
+ count: device.channels.length,
+ })}
+ />
+ )}
+ {device.online ? null : (
+ <Button
+ className={styles.reconnectButton}
+ icon={<Icon icon={RefreshCwIcon} size={10} />}
+ loading={reconnecting}
+ size={'small'}
+ type={'text'}
+ onClick={(event) => {
+ event.stopPropagation();
+ onReconnect();
+ }}
+ >
+ {t('heteroAgent.executionTarget.reconnect')}
+ </Button>
+ )}
+ </>
+ }
+ onClick={onSelect}
+ />
+ </div>
+ </Popover>
+ );
+};
+
+export default DeviceOptionRow;
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 8835b0c712a..db6879b3249 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -11,7 +11,6 @@ import {
ExternalLinkIcon,
InfoIcon,
MonitorDownIcon,
- RefreshCwIcon,
SettingsIcon,
ShieldCheckIcon,
} from 'lucide-react';
@@ -26,7 +25,6 @@ import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectEx
import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import {
devicePoolForAgent,
- ExecutionTargetDeviceStatus,
ExecutionTargetIcon,
groupExecutionTargetDevices,
} from '@/features/ExecutionTargetPicker';
@@ -44,6 +42,7 @@ import { useElectronStore } from '@/store/electron';
import { useTopicId } from '../hooks/useTopicId';
import { formatLockedControlTooltip } from '../utils/lockedControlTooltip';
+import DeviceOptionRow from './DeviceOptionRow';
import OptionRow from './OptionRow';
import { useSandboxNetworkToggle } from './useSandboxNetworkToggle';
import { useTopicAwareTargetSelect } from './useTopicAwareTargetSelect';
@@ -169,12 +168,6 @@ const styles = createStaticStyles(({ css }) => ({
min-width: 0;
`,
- reconnectButton: css`
- min-height: 18px;
- padding-block: 0;
- padding-inline: 2px;
- font-size: 11px;
- `,
optionTitle: css`
overflow: hidden;
@@ -571,52 +564,21 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
return executionTarget === target;
};
- const renderDeviceStatus = (d: NonNullable<typeof devices>[number]) => (
- <ExecutionTargetDeviceStatus
- offlineLabel={t('heteroAgent.executionTarget.offline')}
- online={d.online}
- onlineLabel={t('heteroAgent.executionTarget.onlineConnections', {
- count: d.channels.length,
- })}
- />
- );
-
const renderDeviceRow = (d: NonNullable<typeof devices>[number]) => {
const isCurrentMachine = d.deviceId === currentDeviceId;
return (
- <OptionRow
+ <DeviceOptionRow
active={isActive('device', d.deviceId)}
- disabled={!d.online}
- icon={<ExecutionTargetIcon devicePlatform={d.platform} target={'device'} />}
+ device={d}
+ isCurrentMachine={isCurrentMachine}
key={d.deviceId}
- label={d.friendlyName || d.hostname || d.deviceId}
- desc={
- <>
- {isCurrentMachine
- ? t('heteroAgent.executionTarget.gatewayDesc')
- : renderDeviceStatus(d)}
- {d.online ? null : (
- <Button
- className={styles.reconnectButton}
- icon={<Icon icon={RefreshCwIcon} size={10} />}
- loading={reconnectingDeviceId === d.deviceId}
- size={'small'}
- type={'text'}
- onClick={(event) => {
- event.stopPropagation();
- void handleReconnectDevice(d.deviceId);
- }}
- >
- {t('heteroAgent.executionTarget.reconnect')}
- </Button>
- )}
- </>
- }
+ reconnecting={reconnectingDeviceId === d.deviceId}
tags={tagsFor(
isActive('device', d.deviceId),
isCurrentMachine ? [t('heteroAgent.executionTarget.gateway')] : [],
)}
- onClick={() => void handleSelect('device', d.deviceId)}
+ onReconnect={() => void handleReconnectDevice(d.deviceId)}
+ onSelect={() => void handleSelect('device', d.deviceId)}
/>
);
};
diff --git a/src/features/ChatInput/ControlBar/__tests__/deviceRowKeyDown.test.ts b/src/features/ChatInput/ControlBar/__tests__/deviceRowKeyDown.test.ts
new file mode 100644
index 00000000000..0447d5dcdb1
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/__tests__/deviceRowKeyDown.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { handleDeviceRowKeyDown } from '../deviceRowKeyDown';
+
+const row = {};
+
+const keyEvent = (key: string, target: unknown = row) => ({
+ currentTarget: row as never,
+ key,
+ preventDefault: vi.fn(),
+ target: target as never,
+});
+
+describe('handleDeviceRowKeyDown', () => {
+ it.each(['Enter', ' '])('selects an online row on %j', (key) => {
+ const onSelect = vi.fn();
+ const event = keyEvent(key);
+
+ handleDeviceRowKeyDown(event, { disabled: false, onSelect });
+
+ expect(onSelect).toHaveBeenCalledOnce();
+ expect(event.preventDefault).toHaveBeenCalled();
+ });
+
+ it('ignores other keys', () => {
+ const onSelect = vi.fn();
+
+ handleDeviceRowKeyDown(keyEvent('ArrowDown'), { disabled: false, onSelect });
+
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
+ it('does not select an offline row', () => {
+ const onSelect = vi.fn();
+
+ handleDeviceRowKeyDown(keyEvent('Enter'), { disabled: true, onSelect });
+
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
+ it('leaves keys aimed at an inner control (Reconnect) to that control', () => {
+ const onSelect = vi.fn();
+ const event = keyEvent('Enter', {});
+
+ handleDeviceRowKeyDown(event, { disabled: false, onSelect });
+
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/deviceRowKeyDown.ts b/src/features/ChatInput/ControlBar/deviceRowKeyDown.ts
new file mode 100644
index 00000000000..7903a4eff95
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/deviceRowKeyDown.ts
@@ -0,0 +1,19 @@
+import type { KeyboardEvent } from 'react';
+
+/**
+ * Enter / Space on a focused device row selects it. The detail Popover gives
+ * the row wrapper `role="button"` and focus but no activation of its own, so
+ * without this a keyboard user could tab to the row and have Enter do nothing.
+ * Keys aimed at a control inside the row (the Reconnect button) stay with it,
+ * and a disabled (offline) row ignores them like it ignores clicks.
+ */
+export const handleDeviceRowKeyDown = (
+ event: Pick<KeyboardEvent, 'currentTarget' | 'key' | 'preventDefault' | 'target'>,
+ { disabled, onSelect }: { disabled: boolean; onSelect: () => void },
+) => {
+ if (event.target !== event.currentTarget) return;
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+
+ event.preventDefault();
+ if (!disabled) onSelect();
+};
diff --git a/src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsx b/src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsx
new file mode 100644
index 00000000000..92ac9484338
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Overview/DeviceStatusSection.tsx
@@ -0,0 +1,209 @@
+'use client';
+
+import type { DeviceListItem, DeviceMetricSeries } from '@lobechat/types';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Button, Skeleton, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { RefreshCwIcon, TriangleAlertIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DeviceRunningSummaryValue } from '@/features/DeviceManager/DeviceActivity/RunningUsers';
+import { useDeviceMetricSeries } from '@/features/DeviceManager/DeviceHealth/shared';
+import UsageMeter, {
+ UsageMeterGroup,
+ UsageMeterSkeleton,
+} from '@/features/DeviceManager/DeviceHealth/UsageMeter';
+import { latestUsageView } from '@/features/DeviceManager/DeviceHealth/viewState';
+import { getDeviceIcon, getPlatformLabel } from '@/features/DeviceManager/getDeviceIcon';
+import { useDeviceActivityText } from '@/features/DeviceManager/useDeviceActivityText';
+
+import { OverviewRow } from './OverviewRow';
+import { sectionStyles } from './sectionStyles';
+import { useBoundDevice } from './useBoundDevice';
+
+const styles = createStaticStyles(({ css }) => ({
+ body: css`
+ padding-block: 4px;
+ padding-inline: 8px;
+ `,
+ code: css`
+ overflow: hidden;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ infoGrid: css`
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ gap: 12px;
+ `,
+ name: css`
+ overflow: hidden;
+
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 18px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ presence: css`
+ flex: none;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ `,
+ sub: css`
+ overflow: hidden;
+
+ font-size: 12px;
+ line-height: 16px;
+ color: ${cssVar.colorTextTertiary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ tile: css`
+ display: grid;
+ flex-shrink: 0;
+ place-items: center;
+
+ width: 32px;
+ height: 32px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 9px;
+
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+}));
+
+interface DeviceStatusSectionProps {
+ /** Polls the device's presence and CPU / memory series only while the Overview is on screen. */
+ active: boolean;
+ deviceId: string;
+}
+
+/**
+ * The device the topic runs on, as its device card shows it: presence,
+ * hostname, running topics and the latest CPU / memory load. Answers "is the
+ * machine doing this work healthy and busy?" without leaving the conversation.
+ */
+const DeviceStatusSection = memo<DeviceStatusSectionProps>(({ active, deviceId }) => {
+ const { t } = useTranslation('chat');
+ const { t: tCommon } = useTranslation('common');
+ const bound = useBoundDevice(deviceId, active);
+ const device = bound.status === 'ready' ? bound.device : undefined;
+ const { data, error } = useDeviceMetricSeries(deviceId, active && !!device);
+
+ if (bound.status === 'loading')
+ return (
+ <Flexbox className={sectionStyles.section}>
+ <div className={sectionStyles.skeleton}>
+ <Skeleton.Text rows={2} />
+ </div>
+ </Flexbox>
+ );
+
+ // A failed read is not a removed device: say so and offer a retry.
+ if (bound.status === 'error')
+ return (
+ <Flexbox className={sectionStyles.section}>
+ <OverviewRow
+ danger
+ icon={TriangleAlertIcon}
+ iconColor={cssVar.colorError}
+ value={t('workingPanel.overview.deviceError')}
+ trailing={
+ <Button
+ icon={<Icon icon={RefreshCwIcon} size={12} />}
+ size={'small'}
+ onClick={bound.retry}
+ >
+ {tCommon('retry')}
+ </Button>
+ }
+ />
+ </Flexbox>
+ );
+
+ // Removed, or not visible in this workspace: nothing to describe.
+ if (!device) return null;
+
+ return <DeviceStatusContent data={data} device={device} error={error} />;
+});
+
+DeviceStatusSection.displayName = 'OverviewDeviceStatusSection';
+
+interface DeviceStatusContentProps {
+ data?: DeviceMetricSeries;
+ device: DeviceListItem;
+ error?: unknown;
+}
+
+const DeviceStatusContent = ({ data, device, error }: DeviceStatusContentProps) => {
+ const { t } = useTranslation('setting');
+ const activityText = useDeviceActivityText(device);
+ const online = (device.channels ?? []).length > 0;
+ const usage = latestUsageView({ data, error });
+ const platformLabel = getPlatformLabel(device.platform, device.architecture);
+ const displayName = device.friendlyName || device.hostname || device.deviceId;
+
+ return (
+ <Flexbox className={sectionStyles.section} data-testid={'overview-device-status'}>
+ <Flexbox className={styles.body} gap={14}>
+ <Flexbox horizontal align={'center'} gap={10}>
+ <span className={styles.tile}>{getDeviceIcon(device.platform, 16)}</span>
+ <Flexbox flex={1} gap={1} style={{ minWidth: 0 }}>
+ <span className={styles.name} title={displayName}>
+ {displayName}
+ </span>
+ <Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>
+ <span
+ aria-hidden
+ className={styles.presence}
+ style={{ background: online ? cssVar.colorSuccess : cssVar.colorTextQuaternary }}
+ />
+ <span className={styles.sub} title={activityText}>
+ {platformLabel ? `${activityText} · ${platformLabel}` : activityText}
+ </span>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+
+ <div className={styles.infoGrid}>
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('devices.card.hostname')}
+ </Text>
+ <span className={styles.code} title={device.hostname ?? undefined}>
+ {device.hostname || '—'}
+ </span>
+ </Flexbox>
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('devices.card.runningTopics')}
+ </Text>
+ <DeviceRunningSummaryValue deviceId={device.deviceId} />
+ </Flexbox>
+ </div>
+
+ {usage.loading ? (
+ <UsageMeterGroup loading>
+ <UsageMeterSkeleton />
+ <UsageMeterSkeleton />
+ </UsageMeterGroup>
+ ) : (
+ <UsageMeterGroup>
+ <UsageMeter label={t('devices.card.cpuUsage')} value={usage.latest?.cpuPercent} />
+ <UsageMeter label={t('devices.card.memoryUsage')} value={usage.latest?.memoryPercent} />
+ </UsageMeterGroup>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
+export default DeviceStatusSection;
diff --git a/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts b/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts
index cc7683331b5..759b72753bc 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts
+++ b/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { collectChangeStats, isLinkedWorktreeCheckout, shouldShowCiLabel } from '../overviewData';
+import {
+ collectChangeStats,
+ getStatusDeviceId,
+ isLinkedWorktreeCheckout,
+ shouldShowCiLabel,
+} from '../overviewData';
describe('collectChangeStats', () => {
it('sums additions/deletions across repo and submodule patches', () => {
@@ -68,3 +73,21 @@ describe('shouldShowCiLabel', () => {
expect(shouldShowCiLabel(undefined)).toBe(false);
});
});
+
+describe('getStatusDeviceId', () => {
+ it('shows the bound remote device', () => {
+ expect(getStatusDeviceId('device', 'dev-1')).toBe('dev-1');
+ });
+
+ it('shows the bound local desktop, which has no RPC routing id', () => {
+ expect(getStatusDeviceId('local', 'desktop-1')).toBe('desktop-1');
+ });
+
+ it.each(['auto', 'none', 'sandbox'] as const)('shows nothing for %s', (target) => {
+ expect(getStatusDeviceId(target, 'dev-1')).toBeUndefined();
+ });
+
+ it('shows nothing when no device is bound', () => {
+ expect(getStatusDeviceId('device', undefined)).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Overview/__tests__/useBoundDevice.test.ts b/src/features/Conversation/WorkingSidebar/Overview/__tests__/useBoundDevice.test.ts
new file mode 100644
index 00000000000..31c16f59557
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Overview/__tests__/useBoundDevice.test.ts
@@ -0,0 +1,72 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { PRESENCE_REFRESH_INTERVAL_MS, useBoundDevice } from '../useBoundDevice';
+
+const useDeviceList = vi.fn();
+const mutate = vi.fn();
+
+vi.mock('@/features/DeviceManager/useDeviceList', () => ({
+ useDeviceList: (...args: unknown[]) => useDeviceList(...args),
+}));
+
+const listState = (state: { data?: unknown; error?: unknown; isLoading?: boolean }) =>
+ useDeviceList.mockReturnValue({ isLoading: false, mutate, ...state });
+
+describe('useBoundDevice', () => {
+ beforeEach(() => {
+ useDeviceList.mockReset();
+ mutate.mockReset();
+ listState({ data: [{ deviceId: 'dev-1' }, { deviceId: 'dev-2' }] });
+ });
+
+ it('polls device presence while the Overview is on screen', () => {
+ renderHook(() => useBoundDevice('dev-1', true));
+
+ expect(useDeviceList).toHaveBeenCalledWith({ refreshInterval: PRESENCE_REFRESH_INTERVAL_MS });
+ });
+
+ it('stops polling device presence while the Overview is hidden', () => {
+ renderHook(() => useBoundDevice('dev-1', false));
+
+ expect(useDeviceList).toHaveBeenCalledWith({ refreshInterval: 0 });
+ });
+
+ it('resolves the bound device from the list', () => {
+ const { result } = renderHook(() => useBoundDevice('dev-2', true));
+
+ expect(result.current).toEqual({ device: { deviceId: 'dev-2' }, status: 'ready' });
+ });
+
+ it('reports a loaded list without the device as absent', () => {
+ const { result } = renderHook(() => useBoundDevice('gone', true));
+
+ expect(result.current).toEqual({ status: 'absent' });
+ });
+
+ it('reports the first load as loading', () => {
+ listState({ isLoading: true });
+
+ const { result } = renderHook(() => useBoundDevice('dev-1', true));
+
+ expect(result.current).toEqual({ status: 'loading' });
+ });
+
+ it('reports a failed first load as an error with a retry, not as absent', () => {
+ listState({ error: new Error('network') });
+
+ const { result } = renderHook(() => useBoundDevice('dev-1', true));
+
+ expect(result.current.status).toBe('error');
+ if (result.current.status === 'error') result.current.retry();
+ expect(mutate).toHaveBeenCalledOnce();
+ });
+
+ it('keeps showing cached data when a later revalidation fails', () => {
+ listState({ data: [{ deviceId: 'dev-1' }], error: new Error('network') });
+
+ 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/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
index b99f02515fb..a40d4ec1e8d 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
@@ -49,6 +49,7 @@ import { labPreferSelectors } from '@/store/user/selectors';
import GoalSection from '../GoalSection';
import ProgressSection from '../ProgressSection';
+import DeviceStatusSection from './DeviceStatusSection';
import { collectChangeStats, isLinkedWorktreeCheckout, shouldShowCiLabel } from './overviewData';
import OverviewHeader from './OverviewHeader';
import { ChevronRight, OverviewRow, PickerGlyph, rowStyles } from './OverviewRow';
@@ -68,6 +69,7 @@ const styles = createStaticStyles(({ css }) => ({
interface OverviewProps {
active: boolean;
agentId?: string;
+ /** Routes file / git RPCs; empty for "This device", which reads over IPC. */
deviceId?: string;
environmentAvailable: boolean;
onOpenTab: (tab: string) => void;
@@ -76,6 +78,8 @@ interface OverviewProps {
pullRequest?: DeviceGitLinkedPullRequest | null;
repoType?: string;
sourcePath?: string;
+ /** The bound machine whose live status to show, local desktop included. */
+ statusDeviceId?: string;
workingDirectory?: string;
}
@@ -92,6 +96,7 @@ const Overview = memo<OverviewProps>(
pullRequest,
repoType,
sourcePath,
+ statusDeviceId,
workingDirectory,
}) => {
const { t } = useTranslation('chat');
@@ -419,6 +424,9 @@ const Overview = memo<OverviewProps>(
</>
)}
+ {/* The bound machine's live state, as its device card shows it. */}
+ {statusDeviceId && <DeviceStatusSection active={active} deviceId={statusDeviceId} />}
+
<TopicBackgroundActivity topicId={topicId} />
{environmentAvailable && !workingDirectory && (
<Empty
diff --git a/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts b/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts
index 5207b60c61b..7df75a6b975 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts
+++ b/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts
@@ -1,5 +1,9 @@
import type { GitWorkingTreePatches } from '@lobechat/electron-client-ipc';
-import type { DeviceGitPullRequestCiStatus, DeviceGitWorktreeListItem } from '@lobechat/types';
+import type {
+ DeviceExecutionTarget,
+ DeviceGitPullRequestCiStatus,
+ DeviceGitWorktreeListItem,
+} from '@lobechat/types';
import { normalizeDisplayPath } from '@/features/ChatInput/ControlBar/worktreeHelpers';
@@ -57,3 +61,14 @@ export const isLinkedWorktreeCheckout = (
*/
export const shouldShowCiLabel = (status?: DeviceGitPullRequestCiStatus): boolean =>
status === 'failure' || status === 'pending';
+
+/**
+ * The machine whose live status the Overview shows. Unlike the RPC routing id,
+ * which is empty for "This device" so file and git reads stay on Electron IPC,
+ * a local run still names the desktop it is bound to, and that machine has a
+ * device card like any other.
+ */
+export const getStatusDeviceId = (
+ target: DeviceExecutionTarget,
+ boundDeviceId: string | undefined,
+): string | undefined => (target === 'device' || target === 'local' ? boundDeviceId : undefined);
diff --git a/src/features/Conversation/WorkingSidebar/Overview/useBoundDevice.ts b/src/features/Conversation/WorkingSidebar/Overview/useBoundDevice.ts
new file mode 100644
index 00000000000..8b793d68913
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Overview/useBoundDevice.ts
@@ -0,0 +1,42 @@
+import type { DeviceListItem } from '@lobechat/types';
+
+import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
+
+/** Re-reads presence so a device that drops or reconnects shows it without a refocus. */
+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. */
+ | { status: 'absent' }
+ | { device: DeviceListItem; status: 'ready' };
+
+/**
+ * The device a topic is bound to, kept live while the Overview is on screen.
+ * The device list does not poll on its own, so without this a device that
+ * disconnects keeps its old presence until the window is refocused.
+ *
+ * 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.
+ */
+export const useBoundDevice = (deviceId: string, active: boolean): BoundDeviceState => {
+ const {
+ data: devices,
+ error,
+ 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' };
+ }
+ if (error) return { retry: () => void mutate(), status: 'error' };
+ if (isLoading) return { status: 'loading' };
+
+ return { status: 'absent' };
+};
diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsx
index a5d0a5482f0..bf7078f6e42 100644
--- a/src/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/index.tsx
@@ -85,6 +85,7 @@ import Files from './Files';
import { sidebarWidthBudget } from './fitsBesidePortal';
import { MAX_PANEL_WIDTH, MIN_PANEL_WIDTH, OVERVIEW_PANEL_WIDTH } from './layout';
import Overview from './Overview';
+import { getStatusDeviceId } from './Overview/overviewData';
import OverviewSlot from './OverviewSlot';
import PullRequest from './PullRequest';
import ResourcesSection from './ResourcesSection';
@@ -368,10 +369,8 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
// tree + git reads go over RPC, so both Review and Files are reachable even
// when runtimeMode isn't `local`.
const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
- // `targetDeviceId` also identifies the local desktop for per-device working
- // directory state. Files/Review only need a deviceId when routing through a
- // remote device RPC; local "This device" must keep Electron IPC + file-open
- // actions enabled.
+ // `targetDeviceId` also names the local desktop (directory state, Overview status).
+ // Files/Review route a deviceId only for remote RPC; "This device" keeps Electron IPC.
const remoteDeviceId = isDeviceMode ? agencyConfig.boundDeviceId : undefined;
const isLocalExecution = effectiveTarget === 'local';
// A cloud-sandbox run keeps its files in the persistent workspace, so it has a
@@ -1043,6 +1042,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
pullRequest={pullRequest}
repoType={environmentRepoType}
sourcePath={sourceWorkingDirectory}
+ statusDeviceId={getStatusDeviceId(effectiveTarget, agencyConfig?.boundDeviceId)}
workingDirectory={environmentWorkingDirectory}
onOpenTab={openTab}
onRefreshPullRequest={refreshPullRequest}
diff --git a/src/features/DeviceManager/DeviceCard.tsx b/src/features/DeviceManager/DeviceCard.tsx
index d44423f3587..2ff77d2d71a 100644
--- a/src/features/DeviceManager/DeviceCard.tsx
+++ b/src/features/DeviceManager/DeviceCard.tsx
@@ -5,7 +5,6 @@ import { DropdownMenu, Flexbox, Icon, Tooltip } from '@lobehub/ui';
import { ActionIcon, Avatar, confirmModal, Tag, Text } from '@lobehub/ui/base-ui';
import { useInViewport } from 'ahooks';
import { createStaticStyles, cssVar } from 'antd-style';
-import dayjs from 'dayjs';
import {
EyeOffIcon,
GlobeIcon,
@@ -28,6 +27,7 @@ import { latestUsageView } from './DeviceHealth/viewState';
import { getDeviceIcon, getPlatformLabel } from './getDeviceIcon';
import { openShareDeviceModal } from './ShareDeviceModal';
import { useCanEditDevice } from './useCanEditDevice';
+import { useDeviceActivityText } from './useDeviceActivityText';
import { useDeviceCardMutations } from './useDeviceCardMutations';
const styles = createStaticStyles(({ css }) => ({
@@ -137,30 +137,7 @@ const DeviceCard = memo<DeviceCardProps>(({ device, isCurrent, onOpen }) => {
// Rendered inline (not as a dot tooltip): "when was this machine last
// reachable" is the answer needed to pick between rows, and hover can't
// answer it for a whole list at once — nor at all on touch.
- //
- // Online reads the gateway's live `connectedAt` from `channels[0]` — the
- // newest connection, since the pool is sorted newest-first in
- // `deviceGateway.queryDeviceList`. That is the same channel
- // `sortDevicesByActivity` ranks this row by, so the label always explains
- // the row's position.
- //
- // Offline can only report `lastSeen`, which is stamped on register — and
- // every client registers right before opening its WS
- // (`gatewayConnectionSrv`, CLI `registerDevice`) — so it means "last
- // CONNECTED", not "last active". The copy says exactly that; it becomes a
- // true last-active once a writer stamps liveness.
- //
- // A single connection drops the "1 connection" count — it is the common
- // case and would truncate the footer on a three-up grid.
- const activityText = online
- ? `${
- channels.length > 1
- ? t('devices.status.onlineConnections', { count: channels.length })
- : t('devices.status.online')
- } · ${t('devices.channel.connected', {
- time: dayjs(channels[0]?.connectedAt ?? device.lastSeen).fromNow(),
- })}`
- : t('devices.lastSeen', { time: dayjs(device.lastSeen).fromNow() });
+ const activityText = useDeviceActivityText(device);
// Publish / make-private for workspace enrollments. Reuses the
// shared visibility-confirm body so the consequences copy matches agents /
diff --git a/src/features/DeviceManager/DeviceHoverPanel.tsx b/src/features/DeviceManager/DeviceHoverPanel.tsx
new file mode 100644
index 00000000000..1f8f2b31c01
--- /dev/null
+++ b/src/features/DeviceManager/DeviceHoverPanel.tsx
@@ -0,0 +1,211 @@
+'use client';
+
+import type { DeviceListItem } from '@lobechat/types';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import {
+ CableIcon,
+ CalendarClockIcon,
+ CpuIcon,
+ FolderIcon,
+ LayersIcon,
+ type LucideIcon,
+ MemoryStickIcon,
+ MonitorIcon,
+ PowerIcon,
+ ServerIcon,
+ UserIcon,
+} from 'lucide-react';
+import type { ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatSize } from '@/utils/format';
+
+import { useDeviceMetricSeries } from './DeviceHealth/shared';
+import UsageMeter, { UsageMeterGroup, UsageMeterSkeleton } from './DeviceHealth/UsageMeter';
+import { latestUsageView } from './DeviceHealth/viewState';
+import { buildDeviceHoverSummary } from './deviceHoverSummary';
+import { getDeviceIcon } from './getDeviceIcon';
+
+const styles = createStaticStyles(({ css }) => ({
+ code: css`
+ overflow: hidden;
+
+ min-width: 0;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ container: css`
+ width: 300px;
+ padding-block: 4px 8px;
+ `,
+ row: css`
+ padding-block: 4px;
+ padding-inline: 8px;
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ sectionBar: css`
+ flex-shrink: 0;
+ width: 3px;
+ height: 14px;
+ border-radius: 2px;
+ `,
+ sectionTitle: css`
+ padding-block: 6px;
+ padding-inline: 8px;
+ font-size: 13px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ usage: css`
+ padding-block: 4px;
+ padding-inline: 8px;
+ `,
+ value: css`
+ overflow: hidden;
+ min-width: 0;
+ color: ${cssVar.colorText};
+ text-align: end;
+ `,
+}));
+
+const Section = ({ color, title }: { color: string; title: string }) => (
+ <Flexbox horizontal align={'center'} className={styles.sectionTitle} gap={8}>
+ <div className={styles.sectionBar} style={{ background: color }} />
+ <span>{title}</span>
+ </Flexbox>
+);
+
+const InfoRow = ({
+ children,
+ icon,
+ label,
+}: {
+ children?: ReactNode;
+ icon: LucideIcon;
+ label: string;
+}) => (
+ <Flexbox horizontal align={'center'} className={styles.row} gap={16} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>
+ <Icon icon={icon} size={13} />
+ <span>{label}</span>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} className={styles.value} gap={6} justify={'flex-end'}>
+ {children ?? <Text type={'secondary'}>—</Text>}
+ </Flexbox>
+ </Flexbox>
+);
+
+interface DeviceHoverPanelProps {
+ device: DeviceListItem;
+}
+
+/**
+ * A device's details at a glance, shown beside its row in the execution
+ * environment picker: live state and load first (what decides whether to run
+ * there), then the machine's specs. A read-only digest of the detail page's
+ * overview, reading the same metric series so opening one warms the other.
+ */
+const DeviceHoverPanel = ({ device }: DeviceHoverPanelProps) => {
+ const { t } = useTranslation('setting');
+
+ // The series also carries the specs (cores, memory), so fetch it for offline
+ // devices too; only an online device's last reading is shown as its load.
+ const { data, error } = useDeviceMetricSeries(device.deviceId);
+ const usage = latestUsageView({ data, error });
+ const summary = buildDeviceHoverSummary(device, data);
+ const { online } = summary;
+
+ return (
+ <Flexbox className={styles.container}>
+ <Section color={cssVar.colorSuccess} title={t('devices.detail.runtime')} />
+ <InfoRow icon={PowerIcon} label={t('devices.detail.status')}>
+ <span
+ style={{
+ background: online ? cssVar.colorSuccess : cssVar.colorTextQuaternary,
+ borderRadius: '50%',
+ flex: 'none',
+ height: 6,
+ width: 6,
+ }}
+ />
+ <span>{online ? t('devices.status.online') : t('devices.status.offline')}</span>
+ </InfoRow>
+ {online && (
+ <InfoRow icon={CableIcon} label={t('devices.detail.connections')}>
+ {summary.connections}
+ </InfoRow>
+ )}
+ <InfoRow icon={CalendarClockIcon} label={t('devices.detail.lastConnected')}>
+ {dayjs(summary.lastConnectedAt).fromNow()}
+ </InfoRow>
+ {online && (
+ <div className={styles.usage}>
+ {usage.loading ? (
+ <UsageMeterGroup loading>
+ <UsageMeterSkeleton />
+ <UsageMeterSkeleton />
+ </UsageMeterGroup>
+ ) : (
+ <UsageMeterGroup>
+ <UsageMeter label={t('devices.card.cpuUsage')} value={usage.latest?.cpuPercent} />
+ <UsageMeter
+ label={t('devices.card.memoryUsage')}
+ value={usage.latest?.memoryPercent}
+ />
+ </UsageMeterGroup>
+ )}
+ </div>
+ )}
+
+ <Section color={cssVar.colorInfo} title={t('devices.detail.specs')} />
+ <InfoRow icon={MonitorIcon} label={t('devices.detail.os')}>
+ {summary.platformLabel ? (
+ <>
+ <span style={{ display: 'flex', flex: 'none' }}>
+ {getDeviceIcon(device.platform, 13)}
+ </span>
+ <span>{summary.platformLabel}</span>
+ </>
+ ) : undefined}
+ </InfoRow>
+ <InfoRow icon={LayersIcon} label={t('devices.detail.architecture')}>
+ {summary.architecture}
+ </InfoRow>
+ <InfoRow icon={CpuIcon} label={t('devices.detail.cpu')}>
+ {summary.cores ? t('devices.detail.cores', { count: summary.cores }) : undefined}
+ </InfoRow>
+ <InfoRow icon={MemoryStickIcon} label={t('devices.detail.memory')}>
+ {summary.memoryTotalBytes ? formatSize(summary.memoryTotalBytes) : undefined}
+ </InfoRow>
+ <InfoRow icon={ServerIcon} label={t('devices.card.hostname')}>
+ {summary.hostname ? (
+ <span className={styles.code} title={summary.hostname}>
+ {summary.hostname}
+ </span>
+ ) : undefined}
+ </InfoRow>
+ <InfoRow icon={FolderIcon} label={t('devices.card.workingDir')}>
+ {summary.workingDir ? (
+ <span className={styles.code} title={summary.workingDir}>
+ {summary.workingDir}
+ </span>
+ ) : undefined}
+ </InfoRow>
+ {summary.enrollerName !== undefined && (
+ <InfoRow icon={UserIcon} label={t('workspaceSetting.devices.enrolledByLabel')}>
+ <Text ellipsis fontSize={12}>
+ {summary.enrollerName ?? t('workspaceSetting.devices.unknownEnroller')}
+ </Text>
+ </InfoRow>
+ )}
+ </Flexbox>
+ );
+};
+
+export default DeviceHoverPanel;
diff --git a/src/features/DeviceManager/deviceHoverSummary.test.ts b/src/features/DeviceManager/deviceHoverSummary.test.ts
new file mode 100644
index 00000000000..07f66e7b926
--- /dev/null
+++ b/src/features/DeviceManager/deviceHoverSummary.test.ts
@@ -0,0 +1,99 @@
+import type { DeviceListItem, DeviceMetricSeries } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { buildDeviceHoverSummary } from './deviceHoverSummary';
+
+const series: DeviceMetricSeries = {
+ bucketMs: 300_000,
+ cpuCount: 8,
+ from: 0,
+ memoryTotalBytes: 32 * 1024 ** 3,
+ points: [],
+ to: 1,
+};
+
+const makeDevice = (overrides: Partial<DeviceListItem> = {}): DeviceListItem => ({
+ architecture: 'x64',
+ channels: [
+ { channel: 'cli', connectedAt: '2026-10-15T10:00:00.000Z', hostname: null, platform: null },
+ { channel: 'desktop', connectedAt: '2026-10-15T08:00:00.000Z', hostname: null, platform: null },
+ ],
+ defaultCwd: '/home/dev/project',
+ deviceId: 'dev-1',
+ enroller: null,
+ friendlyName: 'Dev box',
+ hostname: 'dev-box.local',
+ identitySource: null,
+ lastSeen: '2026-10-14T00:00:00.000Z',
+ online: true,
+ platform: 'linux',
+ registered: true,
+ scope: 'personal',
+ visibility: null,
+ workingDirs: [],
+ ...overrides,
+});
+
+describe('buildDeviceHoverSummary', () => {
+ it('combines the device row with the specs from its metric series', () => {
+ expect(buildDeviceHoverSummary(makeDevice(), series)).toEqual({
+ architecture: 'x64',
+ connections: 2,
+ cores: 8,
+ enrollerName: undefined,
+ hostname: 'dev-box.local',
+ lastConnectedAt: '2026-10-15T10:00:00.000Z',
+ memoryTotalBytes: 32 * 1024 ** 3,
+ online: true,
+ platformLabel: 'Linux',
+ workingDir: '/home/dev/project',
+ });
+ });
+
+ it('falls back to the last registration and leaves unreported fields empty', () => {
+ const summary = buildDeviceHoverSummary(
+ makeDevice({
+ architecture: null,
+ channels: [],
+ defaultCwd: '',
+ hostname: null,
+ online: false,
+ platform: null,
+ }),
+ { ...series, cpuCount: null, memoryTotalBytes: null },
+ );
+
+ expect(summary).toMatchObject({
+ architecture: undefined,
+ connections: 0,
+ cores: undefined,
+ hostname: undefined,
+ lastConnectedAt: '2026-10-14T00:00:00.000Z',
+ memoryTotalBytes: undefined,
+ online: false,
+ platformLabel: undefined,
+ workingDir: undefined,
+ });
+ });
+
+ it('leaves specs empty before the metric series loads', () => {
+ const summary = buildDeviceHoverSummary(makeDevice());
+
+ expect(summary.cores).toBeUndefined();
+ expect(summary.memoryTotalBytes).toBeUndefined();
+ });
+
+ it('names the enroller only for workspace devices', () => {
+ const enroller = { avatar: null, fullName: null, userId: 'u1', username: 'ada' };
+
+ expect(buildDeviceHoverSummary(makeDevice({ enroller })).enrollerName).toBeUndefined();
+ expect(buildDeviceHoverSummary(makeDevice({ enroller, scope: 'workspace' })).enrollerName).toBe(
+ 'ada',
+ );
+ expect(
+ buildDeviceHoverSummary(
+ makeDevice({ enroller: { ...enroller, username: null }, scope: 'workspace' }),
+ ).enrollerName,
+ ).toBeNull();
+ });
+});
diff --git a/src/features/DeviceManager/deviceHoverSummary.ts b/src/features/DeviceManager/deviceHoverSummary.ts
new file mode 100644
index 00000000000..985efcaf701
--- /dev/null
+++ b/src/features/DeviceManager/deviceHoverSummary.ts
@@ -0,0 +1,49 @@
+import type { DeviceListItem, DeviceMetricSeries } from '@lobechat/types';
+
+import { getPlatformLabel } from './getDeviceIcon';
+
+export interface DeviceHoverSummary {
+ architecture?: string;
+ /** Live connections; only meaningful while online. */
+ connections: number;
+ cores?: number;
+ /**
+ * Who enrolled a workspace device. `null` names an enroller the list could
+ * not resolve; `undefined` means the row has no enroller to show.
+ */
+ enrollerName?: string | null;
+ hostname?: string;
+ /** When the device last (re)connected — its newest channel, else when it last registered. */
+ lastConnectedAt: string;
+ memoryTotalBytes?: number;
+ online: boolean;
+ platformLabel?: string;
+ workingDir?: string;
+}
+
+/**
+ * What the picker's hover panel shows for one device. Fields the device never
+ * reported come back `undefined` so every row renders the same placeholder.
+ */
+export const buildDeviceHoverSummary = (
+ device: DeviceListItem,
+ series?: DeviceMetricSeries,
+): DeviceHoverSummary => {
+ const channels = device.channels ?? [];
+
+ return {
+ architecture: device.architecture || undefined,
+ connections: channels.length,
+ cores: series?.cpuCount || undefined,
+ enrollerName:
+ device.scope === 'workspace' && device.enroller
+ ? device.enroller.fullName || device.enroller.username || null
+ : undefined,
+ hostname: device.hostname || undefined,
+ lastConnectedAt: channels[0]?.connectedAt ?? device.lastSeen,
+ memoryTotalBytes: series?.memoryTotalBytes || undefined,
+ online: device.online,
+ platformLabel: getPlatformLabel(device.platform),
+ workingDir: device.defaultCwd || undefined,
+ };
+};
diff --git a/src/features/DeviceManager/useDeviceActivityText.ts b/src/features/DeviceManager/useDeviceActivityText.ts
new file mode 100644
index 00000000000..450416eeb09
--- /dev/null
+++ b/src/features/DeviceManager/useDeviceActivityText.ts
@@ -0,0 +1,38 @@
+import type { DeviceListItem } from '@lobechat/types';
+import dayjs from 'dayjs';
+import { useTranslation } from 'react-i18next';
+
+/**
+ * A device's presence as one line — "Online · Connected 5 minutes ago" or
+ * "Last connected 2 days ago". Shared by the device card footer and the
+ * conversation Overview, so both describe the same machine the same way.
+ *
+ * Online reads the gateway's live `connectedAt` from `channels[0]` — the
+ * newest connection, since the pool is sorted newest-first in
+ * `deviceGateway.queryDeviceList`. That is the same channel
+ * `sortDevicesByActivity` ranks a row by, so the label always explains the
+ * row's position.
+ *
+ * Offline can only report `lastSeen`, which is stamped on register — and
+ * every client registers right before opening its WS (`gatewayConnectionSrv`,
+ * CLI `registerDevice`) — so it means "last CONNECTED", not "last active".
+ *
+ * A single connection drops the "1 connection" count — it is the common case
+ * and would truncate a narrow line.
+ */
+export const useDeviceActivityText = (device: DeviceListItem) => {
+ const { t } = useTranslation('setting');
+ const channels = device.channels ?? [];
+
+ if (channels.length === 0)
+ return t('devices.lastSeen', { time: dayjs(device.lastSeen).fromNow() });
+
+ const status =
+ channels.length > 1
+ ? t('devices.status.onlineConnections', { count: channels.length })
+ : t('devices.status.online');
+
+ return `${status} · ${t('devices.channel.connected', {
+ time: dayjs(channels[0]?.connectedAt ?? device.lastSeen).fromNow(),
+ })}`;
+};
diff --git a/src/features/DeviceManager/useDeviceList.ts b/src/features/DeviceManager/useDeviceList.ts
index 40c4074a46a..e118fbab98a 100644
--- a/src/features/DeviceManager/useDeviceList.ts
+++ b/src/features/DeviceManager/useDeviceList.ts
@@ -1,6 +1,6 @@
import { isDesktop } from '@lobechat/const';
import type { DeviceListItem } from '@lobechat/types';
-import type { SWRResponse } from 'swr';
+import type { SWRConfiguration, SWRResponse } from 'swr';
import { useClientDataSWR } from '@/libs/swr';
import { deviceService } from '@/services/device';
@@ -24,11 +24,15 @@ import { DEVICE_LIST_SWR_KEY } from './const';
*
* 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 = (): SWRResponse<DeviceListItem[]> => {
+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,
);
};