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): CLI delete, scrollable device panels, and multi-select delete (#16299)

Arvin Xub17f9656c583
diff --git a/apps/cli/src/commands/device.test.ts b/apps/cli/src/commands/device.test.ts
new file mode 100644
index 00000000000..239d4d9795e
--- /dev/null
+++ b/apps/cli/src/commands/device.test.ts
@@ -0,0 +1,167 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as FormatUtils from '../utils/format';
+import { log } from '../utils/logger';
+import { registerDeviceCommand } from './device';
+
+const { mockTrpcClient } = vi.hoisted(() => ({
+ mockTrpcClient: {
+ device: {
+ getDeviceSystemInfo: { query: vi.fn() },
+ listDevices: { query: vi.fn() },
+ removeDevice: { mutate: vi.fn() },
+ removeWorkspaceDevice: { mutate: vi.fn() },
+ status: { query: vi.fn() },
+ },
+ },
+}));
+
+const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({
+ getTrpcClient: vi.fn(),
+}));
+
+const { mockConfirm } = vi.hoisted(() => ({
+ mockConfirm: vi.fn(),
+}));
+
+vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
+vi.mock('../utils/logger', () => ({
+ log: { debug: vi.fn(), error: vi.fn(), heartbeat: vi.fn(), info: vi.fn(), warn: vi.fn() },
+ setVerbose: vi.fn(),
+}));
+vi.mock('../utils/format', async (importOriginal) => {
+ const actual = await importOriginal<typeof FormatUtils>();
+ return { ...actual, confirm: mockConfirm };
+});
+
+describe('device command', () => {
+ let exitSpy: ReturnType<typeof vi.spyOn>;
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ mockConfirm.mockReset();
+ for (const method of Object.values(mockTrpcClient.device)) {
+ for (const fn of Object.values(method)) {
+ (fn as ReturnType<typeof vi.fn>).mockReset();
+ }
+ }
+ // Default: the deletable ids exist as PERSONAL devices, so `delete` resolves
+ // them to the personal `removeDevice` path. Tests override per-scope as needed.
+ mockTrpcClient.device.listDevices.query.mockResolvedValue([
+ { deviceId: 'd1', scope: 'personal' },
+ { deviceId: 'd2', scope: 'personal' },
+ { deviceId: '8040798a77ae', scope: 'personal' },
+ ]);
+ });
+
+ afterEach(() => {
+ exitSpy.mockRestore();
+ consoleSpy.mockRestore();
+ });
+
+ function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ registerDeviceCommand(program);
+ return program;
+ }
+
+ describe('delete', () => {
+ it('should remove a device with --yes (no prompt)', async () => {
+ mockTrpcClient.device.removeDevice.mutate.mockResolvedValue({ success: true });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'device', 'delete', 'd1', '--yes']);
+
+ expect(mockConfirm).not.toHaveBeenCalled();
+ expect(mockTrpcClient.device.removeDevice.mutate).toHaveBeenCalledWith({ deviceId: 'd1' });
+ });
+
+ it('should remove multiple devices in one call', async () => {
+ mockTrpcClient.device.removeDevice.mutate.mockResolvedValue({ success: true });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'device', 'delete', 'd1', 'd2', '--yes']);
+
+ expect(mockTrpcClient.device.removeDevice.mutate).toHaveBeenNthCalledWith(1, {
+ deviceId: 'd1',
+ });
+ expect(mockTrpcClient.device.removeDevice.mutate).toHaveBeenNthCalledWith(2, {
+ deviceId: 'd2',
+ });
+ });
+
+ it('should be reachable via the `remove` alias', async () => {
+ mockTrpcClient.device.removeDevice.mutate.mockResolvedValue({ success: true });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'device', 'remove', 'd1', '--yes']);
+
+ expect(mockTrpcClient.device.removeDevice.mutate).toHaveBeenCalledWith({ deviceId: 'd1' });
+ });
+
+ it('should prompt for confirmation and remove when confirmed', async () => {
+ mockConfirm.mockResolvedValue(true);
+ mockTrpcClient.device.removeDevice.mutate.mockResolvedValue({ success: true });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'device', 'delete', 'd1']);
+
+ expect(mockConfirm).toHaveBeenCalledTimes(1);
+ expect(mockTrpcClient.device.removeDevice.mutate).toHaveBeenCalledWith({ deviceId: 'd1' });
+ });
+
+ it('should cancel without removing when not confirmed', async () => {
+ mockConfirm.mockResolvedValue(false);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'device', 'delete', 'd1']);
+
+ expect(mockTrpcClient.device.removeDevice.mutate).not.toHaveBeenCalled();
+ expect(consoleSpy).toHaveBeenCalledWith('Cancelled.');
+ });
+
+ it('should exit(1) when a removal fails', async () => {
+ mockTrpcClient.device.removeDevice.mutate.mockRejectedValue(new Error('boom'));
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'device', 'delete', 'd1', '--yes']);
+
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('boom'));
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+
+ it('should route a workspace device to removeWorkspaceDevice', async () => {
+ mockTrpcClient.device.listDevices.query.mockResolvedValue([
+ { deviceId: 'ws1', scope: 'workspace' },
+ ]);
+ mockTrpcClient.device.removeWorkspaceDevice.mutate.mockResolvedValue({ success: true });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'device', 'delete', 'ws1', '--yes']);
+
+ expect(mockTrpcClient.device.removeWorkspaceDevice.mutate).toHaveBeenCalledWith({
+ deviceId: 'ws1',
+ });
+ expect(mockTrpcClient.device.removeDevice.mutate).not.toHaveBeenCalled();
+ });
+
+ it('should error + exit(1) without deleting when the device is not in the list', async () => {
+ mockTrpcClient.device.listDevices.query.mockResolvedValue([
+ { deviceId: 'other', scope: 'personal' },
+ ]);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'device', 'delete', 'missing', '--yes']);
+
+ expect(mockTrpcClient.device.removeDevice.mutate).not.toHaveBeenCalled();
+ expect(mockTrpcClient.device.removeWorkspaceDevice.mutate).not.toHaveBeenCalled();
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('was not found'));
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+ });
+});
diff --git a/apps/cli/src/commands/device.ts b/apps/cli/src/commands/device.ts
index 51be6307c88..88364408d3e 100644
--- a/apps/cli/src/commands/device.ts
+++ b/apps/cli/src/commands/device.ts
@@ -2,7 +2,7 @@ import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
-import { outputJson, printTable, timeAgo } from '../utils/format';
+import { confirm, outputJson, printTable, timeAgo } from '../utils/format';
import { log } from '../utils/logger';
export function registerDeviceCommand(program: Command) {
@@ -75,6 +75,60 @@ export function registerDeviceCommand(program: Command) {
console.log(` Videos : ${info.videosPath}`);
});
+ // ── delete ────────────────────────────────────────────
+
+ device
+ .command('delete <deviceId...>')
+ .alias('remove')
+ .description('Remove one or more devices from your account')
+ .option('--yes', 'Skip confirmation prompt')
+ .action(async (deviceIds: string[], options: { yes?: boolean }) => {
+ if (!options.yes) {
+ const label =
+ deviceIds.length === 1 ? `device "${deviceIds[0]}"` : `${deviceIds.length} devices`;
+ const confirmed = await confirm(`Are you sure you want to remove ${label}?`);
+ if (!confirmed) {
+ console.log('Cancelled.');
+ return;
+ }
+ }
+
+ const client = await getTrpcClient();
+
+ // Resolve each device's scope first: workspace devices are owner-gated and
+ // live in a separate pool, so they need `removeWorkspaceDevice`, not the
+ // personal `removeDevice`. Routing blindly through the personal path would
+ // no-op on a workspace device yet still print success. `listDevices`
+ // already returns both pools (only when a workspace context is set).
+ const devices = await client.device.listDevices.query();
+ const byId = new Map(devices.map((d: any) => [d.deviceId, d]));
+
+ let failed = 0;
+ for (const deviceId of deviceIds) {
+ const device = byId.get(deviceId);
+ if (!device) {
+ failed += 1;
+ log.error(
+ `Device "${deviceId}" was not found. Run 'lh device list' to see available devices.`,
+ );
+ continue;
+ }
+ try {
+ if (device.scope === 'workspace') {
+ await client.device.removeWorkspaceDevice.mutate({ deviceId });
+ } else {
+ await client.device.removeDevice.mutate({ deviceId });
+ }
+ console.log(`${pc.green('✓')} Removed device ${pc.bold(deviceId)}`);
+ } catch (e) {
+ failed += 1;
+ log.error(`Failed to remove "${deviceId}": ${(e as Error).message}`);
+ }
+ }
+
+ if (failed > 0) process.exit(1);
+ });
+
// ── status ────────────────────────────────────────────
device
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 24b1d2702cf..f98ffaf5cac 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -280,6 +280,7 @@
"defaultAgent.title": "New Agent",
"devices.actions.edit": "Edit",
"devices.actions.remove": "Remove",
+ "devices.actions.removeSelected": "Remove ({{count}})",
"devices.capabilities.commands.desc": "Safely execute terminal commands in your environment.",
"devices.capabilities.commands.title": "Run commands",
"devices.capabilities.files.desc": "Let agents directly access and organize the files on your computer.",
@@ -332,6 +333,10 @@
"devices.lastSeen": "Last active {{time}}",
"devices.remove.confirm": "Remove this device?",
"devices.remove.confirmDesc": "This disconnects the device from your account. It does not sign the device out, and it can re-register on next connect.",
+ "devices.remove.confirmMany": "Remove {{count}} devices?",
+ "devices.remove.confirmManyDesc": "This disconnects the selected devices from your account. They are not signed out, and each can re-register on next connect.",
+ "devices.selection.selected": "{{count}} selected",
+ "devices.selection.total": "{{count}} devices",
"devices.status.offline": "Offline",
"devices.status.online": "Online",
"devices.title": "My Devices",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 6fcff7993ad..c760aa928e9 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -280,6 +280,7 @@
"defaultAgent.title": "新建助理",
"devices.actions.edit": "编辑",
"devices.actions.remove": "移除",
+ "devices.actions.removeSelected": "移除({{count}})",
"devices.capabilities.commands.desc": "在你的环境中安全地执行终端命令。",
"devices.capabilities.commands.title": "运行命令",
"devices.capabilities.files.desc": "让智能体直接访问并整理你电脑上的文件。",
@@ -332,6 +333,10 @@
"devices.lastSeen": "最近活跃 {{time}}",
"devices.remove.confirm": "移除此设备?",
"devices.remove.confirmDesc": "这会断开设备与你账户的关联,但不会让设备登出,下次连接时它可重新注册。",
+ "devices.remove.confirmMany": "移除这 {{count}} 台设备?",
+ "devices.remove.confirmManyDesc": "这会断开所选设备与你账户的关联,它们不会被登出,下次连接时均可重新注册。",
+ "devices.selection.selected": "已选 {{count}} 项",
+ "devices.selection.total": "{{count}} 台设备",
"devices.status.offline": "离线",
"devices.status.online": "在线",
"devices.title": "我的设备",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 98c5809c3d6..2fe47d0e04e 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -339,6 +339,7 @@ export default {
'creds.view.warning': 'These values are sensitive. Do not share them with others.',
'devices.actions.edit': 'Edit',
'devices.actions.remove': 'Remove',
+ 'devices.actions.removeSelected': 'Remove ({{count}})',
'devices.channel.connected': 'Connected {{time}}',
'devices.currentBadge': 'This device',
'devices.detail.addDir': 'Add directory',
@@ -404,6 +405,11 @@ export default {
'devices.remove.confirm': 'Remove this device?',
'devices.remove.confirmDesc':
'This disconnects the device from your account. It does not sign the device out, and it can re-register on next connect.',
+ 'devices.remove.confirmMany': 'Remove {{count}} devices?',
+ 'devices.remove.confirmManyDesc':
+ 'This disconnects the selected devices from your account. They are not signed out, and each can re-register on next connect.',
+ 'devices.selection.selected': '{{count}} selected',
+ 'devices.selection.total': '{{count}} devices',
'devices.status.offline': 'Offline',
'devices.status.online': 'Online',
'devices.title': 'My Devices',
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index b8a2eb4a8ae..2608dd06100 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -93,6 +93,17 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorSuccess};
box-shadow: 0 0 0 2px ${cssVar.colorSuccessBg};
`,
+ deviceList: css`
+ overflow-y: auto;
+
+ /* Cap the device section so a long list (servers/CLI fleets) stays scrollable
+ inside the popover instead of growing past the viewport. */
+ max-height: 240px;
+
+ /* Room for the scrollbar so rows don't sit flush against it. */
+ margin-inline-end: -4px;
+ padding-inline-end: 4px;
+ `,
empty: css`
padding-block: 8px;
padding-inline: 8px;
@@ -556,22 +567,28 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
label={t('heteroAgent.executionTarget.sandbox')}
onClick={() => void handleSelect('sandbox')}
/>
- {showDeviceGroups ? (
- <>
- {personalDevices.length > 0 ? (
+ {deviceRows.length > 0 ? (
+ <div className={styles.deviceList}>
+ {showDeviceGroups ? (
<>
+ {personalDevices.length > 0 ? (
+ <>
+ <div className={styles.groupLabel}>
+ {t('heteroAgent.executionTarget.personalGroup')}
+ </div>
+ {personalDevices.map((d) => renderDeviceRow(d))}
+ </>
+ ) : null}
<div className={styles.groupLabel}>
- {t('heteroAgent.executionTarget.personalGroup')}
+ {t('heteroAgent.executionTarget.workspaceGroup')}
</div>
- {personalDevices.map((d) => renderDeviceRow(d))}
+ {workspaceDevices.map((d) => renderDeviceRow(d))}
</>
- ) : null}
- <div className={styles.groupLabel}>{t('heteroAgent.executionTarget.workspaceGroup')}</div>
- {workspaceDevices.map((d) => renderDeviceRow(d))}
- </>
- ) : (
- personalDevices.map((d) => renderDeviceRow(d))
- )}
+ ) : (
+ personalDevices.map((d) => renderDeviceRow(d))
+ )}
+ </div>
+ ) : null}
{hasNoDevices && isLoading ? (
<div className={styles.empty}>{t('heteroAgent.executionTarget.loading')}</div>
) : null}
diff --git a/src/features/DeviceManager/DeviceItem.tsx b/src/features/DeviceManager/DeviceItem.tsx
index 8c21a754137..7c4b84ec4f8 100644
--- a/src/features/DeviceManager/DeviceItem.tsx
+++ b/src/features/DeviceManager/DeviceItem.tsx
@@ -1,7 +1,7 @@
'use client';
import type { DeviceListItem } from '@lobechat/types';
-import { ActionIcon, DropdownMenu, Flexbox, Icon, Tag, Text, Tooltip } from '@lobehub/ui';
+import { ActionIcon, Checkbox, DropdownMenu, Flexbox, Icon, Tag, Text, Tooltip } from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import dayjs from 'dayjs';
@@ -60,101 +60,119 @@ const styles = createStaticStyles(({ css }) => ({
}));
interface DeviceItemProps {
+ /** Whether this row is ticked for bulk actions. */
+ checked?: boolean;
device: DeviceListItem;
isCurrent?: boolean;
+ /** Toggle the bulk-selection checkbox. When provided the checkbox is shown. */
+ onCheckChange?: (checked: boolean) => void;
onSelect: () => void;
selected?: boolean;
}
-const DeviceItem = memo<DeviceItemProps>(({ device, isCurrent, onSelect, selected }) => {
- const { t } = useTranslation('setting');
-
- // Workspace devices are owner-gated + workspace-scoped on the server; personal
- // devices stay userId-scoped. Route by the device's own scope.
- const onRemoveSuccess = () => refreshDeviceList();
- const removePersonal = lambdaQuery.device.removeDevice.useMutation({
- onSuccess: onRemoveSuccess,
- });
- const removeWorkspace = lambdaQuery.device.removeWorkspaceDevice.useMutation({
- onSuccess: onRemoveSuccess,
- });
- const removeDevice = device.scope === 'workspace' ? removeWorkspace : removePersonal;
-
- const displayName = device.friendlyName || device.hostname || device.deviceId;
- const isFallback = device.identitySource === 'fallback';
- // Online when the device has at least one live connection in `device.channels`.
- const channels = device.channels ?? [];
- const online = channels.length > 0;
- const statusTooltip = online
- ? t('devices.channel.connected', {
- time: dayjs(channels[0]?.connectedAt ?? device.lastSeen).fromNow(),
- })
- : t('devices.lastSeen', { time: dayjs(device.lastSeen).fromNow() });
-
- const handleRemove = () =>
- confirmModal({
- content: t('devices.remove.confirmDesc'),
- okButtonProps: { danger: true },
- okText: t('devices.actions.remove'),
- onOk: async () => {
- await removeDevice.mutateAsync({ deviceId: device.deviceId });
- },
- title: t('devices.remove.confirm'),
- });
+const DeviceItem = memo<DeviceItemProps>(
+ ({ checked, device, isCurrent, onCheckChange, onSelect, selected }) => {
+ const { t } = useTranslation('setting');
- return (
- <Flexbox
- horizontal
- align={'flex-start'}
- className={cx(styles.row, selected && styles.rowActive)}
- gap={12}
- onClick={onSelect}
- >
- <span className={styles.icon} style={{ marginBlockStart: 2 }}>
- {getDeviceIcon(device.platform)}
- </span>
- <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Text ellipsis weight={500}>
- {displayName}
- </Text>
- <Tooltip title={statusTooltip}>
- <span className={online ? styles.dotOnline : styles.dotOffline} />
- </Tooltip>
- {isCurrent && <Tag>{t('devices.currentBadge')}</Tag>}
- {isFallback && (
- <Tooltip title={t('devices.fallbackTooltip')}>
- <Tag icon={<Icon icon={TriangleAlertIcon} />}>{t('devices.fallbackBadge')}</Tag>
+ // Workspace devices are owner-gated + workspace-scoped on the server; personal
+ // devices stay userId-scoped. Route by the device's own scope.
+ const onRemoveSuccess = () => refreshDeviceList();
+ const removePersonal = lambdaQuery.device.removeDevice.useMutation({
+ onSuccess: onRemoveSuccess,
+ });
+ const removeWorkspace = lambdaQuery.device.removeWorkspaceDevice.useMutation({
+ onSuccess: onRemoveSuccess,
+ });
+ const removeDevice = device.scope === 'workspace' ? removeWorkspace : removePersonal;
+
+ const displayName = device.friendlyName || device.hostname || device.deviceId;
+ const isFallback = device.identitySource === 'fallback';
+ // Online when the device has at least one live connection in `device.channels`.
+ const channels = device.channels ?? [];
+ const online = channels.length > 0;
+ const statusTooltip = online
+ ? t('devices.channel.connected', {
+ time: dayjs(channels[0]?.connectedAt ?? device.lastSeen).fromNow(),
+ })
+ : t('devices.lastSeen', { time: dayjs(device.lastSeen).fromNow() });
+
+ const handleRemove = () =>
+ confirmModal({
+ content: t('devices.remove.confirmDesc'),
+ okButtonProps: { danger: true },
+ okText: t('devices.actions.remove'),
+ onOk: async () => {
+ await removeDevice.mutateAsync({ deviceId: device.deviceId });
+ },
+ title: t('devices.remove.confirm'),
+ });
+
+ return (
+ <Flexbox
+ horizontal
+ align={'flex-start'}
+ className={cx(styles.row, selected && styles.rowActive)}
+ gap={12}
+ onClick={onSelect}
+ >
+ {onCheckChange && (
+ <span
+ style={{ marginBlockStart: 2 }}
+ onClick={(e) => {
+ // Ticking a row is a bulk-select action, not a "open detail" click.
+ e.stopPropagation();
+ onCheckChange(!checked);
+ }}
+ >
+ <Checkbox checked={checked} />
+ </span>
+ )}
+ <span className={styles.icon} style={{ marginBlockStart: 2 }}>
+ {getDeviceIcon(device.platform)}
+ </span>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text ellipsis weight={500}>
+ {displayName}
+ </Text>
+ <Tooltip title={statusTooltip}>
+ <span className={online ? styles.dotOnline : styles.dotOffline} />
</Tooltip>
+ {isCurrent && <Tag>{t('devices.currentBadge')}</Tag>}
+ {isFallback && (
+ <Tooltip title={t('devices.fallbackTooltip')}>
+ <Tag icon={<Icon icon={TriangleAlertIcon} />}>{t('devices.fallbackBadge')}</Tag>
+ </Tooltip>
+ )}
+ </Flexbox>
+ {device.defaultCwd && (
+ <Flexbox horizontal align={'center'} gap={6}>
+ <Icon icon={FolderIcon} size={12} style={{ color: cssVar.colorTextQuaternary }} />
+ <Text className={styles.cwd} style={{ fontSize: 12 }} type={'secondary'}>
+ {device.defaultCwd}
+ </Text>
+ </Flexbox>
)}
</Flexbox>
- {device.defaultCwd && (
- <Flexbox horizontal align={'center'} gap={6}>
- <Icon icon={FolderIcon} size={12} style={{ color: cssVar.colorTextQuaternary }} />
- <Text className={styles.cwd} style={{ fontSize: 12 }} type={'secondary'}>
- {device.defaultCwd}
- </Text>
- </Flexbox>
- )}
+ <span onClick={(e) => e.stopPropagation()}>
+ <DropdownMenu
+ items={[
+ {
+ danger: true,
+ icon: <Icon icon={Trash2Icon} />,
+ key: 'remove',
+ label: t('devices.actions.remove'),
+ onClick: handleRemove,
+ },
+ ]}
+ >
+ <ActionIcon icon={MoreVerticalIcon} />
+ </DropdownMenu>
+ </span>
</Flexbox>
- <span onClick={(e) => e.stopPropagation()}>
- <DropdownMenu
- items={[
- {
- danger: true,
- icon: <Icon icon={Trash2Icon} />,
- key: 'remove',
- label: t('devices.actions.remove'),
- onClick: handleRemove,
- },
- ]}
- >
- <ActionIcon icon={MoreVerticalIcon} />
- </DropdownMenu>
- </span>
- </Flexbox>
- );
-});
+ );
+ },
+);
DeviceItem.displayName = 'DeviceItem';
diff --git a/src/features/DeviceManager/DeviceManager.tsx b/src/features/DeviceManager/DeviceManager.tsx
index 7d36ace7381..13e9a0a6354 100644
--- a/src/features/DeviceManager/DeviceManager.tsx
+++ b/src/features/DeviceManager/DeviceManager.tsx
@@ -2,7 +2,8 @@
import { isDesktop } from '@lobechat/const';
import type { DeviceScope } from '@lobechat/types';
-import { Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';
+import { Button, Checkbox, Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';
+import { confirmModal } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import {
ChevronRightIcon,
@@ -12,18 +13,20 @@ import {
ServerIcon,
ShieldCheckIcon,
TerminalIcon,
+ Trash2Icon,
ZapIcon,
} from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useClientDataSWR } from '@/libs/swr';
+import { lambdaQuery } from '@/libs/trpc/client';
import { deviceService } from '@/services/device';
import { useElectronStore } from '@/store/electron';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
-import { DEVICE_LIST_SWR_KEY } from './const';
+import { DEVICE_LIST_SWR_KEY, refreshDeviceList } from './const';
import DeviceDetailPanel from './DeviceDetailPanel';
import DeviceItem from './DeviceItem';
@@ -104,6 +107,22 @@ const styles = createStaticStyles(({ css }) => ({
border: 1px solid ${cssVar.colorBorderSecondary};
border-radius: ${cssVar.borderRadiusLG};
`,
+ listHeader: css`
+ padding-block: 8px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ listScroll: css`
+ overflow-y: auto;
+
+ /* Cap the list so long fleets (servers / CLI agents) stay scrollable instead
+ of pushing the page — pairs with the detail panel sitting beside it. */
+ max-height: 480px;
+ `,
+ selectAll: css`
+ cursor: pointer;
+ user-select: none;
+ `,
option: css`
cursor: pointer;
padding: 20px;
@@ -250,6 +269,13 @@ const DeviceManager = memo<DeviceManagerProps>(({ onConnect, scope }) => {
const currentDeviceId = !isWorkspace && isDesktop ? gatewayDeviceInfo?.deviceId : undefined;
const [selectedId, setSelectedId] = useState<string>();
+ const [checkedIds, setCheckedIds] = useState<Set<string>>(() => new Set());
+
+ // Bulk remove routes by the managed scope (the list is single-scope), mirroring
+ // the per-row mutation choice in `DeviceItem`.
+ const removePersonal = lambdaQuery.device.removeDevice.useMutation();
+ const removeWorkspace = lambdaQuery.device.removeWorkspaceDevice.useMutation();
+ const removeMutation = isWorkspace ? removeWorkspace : removePersonal;
if (isLoading) return <Skeleton active paragraph={{ rows: 4 }} title={false} />;
@@ -297,20 +323,90 @@ const DeviceManager = memo<DeviceManagerProps>(({ onConnect, scope }) => {
const selected = selectedId ? devices.find((d) => d.deviceId === selectedId) : undefined;
const isCurrent = (id: string) => !!currentDeviceId && id === currentDeviceId;
+ // Only count ids that still exist in the current scope's list, so a stale tick
+ // (e.g. a device removed elsewhere) never inflates the toolbar count.
+ const checkedCount = devices.filter((d) => checkedIds.has(d.deviceId)).length;
+ const allChecked = devices.length > 0 && checkedCount === devices.length;
+ const someChecked = checkedCount > 0 && !allChecked;
+
+ const toggleChecked = (deviceId: string, next: boolean) =>
+ setCheckedIds((prev) => {
+ const draft = new Set(prev);
+ if (next) draft.add(deviceId);
+ else draft.delete(deviceId);
+ return draft;
+ });
+
+ const toggleAll = () =>
+ setCheckedIds(allChecked ? new Set() : new Set(devices.map((d) => d.deviceId)));
+
+ const handleBulkRemove = () => {
+ const ids = devices.filter((d) => checkedIds.has(d.deviceId)).map((d) => d.deviceId);
+ if (ids.length === 0) return;
+ confirmModal({
+ content: t('devices.remove.confirmManyDesc', { count: ids.length }),
+ okButtonProps: { danger: true },
+ okText: t('devices.actions.removeSelected', { count: ids.length }),
+ onOk: async () => {
+ await Promise.all(ids.map((deviceId) => removeMutation.mutateAsync({ deviceId })));
+ await refreshDeviceList();
+ setCheckedIds(new Set());
+ if (selectedId && ids.includes(selectedId)) setSelectedId(undefined);
+ },
+ title: t('devices.remove.confirmMany', { count: ids.length }),
+ });
+ };
+
return (
<Flexbox horizontal align={'flex-start'} gap={16}>
- <Flexbox className={styles.listCol} flex={1} padding={4}>
- {devices.map((device) => (
- <DeviceItem
- device={device}
- isCurrent={isCurrent(device.deviceId)}
- key={device.deviceId}
- selected={device.deviceId === selectedId}
- onSelect={() =>
- setSelectedId((prev) => (prev === device.deviceId ? undefined : device.deviceId))
- }
- />
- ))}
+ <Flexbox className={styles.listCol} flex={1}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.listHeader}
+ justify={'space-between'}
+ >
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.selectAll}
+ gap={8}
+ onClick={toggleAll}
+ >
+ <Checkbox checked={allChecked} indeterminate={someChecked} />
+ <Text style={{ fontSize: 13 }} type={'secondary'}>
+ {checkedCount > 0
+ ? t('devices.selection.selected', { count: checkedCount })
+ : t('devices.selection.total', { count: devices.length })}
+ </Text>
+ </Flexbox>
+ {checkedCount > 0 && (
+ <Button
+ danger
+ icon={<Icon icon={Trash2Icon} />}
+ loading={removeMutation.isPending}
+ size={'small'}
+ onClick={handleBulkRemove}
+ >
+ {t('devices.actions.removeSelected', { count: checkedCount })}
+ </Button>
+ )}
+ </Flexbox>
+ <Flexbox className={styles.listScroll} padding={4}>
+ {devices.map((device) => (
+ <DeviceItem
+ checked={checkedIds.has(device.deviceId)}
+ device={device}
+ isCurrent={isCurrent(device.deviceId)}
+ key={device.deviceId}
+ selected={device.deviceId === selectedId}
+ onCheckChange={(next) => toggleChecked(device.deviceId, next)}
+ onSelect={() =>
+ setSelectedId((prev) => (prev === device.deviceId ? undefined : device.deviceId))
+ }
+ />
+ ))}
+ </Flexbox>
</Flexbox>
{selected && (
<Flexbox className={styles.detailCol} flex={1}>