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.

πŸ› fix(task): let local-target tasks pick a working directory (#20386)

Arvin Xuf27224f32708
diff --git a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.test.tsx b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.test.tsx
new file mode 100644
index 00000000000..f1ad8f0f2c4
--- /dev/null
+++ b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.test.tsx
@@ -0,0 +1,49 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import TaskWorkingDirectoryChip from './TaskWorkingDirectoryChip';
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ // Render the picker inline so the recents are assertable without opening it.
+ Popover: ({ children, content }: { children: ReactNode; content: ReactNode }) => (
+ <>
+ {children}
+ {content}
+ </>
+ ),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/features/WorkingDirectory', () => ({ openAddWorkingDirModal: vi.fn() }));
+
+vi.mock('@/services/device', () => ({ deviceService: { statPath: vi.fn() } }));
+
+vi.mock('@/features/DeviceManager/useDeviceList', () => ({
+ useDeviceList: () => ({
+ data: [
+ {
+ defaultCwd: null,
+ deviceId: 'device-1',
+ workingDirs: [{ path: '/repos/notification-center' }],
+ },
+ ],
+ }),
+}));
+
+describe('TaskWorkingDirectoryChip', () => {
+ // The recents used to come from the device store, which a task page may never
+ // populate β€” the picker listed no directories on a cold load.
+ it('lists the recents of the target device from the device list', () => {
+ render(<TaskWorkingDirectoryChip deviceId="device-1" onChange={vi.fn()} />);
+
+ expect(screen.getByText('/repos/notification-center')).toBeInTheDocument();
+ });
+});
diff --git a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx
index e59bc5c536e..eac27408af2 100644
--- a/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx
+++ b/src/features/AgentTasks/features/TaskWorkingDirectoryChip.tsx
@@ -11,13 +11,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 { deviceSelectors, useDeviceStore } from '@/store/device';
import { taskExecutionStyles as styles } from './taskExecutionStyles';
import TaskPickerOption from './TaskPickerOption';
@@ -51,12 +51,16 @@ const TaskWorkingDirectoryChip = memo<TaskWorkingDirectoryChipProps>(
const { t: tDevice } = useTranslation('device');
const [open, setOpen] = useState(false);
- const rawRecents = useDeviceStore(deviceSelectors.getDeviceWorkingDirs(deviceId));
- const rawDeviceDefaultCwd = useDeviceStore(deviceSelectors.getDeviceDefaultCwd(deviceId));
- const deviceDefaultCwd = getWorkingDirectoryPathString(rawDeviceDefaultCwd);
+ // 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.
+ const { data: devices } = useDeviceList();
+ const device = devices?.find((item) => item.deviceId === deviceId);
+ const deviceDefaultCwd = getWorkingDirectoryPathString(device?.defaultCwd ?? undefined);
+ const rawRecents = device?.workingDirs;
const recents = useMemo(
- () => rawRecents.filter((entry) => !!getWorkingDirectoryPathString(entry.path)),
+ () => (rawRecents ?? []).filter((entry) => !!getWorkingDirectoryPathString(entry.path)),
[rawRecents],
);
diff --git a/src/features/AgentTasks/features/useTaskRunTarget.test.ts b/src/features/AgentTasks/features/useTaskRunTarget.test.ts
index cc10832a017..14bafbdf33e 100644
--- a/src/features/AgentTasks/features/useTaskRunTarget.test.ts
+++ b/src/features/AgentTasks/features/useTaskRunTarget.test.ts
@@ -28,7 +28,22 @@ 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 }[],
- deviceState: { defaultCwd: {} as Record<string, string>, workingDirs: {} as Record<string, []> },
+ electron: { currentDeviceId: undefined as string | undefined, isDesktop: false },
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return {
+ ...actual,
+ get isDesktop() {
+ return mocks.electron.isDesktop;
+ },
+ };
+});
+
+vi.mock('@/store/electron', () => ({
+ useElectronStore: (selector: (state: unknown) => unknown) =>
+ selector({ gatewayDeviceInfo: { deviceId: mocks.electron.currentDeviceId } }),
}));
vi.mock('react-i18next', () => ({
@@ -59,17 +74,6 @@ vi.mock('@/store/agent/selectors', () => ({
agentByIdSelectors: { isAgentHeterogeneousById: () => () => true },
}));
-vi.mock('@/store/device', () => ({
- deviceSelectors: {
- getDeviceDefaultCwd: (deviceId?: string) => (state: (typeof mocks)['deviceState']) =>
- state.defaultCwd[deviceId ?? ''],
- getDeviceWorkingDirs: (deviceId?: string) => (state: (typeof mocks)['deviceState']) =>
- state.workingDirs[deviceId ?? ''] ?? [],
- },
- useDeviceStore: (selector: (state: (typeof mocks)['deviceState']) => unknown) =>
- selector(mocks.deviceState),
-}));
-
const deviceBoundAgent = {
boundDeviceId: DEVICE_AGENT_BOUND,
executionTarget: 'device',
@@ -83,7 +87,7 @@ beforeEach(() => {
mocks.agency.isPreferenceLoading = false;
mocks.agentState.agentMap = {};
mocks.devices = [];
- mocks.deviceState = { defaultCwd: {}, workingDirs: {} };
+ mocks.electron = { currentDeviceId: undefined, isDesktop: false };
});
describe('useTaskRunTarget', () => {
@@ -113,6 +117,54 @@ describe('useTaskRunTarget', () => {
expect(result.current.pinnedDeviceId).toBeUndefined();
});
+ it('offers the directory control for a local target on this desktop', () => {
+ // A `local` run still starts in a path on a machine β€” this desktop. This
+ // used to report `none`, leaving the task with a dead "Follow agent" hint.
+ mocks.electron = { currentDeviceId: 'device-this-desktop', isDesktop: true };
+ mocks.agency.agencyConfig = {
+ executionTarget: 'local',
+ heterogeneousProvider: { type: 'claude-code' },
+ };
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+
+ expect(result.current.inheritedTarget).toBe('local');
+ expect(result.current.deviceId).toBe('device-this-desktop');
+ expect(result.current.directoryKind).toBe('device');
+ expect(result.current.pinnedDeviceId).toBeUndefined();
+ });
+
+ it('prefers the bound device for a local target, the machine the server routes to', () => {
+ mocks.electron = { currentDeviceId: 'device-this-desktop', isDesktop: true };
+ mocks.agency.agencyConfig = {
+ boundDeviceId: DEVICE_AGENT_BOUND,
+ executionTarget: 'local',
+ heterogeneousProvider: { type: 'claude-code' },
+ };
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+
+ expect(result.current.deviceId).toBe(DEVICE_AGENT_BOUND);
+ expect(result.current.directoryKind).toBe('device');
+ });
+
+ it('offers no directory control for a workspace agent whose local machine is outside the task pool', () => {
+ // A member's personal desktop cannot be resolved by the task's automation or
+ // collaborators, so pinning it through a directory pick would strand the task.
+ mocks.electron = { currentDeviceId: PERSONAL_DEVICE.deviceId, isDesktop: true };
+ mocks.agentState.agentMap = { 'agent-1': { workspaceId: 'ws-1' } };
+ mocks.devices = [PERSONAL_DEVICE, WORKSPACE_DEVICE];
+ mocks.agency.agencyConfig = {
+ executionTarget: 'local',
+ heterogeneousProvider: { type: 'claude-code' },
+ };
+
+ const { result } = renderHook(() => useTaskRunTarget('agent-1'));
+
+ expect(result.current.deviceId).toBeUndefined();
+ expect(result.current.directoryKind).not.toBe('device');
+ });
+
it('ignores a task pin the run side would drop for a fixed selection policy', () => {
// `resolveExecutionPlan` clears `requestedDeviceId` when the policy is
// fixed, so showing that pin would name a machine the run never reaches β€”
diff --git a/src/features/AgentTasks/features/useTaskRunTarget.ts b/src/features/AgentTasks/features/useTaskRunTarget.ts
index f9341749fca..75d63c0fe69 100644
--- a/src/features/AgentTasks/features/useTaskRunTarget.ts
+++ b/src/features/AgentTasks/features/useTaskRunTarget.ts
@@ -15,7 +15,7 @@ import { getWorkingDirectoryPathString } from '@/helpers/workingDirectoryPath';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
-import { deviceSelectors, useDeviceStore } from '@/store/device';
+import { useElectronStore } from '@/store/electron';
export type DeviceLabelSource = Pick<DeviceListItem, 'deviceId' | 'friendlyName' | 'hostname'>;
@@ -100,6 +100,8 @@ export const useTaskRunTarget = (agentId: string, pinnedDeviceId?: string): Task
(s) => s.localAgentWorkingDirectoryMap[agentId],
);
const agentWorkspaceId = useAgentStore((s) => s.agentMap[agentId]?.workspaceId);
+ // This desktop's own device id β€” the machine a `local` target means here.
+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
// The pool a task may pin from must be the pool its runs can reach: a deviceId
// carries the identity it was enrolled under, so a workspace agent cannot run
@@ -129,14 +131,36 @@ export const useTaskRunTarget = (agentId: string, pinnedDeviceId?: string): Task
const pinApplies = !!pinnedDeviceId && canSelectExecutionTarget;
const isDeviceTarget = pinApplies;
const effectiveTarget: DeviceExecutionTarget = pinApplies ? 'device' : inheritedTarget;
+ // A workspace agent's `local` target is the member's own machine, which the
+ // task's automation and collaborators cannot resolve unless it is in the task
+ // pool (public workspace devices); offering it would pin an unreachable device.
+ const localCandidate = agencyConfig?.boundDeviceId || currentDeviceId;
+ const localDeviceId =
+ localCandidate &&
+ (!agentWorkspaceId || pool.some((device) => device.deviceId === localCandidate))
+ ? localCandidate
+ : undefined;
+
+ // A `local` target is a machine too β€” this desktop. A task run carries no
+ // `localDeviceId`, so the server routes it to the agent's bound device (the
+ // desktop syncs its own id there); fall back to this desktop's id when the
+ // binding has not been written yet. Without this the directory axis showed a
+ // dead "Follow agent" hint, although the run starts in a path on a machine.
+ // Picking a directory then pins this machine (`applyTaskDirectorySelection`),
+ // so the run is routed to where the path exists.
const deviceId = pinApplies
? pinnedDeviceId
: inheritedTarget === 'device'
? agencyConfig?.boundDeviceId
- : undefined;
-
- const rawDeviceDefaultCwd = useDeviceStore(deviceSelectors.getDeviceDefaultCwd(deviceId));
- const deviceDefaultCwd = getWorkingDirectoryPathString(rawDeviceDefaultCwd);
+ : inheritedTarget === 'local'
+ ? localDeviceId
+ : undefined;
+
+ // From the device list this hook already fetched, not the device store,
+ // which a task page may never populate.
+ const deviceDefaultCwd = getWorkingDirectoryPathString(
+ devices?.find((device) => device.deviceId === deviceId)?.defaultCwd ?? undefined,
+ );
// Only a device run has a machine whose default could apply; asking for one
// otherwise would describe a directory the cloud run never uses.
diff --git a/src/store/device/action.test.ts b/src/store/device/action.test.ts
index 3aeb122e69e..11e3f9e2687 100644
--- a/src/store/device/action.test.ts
+++ b/src/store/device/action.test.ts
@@ -1,6 +1,7 @@
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 { mutate } from '@/libs/swr';
import { deviceKeys } from '@/libs/swr/keys';
import { deviceService } from '@/services/device';
@@ -71,6 +72,21 @@ describe('DeviceAction', () => {
expect(mutate).toHaveBeenCalledWith(deviceKeys.listDevices());
});
+ // Task controls read the workspace-scoped `useDeviceList` entry, so a cwd
+ // write that only revalidated this store's key left them showing stale recents.
+ it('also revalidates the canonical device-list cache', async () => {
+ useDeviceStore.setState({ devices: [buildDevice()] });
+
+ await useDeviceStore.getState().clearDeviceDefaultCwd('dev-1');
+
+ const matcher = vi
+ .mocked(mutate)
+ .mock.calls.map(([key]) => key)
+ .find((key): key is (key: unknown) => boolean => typeof key === 'function');
+ expect(matcher?.([DEVICE_LIST_SWR_KEY, 'ws-1'])).toBe(true);
+ expect(matcher?.(deviceKeys.listDevices())).toBe(false);
+ });
+
it('does nothing when the target device does not exist', async () => {
useDeviceStore.setState({ devices: [buildDevice()] });
diff --git a/src/store/device/action.ts b/src/store/device/action.ts
index 44c2f419c6f..35fdd3120a7 100644
--- a/src/store/device/action.ts
+++ b/src/store/device/action.ts
@@ -1,6 +1,7 @@
import type { DeviceListItem, WorkingDirEntry } from '@lobechat/types';
import { type SWRResponse } from 'swr';
+import { refreshDeviceList } from '@/features/DeviceManager/const';
import { mutate, useClientDataSWR } from '@/libs/swr';
import { deviceKeys } from '@/libs/swr/keys';
import { deviceService } from '@/services/device';
@@ -11,6 +12,13 @@ import { type DeviceStore } from './store';
type Setter = StoreSetter<DeviceStore>;
+/**
+ * Revalidate both device-list caches: this store's own key and the canonical
+ * workspace-scoped `useDeviceList` entry, which task controls read.
+ */
+const revalidateDeviceLists = () =>
+ Promise.all([mutate(deviceKeys.listDevices()), refreshDeviceList()]);
+
export const deviceSlice = (set: Setter, get: () => DeviceStore, _api?: unknown) =>
new DeviceActionImpl(set, get, _api);
@@ -64,7 +72,7 @@ export class DeviceActionImpl {
});
} finally {
// Re-fetch the truth (self-corrects a failed optimistic write).
- await mutate(deviceKeys.listDevices());
+ await revalidateDeviceLists();
}
};
@@ -100,7 +108,7 @@ export class DeviceActionImpl {
);
throw error;
} finally {
- await mutate(deviceKeys.listDevices());
+ await revalidateDeviceLists();
}
};
@@ -137,7 +145,7 @@ export class DeviceActionImpl {
try {
await deviceService.updateDevice({ deviceId, workingDirs: merged });
} finally {
- await mutate(deviceKeys.listDevices());
+ await revalidateDeviceLists();
}
};
@@ -160,7 +168,7 @@ export class DeviceActionImpl {
try {
await deviceService.updateDevice({ deviceId, workingDirs: updated });
} finally {
- await mutate(deviceKeys.listDevices());
+ await revalidateDeviceLists();
}
};