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(connect-agent): open the connect wizard on a preselected device (#21273)

Rdmclin28fed17cc4d11
diff --git a/src/features/ConnectAgent/deviceListState.test.ts b/src/features/ConnectAgent/deviceListState.test.ts
index 831fe69d177..f4479557819 100644
--- a/src/features/ConnectAgent/deviceListState.test.ts
+++ b/src/features/ConnectAgent/deviceListState.test.ts
@@ -1,6 +1,7 @@
+import type { DeviceListItem } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { getDeviceListState } from './deviceListState';
+import { getDeviceListState, isListableDevice } from './deviceListState';
describe('getDeviceListState', () => {
it('keeps an empty device result in loading state while the request is in flight', () => {
@@ -51,3 +52,17 @@ describe('getDeviceListState when the request fails', () => {
).toBe('loading');
});
});
+
+describe('isListableDevice', () => {
+ const personal = { deviceId: 'dev_p', scope: 'personal' } as DeviceListItem;
+ const shared = { deviceId: 'dev_w', scope: 'workspace' } as DeviceListItem;
+
+ it('keeps personal devices out of a workspace', () => {
+ expect(isListableDevice(personal, true)).toBe(false);
+ expect(isListableDevice(shared, true)).toBe(true);
+ });
+
+ it('lists every device outside a workspace', () => {
+ expect(isListableDevice(personal, false)).toBe(true);
+ });
+});
diff --git a/src/features/ConnectAgent/deviceListState.ts b/src/features/ConnectAgent/deviceListState.ts
index 5cf5eeaf632..9060e6823c1 100644
--- a/src/features/ConnectAgent/deviceListState.ts
+++ b/src/features/ConnectAgent/deviceListState.ts
@@ -1,3 +1,5 @@
+import type { DeviceListItem } from '@lobechat/types';
+
export type DeviceListState = 'empty' | 'error' | 'loading' | 'ready';
interface GetDeviceListStateOptions {
@@ -24,3 +26,10 @@ export const getDeviceListState = ({
if (!isConfirmed) return error ? 'error' : 'loading';
return 'empty';
};
+
+/**
+ * Whether the picker would list this device: inside a workspace only the
+ * workspace's own devices are connectable.
+ */
+export const isListableDevice = (device: DeviceListItem, restrictToWorkspace: boolean) =>
+ !restrictToWorkspace || device.scope === 'workspace';
diff --git a/src/features/ConnectAgent/index.tsx b/src/features/ConnectAgent/index.tsx
index 891b5252509..bbc03b3eec0 100644
--- a/src/features/ConnectAgent/index.tsx
+++ b/src/features/ConnectAgent/index.tsx
@@ -48,7 +48,7 @@ import { isDevicePresenceUnknown, useDeviceList } from '@/store/device';
import { useElectronStore } from '@/store/electron';
import { useHomeStore } from '@/store/home';
-import { getDeviceListState } from './deviceListState';
+import { getDeviceListState, isListableDevice } from './deviceListState';
import type { ConnectableProvider, ConnectAgentProfile } from './providers';
import { buildConnectAgentConfig, CONNECTABLE_PROVIDERS } from './providers';
import type { ScanTarget } from './useAgentScan';
@@ -381,12 +381,14 @@ const AgentScanRow = memo<{
interface ConnectAgentContentProps {
groupId?: string;
+ initialDevice?: DeviceListItem;
onTitleChange: (title: string) => void;
+ showOpenChat?: boolean;
visibility?: 'private' | 'public';
}
const ConnectAgentContent = memo<ConnectAgentContentProps>(
- ({ groupId, onTitleChange, visibility }) => {
+ ({ groupId, initialDevice, onTitleChange, showOpenChat = true, visibility }) => {
const { t } = useTranslation('chat');
const { close, setCanDismissByClickOutside } = useModalContext();
const navigate = useWorkspaceAwareNavigate();
@@ -399,8 +401,15 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
const activeWorkspaceId = useActiveWorkspaceId();
const restrictToWorkspaceDevices = Boolean(activeWorkspaceId);
- const [step, setStep] = useState(0);
- const [target, setTarget] = useState<ScanTarget | null>(null);
+ // A preselected device the picker would not list starts at the picker instead.
+ const preselected =
+ initialDevice && isListableDevice(initialDevice, restrictToWorkspaceDevices)
+ ? initialDevice
+ : undefined;
+ const [step, setStep] = useState(preselected ? 1 : 0);
+ const [target, setTarget] = useState<ScanTarget | null>(() =>
+ preselected ? { device: preselected, kind: 'device' } : null,
+ );
const [selectedTypes, setSelectedTypes] = useState<HeterogeneousAgentType[]>([]);
const [profiles, setProfiles] = useState<
Partial<Record<RemoteHeterogeneousAgentType, ConnectAgentProfile>>
@@ -411,7 +420,7 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
const [createError, setCreateError] = useState<string | undefined>();
const [done, setDone] = useState<CreatedAgent[] | null>(null);
- const { scan, state: scanState } = useAgentScan();
+ const { rescan: rescanTarget, state: scanState } = useAgentScan(target);
useEffect(() => {
setCanDismissByClickOutside(!creating);
@@ -427,7 +436,7 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
} = useDeviceList();
const listedDevices = useMemo(
- () => (devices ?? []).filter((d) => !restrictToWorkspaceDevices || d.scope === 'workspace'),
+ () => (devices ?? []).filter((d) => isListableDevice(d, restrictToWorkspaceDevices)),
[devices, restrictToWorkspaceDevices],
);
const onlineDevices = listedDevices.filter((d) => d.online);
@@ -461,22 +470,17 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
const single = selectedProviders.length === 1 ? selectedProviders[0] : null;
const singleVersion = single ? scanState.agents?.[single.type]?.version : undefined;
- const pickTarget = useCallback(
- (next: ScanTarget) => {
- setTarget(next);
- setSelectedTypes([]);
- setProfiles({});
- setStep(1);
- void scan(next);
- },
- [scan],
- );
+ const pickTarget = useCallback((next: ScanTarget) => {
+ setTarget(next);
+ setSelectedTypes([]);
+ setProfiles({});
+ setStep(1);
+ }, []);
const rescan = useCallback(() => {
- if (!target) return;
setSelectedTypes([]);
- void scan(target);
- }, [scan, target]);
+ rescanTarget();
+ }, [rescanTarget]);
const toggleType = useCallback(
(provider: ConnectableProvider) => {
@@ -607,7 +611,7 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
if (done) {
return (
<Flexbox gap={8} paddingBlock={'16px 8px'}>
- <SectionLabel>{t('connectAgent.create.doneHint')}</SectionLabel>
+ {showOpenChat && <SectionLabel>{t('connectAgent.create.doneHint')}</SectionLabel>}
<div className={styles.groupList}>
{done.map((agent) => (
<div className={`${styles.row} ${styles.rowStatic}`} key={agent.agentId}>
@@ -622,9 +626,11 @@ const ConnectAgentContent = memo<ConnectAgentContentProps>(
</Text>
</Flexbox>
<div className={styles.dot} />
- <Button size={'small'} onClick={() => openChat(agent.agentId)}>
- {t('connectAgent.create.openChat')}
- </Button>
+ {showOpenChat && (
+ <Button size={'small'} onClick={() => openChat(agent.agentId)}>
+ {t('connectAgent.create.openChat')}
+ </Button>
+ )}
</div>
))}
</div>
@@ -1004,6 +1010,10 @@ ConnectAgentContent.displayName = 'ConnectAgentContent';
export interface OpenConnectAgentModalOptions {
groupId?: string;
+ /** Skip the machine picker and scan this device's agents right away. */
+ initialDevice?: DeviceListItem;
+ /** Offer "open chat" on the done view; off for hosts that must not navigate away. */
+ showOpenChat?: boolean;
visibility?: 'private' | 'public';
}
@@ -1016,6 +1026,8 @@ export const openConnectAgentModal = (options?: OpenConnectAgentModalOptions): M
content: (
<ConnectAgentContent
groupId={options?.groupId}
+ initialDevice={options?.initialDevice}
+ showOpenChat={options?.showOpenChat}
visibility={options?.visibility}
onTitleChange={(title) => holder.instance?.update({ title })}
/>
diff --git a/src/features/ConnectAgent/useAgentScan.test.ts b/src/features/ConnectAgent/useAgentScan.test.ts
index b31db526ce7..85976eaa2d2 100644
--- a/src/features/ConnectAgent/useAgentScan.test.ts
+++ b/src/features/ConnectAgent/useAgentScan.test.ts
@@ -1,14 +1,25 @@
+import type { DeviceListItem } from '@lobechat/types';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement } from 'react';
+import { SWRConfig } from 'swr';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { deviceService } from '@/services/device';
+
import {
buildConnectAgentConfig,
buildPlatformAgencyConfig,
getConnectableProvider,
} from './providers';
-import { scanLocal } from './useAgentScan';
+import { scanLocal, useAgentScan } from './useAgentScan';
const detectHeterogeneousAgentCommand = vi.hoisted(() => vi.fn());
+vi.mock('@/services/device', () => ({
+ deviceService: { scanAgents: vi.fn() },
+}));
+
vi.mock('@/services/electron/binary', () => ({
binaryService: { detectHeterogeneousAgentCommand },
}));
@@ -150,3 +161,85 @@ describe('buildConnectAgentConfig', () => {
).toMatchObject({ provider: 'claude-code' });
});
});
+
+describe('useAgentScan', () => {
+ const device = { deviceId: 'dev_1' } as DeviceListItem;
+ const scanAgents = vi.mocked(deviceService.scanAgents);
+ const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { provider: () => new Map() } }, children);
+
+ beforeEach(() => {
+ scanAgents.mockReset();
+ });
+
+ it('stays idle without a target', () => {
+ const { result } = renderHook(() => useAgentScan(null), { wrapper });
+
+ expect(result.current.state).toEqual({ agents: null, status: 'idle' });
+ expect(scanAgents).not.toHaveBeenCalled();
+ });
+
+ it('scans the target device as soon as it is given', async () => {
+ const agents = { 'claude-code': { available: true, version: '1.0.0' } };
+ scanAgents.mockResolvedValue({ agents } as any);
+
+ const { result } = renderHook(() => useAgentScan({ device, kind: 'device' }), { wrapper });
+
+ expect(result.current.state.status).toBe('scanning');
+ await waitFor(() => expect(result.current.state).toEqual({ agents, status: 'success' }));
+ expect(scanAgents).toHaveBeenCalledWith({ deviceId: 'dev_1' });
+ });
+
+ it('reports a device-side scan failure and re-probes on rescan', async () => {
+ scanAgents.mockResolvedValueOnce({ agents: null, error: 'device offline' } as any);
+
+ const { result } = renderHook(() => useAgentScan({ device, kind: 'device' }), { wrapper });
+
+ await waitFor(() =>
+ expect(result.current.state).toEqual({
+ agents: null,
+ error: 'device offline',
+ status: 'error',
+ }),
+ );
+
+ const agents = { codex: { available: true } };
+ scanAgents.mockResolvedValueOnce({ agents } as any);
+ act(() => result.current.rescan());
+
+ await waitFor(() => expect(result.current.state).toEqual({ agents, status: 'success' }));
+ expect(scanAgents).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not re-probe on its own when the connection comes back', async () => {
+ scanAgents.mockResolvedValue({ agents: {} } as any);
+ let reconnect: (() => void) | undefined;
+ const reconnectWrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ {
+ value: {
+ initReconnect: (callback: () => void) => {
+ reconnect = callback;
+ },
+ provider: () => new Map(),
+ },
+ },
+ children,
+ );
+
+ const { result } = renderHook(() => useAgentScan({ device, kind: 'device' }), {
+ wrapper: reconnectWrapper,
+ });
+ await waitFor(() => expect(result.current.state.status).toBe('success'));
+
+ expect(reconnect).toBeDefined();
+ await act(async () => {
+ reconnect!();
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+
+ expect(result.current.state.status).toBe('success');
+ expect(scanAgents).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/features/ConnectAgent/useAgentScan.ts b/src/features/ConnectAgent/useAgentScan.ts
index 40e89a6d9d4..86194ca90c6 100644
--- a/src/features/ConnectAgent/useAgentScan.ts
+++ b/src/features/ConnectAgent/useAgentScan.ts
@@ -1,7 +1,8 @@
import type { HeterogeneousAgentScanMap } from '@lobechat/heterogeneous-agents';
import type { DeviceListItem } from '@lobechat/types';
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useMemo } from 'react';
+import { useClientDataSWR } from '@/libs/swr';
import { deviceService } from '@/services/device';
import { binaryService } from '@/services/electron/binary';
@@ -53,42 +54,40 @@ export const scanLocal = async (): Promise<HeterogeneousAgentScanMap> => {
return Object.fromEntries(entries);
};
-export const useAgentScan = () => {
- const [state, setState] = useState<AgentScanState>(IDLE);
- const seqRef = useRef(0);
+const scanTargetKey = (target: ScanTarget | null) => {
+ if (!target) return null;
+ // Same key as the device page's agent runtimes, so either surface reuses the other's probe.
+ return target.kind === 'local'
+ ? ['connectAgent/localScan']
+ : ['device/agentScan', target.device.deviceId];
+};
- const scan = useCallback(async (target: ScanTarget) => {
- const seq = ++seqRef.current;
- setState({ agents: null, status: 'scanning' });
+/**
+ * The agent inventory of the picked target. Keyed by target, so picking one
+ * (or opening the wizard on one) scans it; `rescan` re-probes in place.
+ */
+export const useAgentScan = (target: ScanTarget | null) => {
+ const { data, error, isValidating, mutate } = useClientDataSWR(
+ scanTargetKey(target),
+ async (): Promise<{ agents: HeterogeneousAgentScanMap | null; error?: string }> =>
+ target?.kind === 'device'
+ ? deviceService.scanAgents({ deviceId: target.device.deviceId })
+ : { agents: await scanLocal() },
+ // Only an explicit rescan re-probes: it also clears the picked runtimes, which
+ // a silent refresh (focus, reconnect, retry) would leave pointing at stale rows.
+ { revalidateOnFocus: false, revalidateOnReconnect: false, shouldRetryOnError: false },
+ );
- try {
- let agents: HeterogeneousAgentScanMap;
- if (target.kind === 'local') {
- agents = await scanLocal();
- } else {
- const result = await deviceService.scanAgents({ deviceId: target.device.deviceId });
- if (result.error) {
- if (seq === seqRef.current)
- setState({ agents: null, error: result.error, status: 'error' });
- return;
- }
- agents = result.agents;
- }
- if (seq === seqRef.current) setState({ agents, status: 'success' });
- } catch (error) {
- if (seq === seqRef.current)
- setState({
- agents: null,
- error: error instanceof Error ? error.message : String(error),
- status: 'error',
- });
- }
- }, []);
+ const state = useMemo<AgentScanState>(() => {
+ if (!target) return IDLE;
+ if (isValidating) return { agents: null, status: 'scanning' };
+ const failure = error ? (error instanceof Error ? error.message : String(error)) : data?.error;
+ if (failure) return { agents: null, error: failure, status: 'error' };
+ if (!data) return { agents: null, status: 'scanning' };
+ return { agents: data.agents, status: 'success' };
+ }, [data, error, isValidating, target]);
- const reset = useCallback(() => {
- seqRef.current += 1;
- setState(IDLE);
- }, []);
+ const rescan = useCallback(() => void mutate(), [mutate]);
- return { reset, scan, state };
+ return { rescan, state };
};