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(agent): per-user device guard & workspace-keyed device list (#17210)

Rdmclin2795f441f496a
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 180cc315801..b2e3ebb2783 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -4,7 +4,6 @@ import { SiApple, SiLinux } from '@icons-pack/react-simple-icons';
import { isDesktop } from '@lobechat/const';
import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import type { DeviceExecutionTarget } from '@lobechat/types';
-import { resolveAgencyConfig } from '@lobechat/types';
import { Microsoft } from '@lobehub/icons';
import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
@@ -26,15 +25,13 @@ import { useTranslation } from 'react-i18next';
import { DOWNLOAD_URL } from '@/const/url';
import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
+import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
-import { lambdaQuery } from '@/libs/trpc/client';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
import { useElectronStore } from '@/store/electron';
-import { useUserStore } from '@/store/user';
-import { workspaceUserSettingsSelectors } from '@/store/user/selectors';
const styles = createStaticStyles(({ css }) => ({
button: css`
@@ -346,22 +343,14 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const [open, setOpen] = useState(false);
const navigate = useWorkspaceAwareNavigate();
- const sharedAgencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
const agentWorkspaceId = useAgentStore((s) => s.agentMap[agentId]?.workspaceId);
const isWorkspaceAgent = Boolean(agentWorkspaceId);
- // The current caller's per-agent override (LOBE-11689). Only ever non-empty
- // for workspace agents in practice β€” personal agents already have a single
- // owner whose choice is the shared config. Comes from the
- // `workspaceUserSettings` slice (backed by `workspace_user_settings.preference`),
- // which the picker eagerly fetches on mount so what the picker shows and
- // what dispatch will actually do always agree. Merged over the shared config
- // via `resolveAgencyConfig`.
- const { isLoading: isWorkspacePreferenceLoading } = useUserStore(
- (s) => s.useFetchWorkspaceUserPreference,
- )();
- const override = useUserStore(workspaceUserSettingsSelectors.agentDeviceOverrideById(agentId));
- const agencyConfig = resolveAgencyConfig(sharedAgencyConfig, override);
+ // Shared config merged with the caller's per-agent override (LOBE-11689) β€”
+ // the hook eagerly fetches the `workspaceUserSettings` bucket on mount so
+ // what the picker shows and what dispatch will actually do always agree.
+ const { agencyConfig, isPreferenceLoading: isWorkspacePreferenceLoading } =
+ useEffectiveAgencyConfig(agentId);
const heteroType = agencyConfig?.heterogeneousProvider?.type;
const boundDeviceId = agencyConfig?.boundDeviceId;
@@ -372,9 +361,10 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
// the option and never fall back to / honour a stale stored `'none'`.
const isHetero = !!heteroType;
- const { data: devices, isLoading } = lambdaQuery.device.listDevices.useQuery(undefined, {
- staleTime: 30_000,
- });
+ // Workspace-keyed SWR fetch β€” the raw lambdaQuery key has no workspace
+ // dimension, so the picker kept showing the previous workspace's pool after
+ // a switch (LOBE-11904).
+ const { data: devices, isLoading } = useDeviceList();
// The current machine's own gateway deviceId (desktop only), used to badge the
// matching device row with a "This device" tag and show the local-process
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
index 48856b32753..36b74e922a3 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
@@ -28,10 +28,10 @@ import {
getWorkingDirectoryName,
getWorkingDirectoryPathString,
} from '@/helpers/workingDirectoryPath';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { deviceService } from '@/services/device';
import { electronSystemService } from '@/services/electron/system';
import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import { deviceSelectors, useDeviceStore } from '@/store/device';
@@ -295,7 +295,10 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =
// One-time fold of legacy localStorage recents into device.workingDirs.
useMigrateDeviceRecents();
- const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
+ // Effective config (shared row + this member's device override, LOBE-11689)
+ // so recents / default cwd / the selected-repo label all resolve against the
+ // device THIS member's run actually targets.
+ const { agencyConfig } = useEffectiveAgencyConfig(agentId);
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
// The local machine's filesystem is browsable; a remote device's is not.
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
index fed25c6caed..b20abfd905b 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
@@ -8,9 +8,8 @@ import { memo } from 'react';
import SafeBoundary from '@/components/ErrorBoundary';
import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
import { getConfigRepoType, getWorkingDirectoryPathString } from '@/helpers/workingDirectoryPath';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
-import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import { deviceSelectors, useDeviceStore } from '@/store/device';
@@ -36,7 +35,10 @@ const getEntryEffectivePath = (entry: WorkingDirEntry) => {
* (read-only) via GitStatus's `deviceId`.
*/
const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agentId }) => {
- const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
+ // Effective config (shared row + this member's device override, LOBE-11689)
+ // so GitStatus probes the same device `useEffectiveWorkingDirectory` resolved
+ // the cwd from β€” raw shared config could point them at different machines.
+ const { agencyConfig } = useEffectiveAgencyConfig(agentId);
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
const isLocalDevice = isDesktop && !!targetDeviceId && targetDeviceId === currentDeviceId;
diff --git a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
index f37d8d99c42..ac1e7e81b59 100644
--- a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
+++ b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
@@ -5,6 +5,7 @@ import { memo } from 'react';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
@@ -36,7 +37,10 @@ const WorkspaceControls = memo<WorkspaceControlsProps>(
({ agentId, alwaysShowWorkspace = false }) => {
const runtimeMode = useAgentStore(chatConfigByIdSelectors.getRuntimeModeById(agentId));
const isHeterogeneous = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
- const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
+ // Effective config = shared row + this member's device override (LOBE-11689),
+ // so `isDeviceMode` routes the working-directory section by the device THIS
+ // member's run actually targets.
+ const { agencyConfig } = useEffectiveAgencyConfig(agentId);
const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);
const isWorkspaceAgent = useAgentStore(agentByIdSelectors.isWorkspaceAgentById(agentId));
const effectiveTarget = resolveExecutionTarget(agencyConfig, {
diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
index 48e44539875..753a0bc3e95 100644
--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
@@ -12,6 +12,7 @@ import type { PartialDeep } from 'type-fest';
import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
import { getHeteroSessionIdForWorkingDirectory } from '@/helpers/heteroSessionByWorkingDirectory';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -71,7 +72,15 @@ const toAgentWorkingDirConfig = (entry: WorkingDirEntry): WorkingDirConfig => ({
export const useCommitWorkingDirectory = (agentId: string) => {
const { t } = useTranslation(['plugin', 'chat']);
+ // The RAW shared config β€” every write below spreads it back into
+ // `agents.agencyConfig`, so it must never contain this member's per-user
+ // device override (spreading the merged config would leak the override's
+ // executionTarget/boundDeviceId into the workspace-shared row).
const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
+ // The EFFECTIVE config (override merged, LOBE-11689) β€” only for resolving
+ // which device the cwd write should target, keeping it on the same machine
+ // the picker/GitStatus/`useEffectiveWorkingDirectory` operate on.
+ const { agencyConfig: effectiveAgencyConfig } = useEffectiveAgencyConfig(agentId);
// Heterogeneous CLI agents (Claude Code, Codex, …) store sessions per-cwd, so
// their session cwd anchors to the SOURCE repo β€” a worktree switch (same repo,
// different activeWorktree) must NOT change the session cwd or reset the
@@ -91,7 +100,25 @@ export const useCommitWorkingDirectory = (agentId: string) => {
const updateDeviceCwd = useDeviceStore((s) => s.updateDeviceCwd);
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
- const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);
+ const targetDeviceId = resolveTargetDeviceId(effectiveAgencyConfig, currentDeviceId);
+
+ // A workspace agent resolving to THIS member's personal machine (a `local`
+ // override, LOBE-11689) must not persist its cwd into the workspace-shared
+ // `agents.agencyConfig.workingDirByDevice` β€” that would leak the member's
+ // personal device id and an absolute local path to every other member. Route
+ // those writes to the per-user legacy slot instead (a `local` pick only
+ // exists on desktop, where that slot works). Workspace-pool devices keep the
+ // shared per-device map: the path lives on a machine the workspace shares.
+ const isWorkspaceAgent = useAgentStore((s) => Boolean(s.agentMap[agentId]?.workspaceId));
+ // A `local` target always denotes the member's own machine β€” its
+ // `boundDeviceId` is that machine's personal gateway id even when viewed
+ // from web (`currentDeviceId` undefined there, so an id-equality check alone
+ // would miss it). The equality arm still covers a desktop default target
+ // (no stored target β†’ `resolveTargetDeviceId` falls back to this machine).
+ const isPersonalDeviceTarget =
+ isWorkspaceAgent &&
+ !!targetDeviceId &&
+ (effectiveAgencyConfig?.executionTarget === 'local' || targetDeviceId === currentDeviceId);
const writeCwd = useCallback(
async (entry?: WorkingDirEntry) => {
@@ -121,7 +148,18 @@ export const useCommitWorkingDirectory = (agentId: string) => {
workingDirectoryConfig: entry ? toAgentWorkingDirConfig(entry) : undefined,
});
} else {
- if (targetDeviceId) {
+ if (targetDeviceId && isPersonalDeviceTarget) {
+ // Per-user slot (see `isPersonalDeviceTarget`) β€” never the shared row.
+ // The legacy slot stores a plain path, so persist the SESSION cwd
+ // (source repo for hetero β€” anchoring a CLI session to a worktree
+ // path would break resume; effective path otherwise). The worktree
+ // pick itself is carried by topic metadata once a conversation
+ // starts; full-fidelity pre-topic persistence needs a per-user
+ // server-side slot (deferred).
+ await updateAgentRuntimeEnvConfigById(agentId, {
+ workingDirectory: sessionCwd || undefined,
+ });
+ } else if (targetDeviceId) {
const prev = agencyConfig?.workingDirByDevice ?? {};
// Clearing sends `undefined` rather than dropping the key: deep-merge
// (client store + server persist) can't remove a key, so the delete is
@@ -139,7 +177,8 @@ export const useCommitWorkingDirectory = (agentId: string) => {
// otherwise it keeps re-supplying a stale cwd from a lower precedence
// level and Clear looks dead. (Only clears the localStorage map; no
// network round-trip since `workingDirectory` is stripped before send.)
- if (!effectivePath && legacyAgentWorkingDirectory) {
+ // The personal-device branch above already wrote that same slot.
+ if (!isPersonalDeviceTarget && !effectivePath && legacyAgentWorkingDirectory) {
await updateAgentRuntimeEnvConfigById(agentId, { workingDirectory: undefined });
}
}
@@ -155,6 +194,7 @@ export const useCommitWorkingDirectory = (agentId: string) => {
activeTopic,
activeTopicId,
isHetero,
+ isPersonalDeviceTarget,
targetDeviceId,
legacyAgentWorkingDirectory,
updateAgentConfigById,
@@ -255,7 +295,7 @@ export const useCommitWorkingDirectory = (agentId: string) => {
async (newPath: string) => {
const path = newPath.trim();
if (!path) return;
- if (targetDeviceId) {
+ if (targetDeviceId && !isPersonalDeviceTarget) {
const prev = agencyConfig?.workingDirByDevice ?? {};
await updateAgentConfigById(agentId, {
agencyConfig: {
@@ -264,12 +304,21 @@ export const useCommitWorkingDirectory = (agentId: string) => {
},
});
} else {
- // No resolvable device (e.g. gateway id unavailable) β€” fall back to the
- // legacy per-agent slot so the action still takes effect.
+ // No resolvable device (e.g. gateway id unavailable), or a workspace
+ // agent targeting this member's own machine (`isPersonalDeviceTarget`,
+ // which must never persist into the shared row) β€” fall back to the
+ // per-user legacy slot so the action still takes effect.
await updateAgentRuntimeEnvConfigById(agentId, { workingDirectory: path });
}
},
- [agentId, agencyConfig, targetDeviceId, updateAgentConfigById, updateAgentRuntimeEnvConfigById],
+ [
+ agentId,
+ agencyConfig,
+ isPersonalDeviceTarget,
+ targetDeviceId,
+ updateAgentConfigById,
+ updateAgentRuntimeEnvConfigById,
+ ],
);
/** Clear the current selection (falls back to the next precedence level). */
diff --git a/src/features/CreatePlatformAgent/index.tsx b/src/features/CreatePlatformAgent/index.tsx
index ee9cd09004b..c51b1afd741 100644
--- a/src/features/CreatePlatformAgent/index.tsx
+++ b/src/features/CreatePlatformAgent/index.tsx
@@ -30,7 +30,7 @@ import { useNavigate } from 'react-router';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { DOWNLOAD_URL } from '@/const/url';
-import { lambdaQuery } from '@/libs/trpc/client';
+import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { deviceService } from '@/services/device';
import { useAgentStore } from '@/store/agent';
import { useHomeStore } from '@/store/home';
@@ -152,14 +152,15 @@ const CreatePlatformAgentContent = memo<CreatePlatformAgentContentProps>(
type: c.type,
}));
+ // Workspace-keyed SWR fetch (see useDeviceList) β€” the raw lambdaQuery key
+ // has no workspace dimension, so the wizard listed the previous
+ // workspace's pool after a switch (LOBE-11904).
const {
data: devices,
isLoading: loadingDevices,
- isFetching: fetchingDevices,
- refetch: refetchDevices,
- } = lambdaQuery.device.listDevices.useQuery(undefined, {
- staleTime: 0,
- });
+ isValidating: fetchingDevices,
+ mutate: refetchDevices,
+ } = useDeviceList();
const selectedPlatformDef = platformDefs.find((p) => p.type === platform)!;
diff --git a/src/features/DeviceManager/DeviceManager.tsx b/src/features/DeviceManager/DeviceManager.tsx
index 5856d1798cb..a3c824ce6a8 100644
--- a/src/features/DeviceManager/DeviceManager.tsx
+++ b/src/features/DeviceManager/DeviceManager.tsx
@@ -21,17 +21,14 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
-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, refreshDeviceList } from './const';
+import { refreshDeviceList } from './const';
import DeviceDetailPanel from './DeviceDetailPanel';
import DeviceItem from './DeviceItem';
import { useCanEditDevice } from './useCanEditDevice';
+import { useDeviceList } from './useDeviceList';
const styles = createStaticStyles(({ css }) => ({
// ─── Onboarding empty state ───
@@ -297,18 +294,9 @@ const DeviceManager = memo<DeviceManagerProps>(({ onConnect, scope, visibility }
const { t } = useTranslation('setting');
const isWorkspace = scope === 'workspace';
- // Fetch via SWR so the cache key carries the active workspace id (see
- // `DEVICE_LIST_SWR_KEY`). The raw TRPC React Query key had no workspace
- // dimension, so a fetch primed while the workspace was still resolving (empty
- // `X-Workspace-Id` header β†’ personal pool) stuck for the whole session and the
- // workspace list rendered empty until a hard refresh.
- // Devices come from an authed lambda procedure, so only query once signed in
- // (desktop always queries β€” it lists the local device's registered cwd).
- const isLogin = useUserStore(authSelectors.isLogin);
- const { data, isLoading, error, mutate, isValidating } = useClientDataSWR(
- isLogin || isDesktop ? [DEVICE_LIST_SWR_KEY] : null,
- () => deviceService.listDevices(),
- );
+ // Workspace-keyed SWR fetch β€” the shared hook every device-listing surface
+ // uses (see `useDeviceList` for why the raw TRPC React Query path is wrong).
+ const { data, isLoading, error, mutate, isValidating } = useDeviceList();
// `listDevices` is workspace-aware and returns both pools β€” keep each surface
// to its own scope (and visibility tab). Ghost rows (`visibility: null`,
// online but unregistered) belong to the shared pool: the server already
diff --git a/src/features/DeviceManager/useDeviceList.ts b/src/features/DeviceManager/useDeviceList.ts
new file mode 100644
index 00000000000..2b78f677184
--- /dev/null
+++ b/src/features/DeviceManager/useDeviceList.ts
@@ -0,0 +1,34 @@
+import { isDesktop } from '@lobechat/const';
+import type { DeviceListItem } from '@lobechat/types';
+import type { SWRResponse } from 'swr';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { deviceService } from '@/services/device';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+import { DEVICE_LIST_SWR_KEY } from './const';
+
+/**
+ * Workspace-aware device list. ALWAYS use this (not
+ * `lambdaQuery.device.listDevices.useQuery`) for any surface that lists or
+ * resolves devices: `useClientDataSWR` augments the cache key with the active
+ * workspace id, so switching workspaces re-fetches into a fresh cache entry.
+ * The raw TRPC React Query key has no workspace dimension β€” a list primed in
+ * one workspace kept serving a stale pool after switching (LOBE-11904), and a
+ * fetch primed while the workspace was still resolving stuck for the whole
+ * session (the DeviceManager fix this generalizes).
+ *
+ * Devices come from an authed lambda procedure, so only query once signed in
+ * (desktop always queries β€” it lists the local device's registered cwd).
+ *
+ * Refresh: `refreshDeviceList()` (`./const`) revalidates every workspace
+ * context's entry; the returned `mutate` revalidates just the active one.
+ */
+export const useDeviceList = (): SWRResponse<DeviceListItem[]> => {
+ const isLogin = useUserStore(authSelectors.isLogin);
+ return useClientDataSWR<DeviceListItem[]>(
+ isLogin || isDesktop ? [DEVICE_LIST_SWR_KEY] : null,
+ () => deviceService.listDevices(),
+ );
+};
diff --git a/src/hooks/useEffectiveAgencyConfig.test.ts b/src/hooks/useEffectiveAgencyConfig.test.ts
new file mode 100644
index 00000000000..f7002fcf477
--- /dev/null
+++ b/src/hooks/useEffectiveAgencyConfig.test.ts
@@ -0,0 +1,141 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useAgentStore } from '@/store/agent';
+import { useUserStore } from '@/store/user';
+
+import { useEffectiveAgencyConfig } from './useEffectiveAgencyConfig';
+
+vi.mock('@/store/agent', () => ({ useAgentStore: vi.fn() }));
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById:
+ (id: string) => (s: { agentMap: Record<string, { agencyConfig?: unknown }> }) =>
+ s.agentMap[id]?.agencyConfig,
+ isWorkspaceAgentById:
+ (id: string) => (s: { agentMap: Record<string, { workspaceId?: string }> }) =>
+ Boolean(s.agentMap[id]?.workspaceId),
+ },
+}));
+vi.mock('@/store/user', () => ({ useUserStore: vi.fn() }));
+vi.mock('@/store/user/selectors', () => ({
+ workspaceUserSettingsSelectors: {
+ agentDeviceOverrideById:
+ (id: string) =>
+ (s: { workspaceUserPreference: { agentDeviceOverrides?: Record<string, unknown> } }) =>
+ s.workspaceUserPreference.agentDeviceOverrides?.[id],
+ },
+}));
+
+const mockedUseAgentStore = vi.mocked(useAgentStore);
+const mockedUseUserStore = vi.mocked(useUserStore);
+
+const sharedConfig = { boundDeviceId: 'creator-device', executionTarget: 'device' as const };
+
+const setupStores = ({
+ agencyConfig = sharedConfig as unknown,
+ fetchedPreference,
+ isLoading = false,
+ override,
+ workspaceId,
+}: {
+ agencyConfig?: unknown;
+ /** SWR response data β€” `undefined` = not yet resolved, `null` = no server row. */
+ fetchedPreference?: unknown;
+ isLoading?: boolean;
+ override?: unknown;
+ workspaceId?: string;
+} = {}) => {
+ const agentState = { agentMap: { 'agent-1': { agencyConfig, workspaceId } } };
+ const userState = {
+ useFetchWorkspaceUserPreference: () => ({ data: fetchedPreference, isLoading }),
+ workspaceUserPreference: { agentDeviceOverrides: override ? { 'agent-1': override } : {} },
+ };
+ mockedUseAgentStore.mockImplementation((selector: any) => selector(agentState));
+ mockedUseUserStore.mockImplementation((selector: any) => selector(userState));
+};
+
+describe('useEffectiveAgencyConfig', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns the shared config as-is for personal agents, ignoring any override', () => {
+ setupStores({ override: { boundDeviceId: 'my-device', executionTarget: 'device' } });
+
+ const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));
+
+ expect(result.current.agencyConfig).toEqual(sharedConfig);
+ });
+
+ it('merges the caller override over the shared config for workspace agents', () => {
+ setupStores({
+ override: { boundDeviceId: 'my-device', executionTarget: 'local' },
+ workspaceId: 'ws-1',
+ });
+
+ const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));
+
+ expect(result.current.agencyConfig).toEqual({
+ boundDeviceId: 'my-device',
+ executionTarget: 'local',
+ });
+ });
+
+ it('falls back to the shared config when a workspace agent has no override', () => {
+ setupStores({ workspaceId: 'ws-1' });
+
+ const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));
+
+ expect(result.current.agencyConfig).toEqual(sharedConfig);
+ });
+
+ it('reports preference loading only for workspace agents', () => {
+ setupStores({ isLoading: true, workspaceId: 'ws-1' });
+ const workspaceResult = renderHook(() => useEffectiveAgencyConfig('agent-1'));
+ expect(workspaceResult.result.current.isPreferenceLoading).toBe(true);
+
+ setupStores({ isLoading: true });
+ const personalResult = renderHook(() => useEffectiveAgencyConfig('agent-1'));
+ expect(personalResult.result.current.isPreferenceLoading).toBe(false);
+ });
+
+ it('prefers the SWR preference over the (possibly stale) store bucket', () => {
+ // Switch-back window: SWR serves the cached CURRENT workspace preference
+ // while the un-keyed store bucket still holds the previous workspace's.
+ setupStores({
+ fetchedPreference: {
+ agentDeviceOverrides: {
+ 'agent-1': { boundDeviceId: 'my-device', executionTarget: 'device' },
+ },
+ },
+ override: { boundDeviceId: 'stale-other-ws-device', executionTarget: 'device' },
+ workspaceId: 'ws-1',
+ });
+
+ const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));
+
+ expect(result.current.agencyConfig?.boundDeviceId).toBe('my-device');
+ });
+
+ it('treats a null SWR response (no server row) as no override', () => {
+ setupStores({
+ fetchedPreference: null,
+ override: { boundDeviceId: 'stale-other-ws-device', executionTarget: 'device' },
+ workspaceId: 'ws-1',
+ });
+
+ const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));
+
+ expect(result.current.agencyConfig).toEqual(sharedConfig);
+ });
+
+ it('returns undefined config when agentId is missing', () => {
+ setupStores({ override: { boundDeviceId: 'my-device' }, workspaceId: 'ws-1' });
+
+ const { result } = renderHook(() => useEffectiveAgencyConfig(undefined));
+
+ expect(result.current.agencyConfig).toBeUndefined();
+ expect(result.current.isPreferenceLoading).toBe(false);
+ });
+});
diff --git a/src/hooks/useEffectiveAgencyConfig.ts b/src/hooks/useEffectiveAgencyConfig.ts
new file mode 100644
index 00000000000..444bb13eb6a
--- /dev/null
+++ b/src/hooks/useEffectiveAgencyConfig.ts
@@ -0,0 +1,64 @@
+import type { LobeAgentAgencyConfig } from '@lobechat/types';
+import { resolveAgencyConfig } from '@lobechat/types';
+
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useUserStore } from '@/store/user';
+
+export interface UseEffectiveAgencyConfigResult {
+ /** Shared `agents.agencyConfig` merged with the caller's per-agent override. */
+ agencyConfig: LobeAgentAgencyConfig | undefined;
+ /**
+ * The workspace preference fetch is still in flight. Until it settles, a
+ * workspace agent's `agencyConfig` may reflect only the shared row β€” callers
+ * that act on `boundDeviceId` / `executionTarget` (device guards, defaults)
+ * should wait instead of acting on a value that may flip.
+ */
+ isPreferenceLoading: boolean;
+}
+
+/**
+ * The agent's EFFECTIVE `agencyConfig` for the current caller.
+ *
+ * The workspace-shared `agents.agencyConfig` is one row per agent, but each
+ * member picks their own execution device (LOBE-11689) β€” that pick lives in
+ * `workspace_user_settings.preference.agentDeviceOverrides[agentId]` and must
+ * be merged over the shared row via `resolveAgencyConfig` at read time.
+ * Reading the shared row alone shows whichever device landed there (usually
+ * the creator's machine) instead of this member's choice.
+ *
+ * Personal agents have a single owner whose choice IS the shared config, so
+ * the override is only applied for workspace agents β€” mirroring the write
+ * side (`useSelectExecutionTarget`).
+ *
+ * Self-populates the workspace preference cache (SWR dedupes across callers;
+ * personal mode short-circuits without a network call).
+ */
+export const useEffectiveAgencyConfig = (agentId?: string): UseEffectiveAgencyConfigResult => {
+ const sharedAgencyConfig = useAgentStore((s) =>
+ agentId ? agentByIdSelectors.getAgencyConfigById(agentId)(s) : undefined,
+ );
+ const isWorkspaceAgent = useAgentStore((s) =>
+ agentId ? agentByIdSelectors.isWorkspaceAgentById(agentId)(s) : false,
+ );
+
+ // Prefer the SWR response over the store bucket: the SWR cache is keyed by
+ // the ACTIVE workspace, while the zustand bucket is a single un-keyed slot β€”
+ // when switching back to a workspace whose preference is already cached,
+ // `isLoading` is false immediately but the bucket still holds the previous
+ // workspace's data until revalidation lands. Optimistic writes stay visible
+ // because `updateWorkspaceUserPreference` mutates the SWR cache too. The
+ // bucket remains the fallback for the pre-first-response window; a `null`
+ // response (no server row yet) means "no override", not "use the bucket".
+ const { data: fetchedPreference, isLoading } = useUserStore(
+ (s) => s.useFetchWorkspaceUserPreference,
+ )();
+ const storePreference = useUserStore((s) => s.workspaceUserPreference);
+ const preference = fetchedPreference === undefined ? storePreference : (fetchedPreference ?? {});
+ const override = agentId ? preference.agentDeviceOverrides?.[agentId] : undefined;
+
+ return {
+ agencyConfig: resolveAgencyConfig(sharedAgencyConfig, isWorkspaceAgent ? override : undefined),
+ isPreferenceLoading: isWorkspaceAgent && isLoading,
+ };
+};
diff --git a/src/hooks/useEffectiveWorkingDirectory.ts b/src/hooks/useEffectiveWorkingDirectory.ts
index 5f5127cb8b4..f3a63147217 100644
--- a/src/hooks/useEffectiveWorkingDirectory.ts
+++ b/src/hooks/useEffectiveWorkingDirectory.ts
@@ -5,8 +5,8 @@ import {
resolveTargetDeviceId,
} from '@/helpers/agentWorkingDirectory';
import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import { deviceSelectors, useDeviceStore } from '@/store/device';
@@ -32,9 +32,10 @@ export const useEffectiveWorkingDirectory = (agentId?: string): string | undefin
const isLogin = useUserStore(authSelectors.isLogin);
useDeviceStore((s) => s.useFetchDevices)(isLogin || isDesktop);
- const agencyConfig = useAgentStore((s) =>
- agentId ? agentByIdSelectors.getAgencyConfigById(agentId)(s) : undefined,
- );
+ // Effective config = shared row + this member's device override (LOBE-11689),
+ // so `resolveTargetDeviceId` targets the device THIS member's run goes to β€”
+ // not whichever machine landed on the workspace-shared row.
+ const { agencyConfig } = useEffectiveAgencyConfig(agentId);
const legacyAgentWorkingDirectory = useAgentStore((s) =>
agentId ? s.localAgentWorkingDirectoryMap[agentId] : undefined,
);
diff --git a/src/hooks/useRemoteAgentDeviceGuard.test.ts b/src/hooks/useRemoteAgentDeviceGuard.test.ts
new file mode 100644
index 00000000000..4dcdb91c068
--- /dev/null
+++ b/src/hooks/useRemoteAgentDeviceGuard.test.ts
@@ -0,0 +1,86 @@
+import { renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
+import { deviceService } from '@/services/device';
+
+import { useRemoteAgentDeviceGuard } from './useRemoteAgentDeviceGuard';
+
+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({ useEffectiveAgencyConfig: vi.fn() }));
+vi.mock('@/services/device', () => ({
+ deviceService: { checkCapability: vi.fn(), listDevices: vi.fn() },
+}));
+
+const mockedUseEffectiveAgencyConfig = vi.mocked(useEffectiveAgencyConfig);
+const mockedListDevices = vi.mocked(deviceService.listDevices);
+
+describe('useRemoteAgentDeviceGuard', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('checks the EFFECTIVE bound device (with the caller override merged)', async () => {
+ // The workspace-shared row points at the creator's (offline) machine; the
+ // caller's override picks their own online device β€” the guard must probe
+ // the override device, not the shared one (LOBE-11904).
+ mockedUseEffectiveAgencyConfig.mockReturnValue({
+ agencyConfig: {
+ boundDeviceId: 'my-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'codex' },
+ },
+ isPreferenceLoading: false,
+ });
+ mockedListDevices.mockResolvedValue([
+ { deviceId: 'creator-device', online: false },
+ { deviceId: 'my-device', online: true },
+ ] as never);
+
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+
+ await waitFor(() => expect(result.current.status).toBe('ok'));
+ });
+
+ it('reports device-offline when the effective bound device has no live channel', async () => {
+ mockedUseEffectiveAgencyConfig.mockReturnValue({
+ agencyConfig: {
+ boundDeviceId: 'my-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'claude-code' },
+ },
+ isPreferenceLoading: false,
+ });
+ mockedListDevices.mockResolvedValue([{ deviceId: 'my-device', online: false }] as never);
+
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+
+ await waitFor(() => expect(result.current.status).toBe('device-offline'));
+ });
+
+ it('stays in checking (and does not probe) while the workspace preference loads', async () => {
+ mockedUseEffectiveAgencyConfig.mockReturnValue({
+ agencyConfig: {
+ boundDeviceId: 'creator-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'codex' },
+ },
+ isPreferenceLoading: true,
+ });
+
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+
+ await waitFor(() => expect(result.current.status).toBe('checking'));
+ expect(mockedListDevices).not.toHaveBeenCalled();
+ });
+
+ it('reports no-device when nothing is bound', async () => {
+ mockedUseEffectiveAgencyConfig.mockReturnValue({
+ agencyConfig: { heterogeneousProvider: { type: 'codex' } },
+ isPreferenceLoading: false,
+ });
+
+ const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));
+
+ await waitFor(() => expect(result.current.status).toBe('no-device'));
+ });
+});
diff --git a/src/hooks/useRemoteAgentDeviceGuard.ts b/src/hooks/useRemoteAgentDeviceGuard.ts
index dfb92f11371..e07d9189415 100644
--- a/src/hooks/useRemoteAgentDeviceGuard.ts
+++ b/src/hooks/useRemoteAgentDeviceGuard.ts
@@ -1,15 +1,11 @@
import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import { useCallback, useEffect, useState } from 'react';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { deviceService } from '@/services/device';
-import { useAgentStore } from '@/store/agent';
export type RemoteAgentDeviceStatus =
- | 'checking'
- | 'device-offline'
- | 'no-device'
- | 'ok'
- | 'platform-unavailable';
+ 'checking' | 'device-offline' | 'no-device' | 'ok' | 'platform-unavailable';
interface UseRemoteAgentDeviceGuardOptions {
/** The conversation's agent β€” validate this agent's bound device, not the global active one. */
@@ -31,9 +27,11 @@ export const useRemoteAgentDeviceGuard = ({
agentId,
enabled = true,
}: UseRemoteAgentDeviceGuardOptions): UseRemoteAgentDeviceGuardResult => {
- const agencyConfig = useAgentStore((s) =>
- agentId ? s.agentMap[agentId]?.agencyConfig : undefined,
- );
+ // Effective config = shared row + this member's per-agent device override
+ // (LOBE-11689). Checking the raw shared `boundDeviceId` would probe whichever
+ // machine landed on the shared row (usually the creator's, often offline)
+ // instead of the device THIS member picked β€” a false "device offline".
+ const { agencyConfig, isPreferenceLoading } = useEffectiveAgencyConfig(agentId);
const boundDeviceId = agencyConfig?.boundDeviceId;
const providerType = agencyConfig?.heterogeneousProvider?.type;
@@ -43,6 +41,15 @@ export const useRemoteAgentDeviceGuard = ({
const check = useCallback(async () => {
if (!enabled) return;
+ // The override hasn't loaded yet β€” `boundDeviceId` may still be the shared
+ // row's device. Stay in `checking` (non-blocking) rather than flash an
+ // offline banner for a device this member never picked; the load flips
+ // `isPreferenceLoading` and re-runs the check.
+ if (isPreferenceLoading) {
+ setStatus('checking');
+ return;
+ }
+
if (!boundDeviceId) {
setStatus('no-device');
return;
@@ -72,7 +79,7 @@ export const useRemoteAgentDeviceGuard = ({
// On error, allow sending β€” don't block user on network issues
setStatus('ok');
}
- }, [enabled, boundDeviceId, providerType]);
+ }, [enabled, isPreferenceLoading, boundDeviceId, providerType]);
useEffect(() => {
void check();
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
index 81a768e1de9..f271335371d 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next';
import WorkspaceControls from '@/features/ChatInput/ControlBar/WorkspaceControls';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -128,7 +129,9 @@ const HeteroControlBar = memo(() => {
// All hooks must be called unconditionally (Rules of Hooks)
const isLoading = useAgentStore(agentByIdSelectors.isAgentConfigLoadingById(agentId));
- const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
+ // Effective config = shared row + this member's device override (LOBE-11689),
+ // so the quota badges gate on where THIS member's run actually executes.
+ const { agencyConfig } = useEffectiveAgencyConfig(agentId);
const isWorkspaceAgent = useAgentStore(agentByIdSelectors.isWorkspaceAgentById(agentId));
// On web there's no full-access badge / skeleton β€” just the workspace controls
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
index 47d64940016..ee0e1ea015d 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
@@ -20,9 +20,10 @@ import { ChatInput } from '@/features/Conversation';
import { contextSelectors, useConversationStore } from '@/features/Conversation/store';
import WideScreenContainer from '@/features/WideScreenContainer';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useRemoteAgentDeviceGuard } from '@/hooks/useRemoteAgentDeviceGuard';
import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
+import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import HeteroControlBar from './HeteroControlBar';
@@ -89,9 +90,14 @@ const HeterogeneousChatInput = memo(() => {
const params = useParams<{ aid: string }>();
const navigate = useNavigate();
- const agencyConfig = useAgentStore(
- (s) => agentSelectors.getAgentConfigById(agentId)(s)?.agencyConfig,
- );
+ // Effective config = shared row + this member's per-agent device override
+ // (LOBE-11689) β€” the raw shared `agencyConfig` may carry another member's
+ // device pick, which would drive the guard/model-selector gates off the
+ // wrong machine.
+ // While the preference is loading, the merged config may still reflect only
+ // the shared row β€” hold the input closed (below) instead of gating device
+ // runs off a value that can flip once the override arrives.
+ const { agencyConfig, isPreferenceLoading } = useEffectiveAgencyConfig(agentId);
const providerType = agencyConfig?.heterogeneousProvider?.type;
const isWorkspaceAgent = useAgentStore(agentByIdSelectors.isWorkspaceAgentById(agentId));
const executionTarget = resolveExecutionTarget(agencyConfig, {
@@ -189,7 +195,9 @@ const HeterogeneousChatInput = memo(() => {
};
const renderCloudConfigGuard = () => {
- if (isDeviceExecution || isConfigured) return null;
+ // Until the override loads, `isDeviceExecution` may be a false negative β€”
+ // don't flash the cloud-config prompt for what turns out to be a device run.
+ if (isPreferenceLoading || isDeviceExecution || isConfigured) return null;
return (
<GuardBanner
@@ -205,8 +213,11 @@ const HeterogeneousChatInput = memo(() => {
};
// Device execution doesn't use the cloud sandbox, so it doesn't need cloud
- // credentials β€” only the sandbox path gates on `isConfigured`.
- const inputDisabled = (!isConfigured && !isDeviceExecution) || deviceBlocked;
+ // credentials β€” only the sandbox path gates on `isConfigured`. While the
+ // workspace preference loads, keep send disabled: the effective target isn't
+ // known yet, so neither guard can vouch for the run.
+ const inputDisabled =
+ isPreferenceLoading || (!isConfigured && !isDeviceExecution) || deviceBlocked;
const hasGuard = deviceBlocked || (!isConfigured && !isDeviceExecution);
return (
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
index 2f89bd27d69..7686b51495e 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/RemoteAgentConfigCard.tsx
@@ -20,7 +20,7 @@ import { BotIcon, CheckCircle2, MonitorSmartphone, RefreshCw, XCircle } from 'lu
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { lambdaQuery } from '@/libs/trpc/client';
+import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { deviceService } from '@/services/device';
import { useAgentStore } from '@/store/agent';
@@ -109,10 +109,10 @@ const ChangeDeviceContent = memo<ChangeDeviceContentProps>(
setCanDismissByClickOutside(!saving);
}, [saving, setCanDismissByClickOutside]);
- const { data: devices, isLoading: loadingDevices } = lambdaQuery.device.listDevices.useQuery(
- undefined,
- { staleTime: 30_000 },
- );
+ // Workspace-keyed SWR fetch (see useDeviceList) β€” the raw lambdaQuery key
+ // has no workspace dimension, so the list went stale across workspace
+ // switches (LOBE-11904).
+ const { data: devices, isLoading: loadingDevices } = useDeviceList();
const onlineDevices = (devices ?? []).filter(
(d) => d.online && (!isWorkspaceAgent || d.scope === 'workspace'),
@@ -274,9 +274,8 @@ const RemoteAgentConfigCard = memo<RemoteAgentConfigCardProps>(
const platformName = HETEROGENEOUS_TYPE_LABELS[provider.type] ?? provider.type;
- const { data: devices } = lambdaQuery.device.listDevices.useQuery(undefined, {
- staleTime: 30_000,
- });
+ // Workspace-keyed SWR fetch β€” see the comment on the sibling call above.
+ const { data: devices } = useDeviceList();
const boundDevice = devices?.find((d) => d.deviceId === boundDeviceId);
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index a1583304946..af3abbb1ca7 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -7,6 +7,7 @@ import {
} from '@lobechat/builtin-tool-agent-management';
import { isDesktop, LOADING_FLAT } from '@lobechat/const';
import { formatSelectedSkillsContext, formatSelectedToolsContext } from '@lobechat/context-engine';
+import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';
import { chainCompressContext } from '@lobechat/prompts';
import type {
ChatImageItem,
@@ -20,13 +21,22 @@ import type {
SendMessageServerResponse,
UIChatMessage,
} from '@lobechat/types';
-import { getWorkingDirEffectivePath, getWorkingDirSourcePath } from '@lobechat/types';
+import {
+ getWorkingDirEffectivePath,
+ getWorkingDirSourcePath,
+ resolveAgencyConfig,
+} from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
import { TRPCClientError } from '@trpc/client';
import { t } from 'i18next';
import { message as antdMessage } from '@/components/AntdStaticMethods';
-import { resolveAgentWorkingDirectoryConfig } from '@/helpers/agentWorkingDirectory';
+import {
+ resolveAgentWorkingDirectory,
+ resolveAgentWorkingDirectoryConfig,
+} from '@/helpers/agentWorkingDirectory';
+import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';
import { agentService } from '@/services/agent';
import { aiChatService } from '@/services/aiChat';
import { chatService } from '@/services/chat';
@@ -72,6 +82,7 @@ import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
import { type StoreSetter } from '@/store/types';
+import { getUserStoreState } from '@/store/user';
import { useUserMemoryStore } from '@/store/userMemory';
import { markdownToTxt } from '@/utils/markdownToTxt';
@@ -578,28 +589,68 @@ export class ConversationLifecycleActionImpl {
: undefined;
const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
const agentState = getAgentStoreState();
- const agentWorkingDirectory =
- runtimeType === 'hetero' && heterogeneousProvider
- ? agentByIdSelectors.getAgentWorkingDirectoryById(agentId, currentDeviceId)(agentState)
- : undefined;
- const agencyConfig = agentByIdSelectors.getAgencyConfigById(agentId)(agentState);
- const agentWorkingDirectoryConfig =
- runtimeType === 'hetero' && heterogeneousProvider
- ? resolveAgentWorkingDirectoryConfig({
- agencyConfig,
- currentDeviceId,
- fallback: agentWorkingDirectory,
- legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],
- })
- : undefined;
+ // Merge the caller's per-user device override (LOBE-11689) so the cwd is
+ // read for the device THIS member's run targets, not the shared row's.
+ const isWorkspaceAgentForCwd = agentByIdSelectors.isWorkspaceAgentById(agentId)(agentState);
+ const agencyConfig = resolveAgencyConfig(
+ agentByIdSelectors.getAgencyConfigById(agentId)(agentState),
+ isWorkspaceAgentForCwd
+ ? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]
+ : undefined,
+ );
+ // Resolve the cwd for every hetero-provider run that lands on a MACHINE
+ // (in-process `hetero` runtime, or a gateway dispatch whose effective
+ // target routes to a device) β€” the server can only honour a cwd the client
+ // resolved (per-user legacy slot included) if it rides along as the new
+ // topic's initial metadata. Sandbox/none targets must NOT resolve one: the
+ // desktop/home fallback is a local machine path that doesn't exist in an
+ // ephemeral cloud sandbox and would pollute the topic's metadata.
+ const heteroEffectiveTarget = heterogeneousProvider
+ ? resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: isDesktop,
+ isHetero: true,
+ workspaceScoped: isWorkspaceAgentForCwd,
+ })
+ : undefined;
+ const resolvesHeteroCwd =
+ !!heterogeneousProvider &&
+ (heteroEffectiveTarget === 'local' ||
+ heteroEffectiveTarget === 'device' ||
+ heteroEffectiveTarget === 'auto');
+ // Same precedence as `getAgentWorkingDirectoryById`, but over the MERGED
+ // config β€” the selector reads the raw shared row internally, which could
+ // fall back to a cwd registered for another member's device. Desktop/home
+ // is the only neutral last resort.
+ const heteroCwdContext =
+ resolvesHeteroCwd && isDesktop ? globalAgentContextManager.getContext() : undefined;
+ const heteroCwdParams = resolvesHeteroCwd
+ ? {
+ agencyConfig,
+ currentDeviceId,
+ fallback: heteroCwdContext?.desktopPath ?? heteroCwdContext?.homePath,
+ legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],
+ }
+ : undefined;
+ const agentWorkingDirectory = heteroCwdParams
+ ? resolveAgentWorkingDirectory(heteroCwdParams)
+ : undefined;
+ const agentWorkingDirectoryConfig = heteroCwdParams
+ ? resolveAgentWorkingDirectoryConfig(heteroCwdParams)
+ : undefined;
// Heterogeneous CLI agents (Claude Code, Codex, …) store sessions per-cwd
// (`~/.claude/projects/<encoded-cwd>/`). Anchor their session cwd to the
// SOURCE repo, NOT the selected worktree, so switching worktree keeps cwd +
// sessionId consistent and never drops the conversation context. The active
// worktree lives only in `workingDirectoryConfig.git.activeWorktree` as a
- // record. Non-hetero runtimes keep the effective (worktree) path.
- const resolveWorkingDirPath =
- runtimeType === 'hetero' ? getWorkingDirSourcePath : getWorkingDirEffectivePath;
+ // record. The per-cwd session store is a LOCAL CLI trait β€” remote platform
+ // agents (openclaw / hermes) run through the gateway with no such
+ // constraint, so they (like non-hetero runtimes) keep the effective
+ // (worktree) path.
+ const isLocalCliHetero =
+ !!heterogeneousProvider && !isRemoteHeterogeneousType(heterogeneousProvider.type);
+ const resolveWorkingDirPath = isLocalCliHetero
+ ? getWorkingDirSourcePath
+ : getWorkingDirEffectivePath;
const workingDirectory =
resolveWorkingDirPath(existingTopic?.metadata?.workingDirectoryConfig) ??
existingTopic?.metadata?.workingDirectory ??
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index ee5887742d4..11648d8f807 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -456,6 +456,12 @@ export class GatewayActionImpl {
// it up. We clear only after the server confirms the topic was created.
const pendingRepos =
isCreateNewTopic && context.agentId ? getPendingTopicRepos(context.agentId) : [];
+ // Pending repo selection wins; otherwise carry the caller-resolved topic
+ // metadata (e.g. the hetero cwd `conversationLifecycle` resolved from the
+ // effective device + per-user legacy slot) so the SERVER topic is born with
+ // it β€” the server can't read client-local state, and without this a
+ // workspace hetero run's first send would fall back to the device default
+ // cwd instead of the member's pick.
const initialTopicMetadata =
pendingRepos.length > 0
? {
@@ -463,7 +469,13 @@ export class GatewayActionImpl {
workingDirectory: pendingRepos[0],
workingDirectoryConfig: { path: pendingRepos[0], repoType: 'github' as const },
}
- : undefined;
+ : isCreateNewTopic && optimisticTopic?.metadata?.workingDirectory
+ ? {
+ repos: optimisticTopic.metadata.repos,
+ workingDirectory: optimisticTopic.metadata.workingDirectory,
+ workingDirectoryConfig: optimisticTopic.metadata.workingDirectoryConfig,
+ }
+ : undefined;
// Honour user-initiated cancel during phase-1 init: while we await the
// execAgentTask round-trip the caller's loading state (e.g. `sendMessage`)
diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.ts
index dcedeccb196..3cab8d18595 100644
--- a/src/store/user/slices/workspaceUserSettings/action.ts
+++ b/src/store/user/slices/workspaceUserSettings/action.ts
@@ -1,7 +1,11 @@
import type { WorkspaceUserPreference } from '@lobechat/types';
+import { useEffect } from 'react';
-import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
-import { useClientDataSWR } from '@/libs/swr';
+import {
+ getActiveWorkspaceId,
+ useActiveWorkspaceId,
+} from '@/business/client/hooks/useActiveWorkspaceId';
+import { mutate, useClientDataSWR } from '@/libs/swr';
import { workspaceUserSettingsService } from '@/services/workspaceUserSettings';
import { type StoreSetter } from '@/store/types';
import { type UserStore } from '@/store/user';
@@ -41,20 +45,29 @@ export class WorkspaceUserSettingsActionImpl {
useFetchWorkspaceUserPreference = () => {
const workspaceId = useActiveWorkspaceId();
- return useClientDataSWR<WorkspaceUserPreference | null>(
+ const swr = useClientDataSWR<WorkspaceUserPreference | null>(
workspaceId ? [WORKSPACE_USER_SETTINGS_SWR_KEY, workspaceId] : null,
async () => workspaceUserSettingsService.getPreference(),
- {
- onSuccess: (data) => {
- if (!data) return;
- this.#set(
- { workspaceUserPreference: data },
- false,
- n('useFetchWorkspaceUserPreference/onSuccess'),
- );
- },
- },
);
+
+ // Sync EVERY data change into the (un-keyed) store bucket β€” not just
+ // fetch successes. On a workspace switch-back the SWR cache serves the
+ // new workspace's preference synchronously, and an `onSuccess`-only sync
+ // would leave the bucket holding the previous workspace's data until
+ // revalidation lands; imperative readers (send-time cwd resolution) read
+ // the bucket, so it must be corrected on the first render. A `null`
+ // response (no server row) clears the bucket for the same reason.
+ const data = swr.data;
+ useEffect(() => {
+ if (data === undefined) return;
+ this.#set(
+ { workspaceUserPreference: data ?? {} },
+ false,
+ n('useFetchWorkspaceUserPreference/sync'),
+ );
+ }, [data]);
+
+ return swr;
};
updateWorkspaceUserPreference = async (
@@ -62,13 +75,19 @@ export class WorkspaceUserSettingsActionImpl {
): Promise<void> => {
// Optimistic merge β€” the picker's own re-render should see the new
// choice on the very next frame, not wait for the mutation round-trip.
+ // Mirror the write into the SWR cache too: readers that prefer the
+ // workspace-keyed SWR data over this un-keyed bucket (see
+ // `useEffectiveAgencyConfig`) must observe the optimistic value as well.
const previous = this.#get().workspaceUserPreference;
const optimistic: WorkspaceUserPreference = { ...previous, ...patch };
+ const workspaceId = getActiveWorkspaceId();
+ const swrKey = workspaceId ? [WORKSPACE_USER_SETTINGS_SWR_KEY, workspaceId] : null;
this.#set(
{ workspaceUserPreference: optimistic },
false,
n('updateWorkspaceUserPreference/optimistic'),
);
+ if (swrKey) void mutate(swrKey, optimistic, { revalidate: false });
try {
await workspaceUserSettingsService.updatePreference(patch);
@@ -80,6 +99,7 @@ export class WorkspaceUserSettingsActionImpl {
false,
n('updateWorkspaceUserPreference/rollback'),
);
+ if (swrKey) void mutate(swrKey, previous, { revalidate: false });
throw error;
}
};