π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(workspace): honor local heterogeneous device overrides (#17317)
AmAzing-fe26f68d68f7
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex e5618bc0048..dae5df39438 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -349,8 +349,11 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {// 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 {+ agencyConfig,+ isPreferenceLoading: isWorkspacePreferenceLoading,+ workspaceScoped,+ } = useEffectiveAgencyConfig(agentId);const heteroType = agencyConfig?.heterogeneousProvider?.type;const boundDeviceId = agencyConfig?.boundDeviceId;@@ -374,19 +377,15 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {const gatewayDeviceInfo = useElectronStore((s) => s.gatewayDeviceInfo);const currentDeviceId = isDesktop ? gatewayDeviceInfo?.deviceId : undefined;- // Effective target: `resolveExecutionTarget` runs over the *merged*- // `agencyConfig` (shared + this user's LOBE-11689 override), so what the- // chip shows and what the server dispatches always agree.- //- // `workspaceScoped: false`: with per-user overrides, workspace agents can- // resolve `local` again β the pre-11689 coercion was only there because- // sharing the choice across members made a personal-scope `local` pick- // dangerous.+ // A member's explicit target override may resolve `local`; without one the+ // raw shared fallback stays workspace-scoped so a legacy `local` value keeps+ // routing to its bound workspace device rather than this member's desktop.const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);const executionTarget = resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: isDesktop,deviceRoutingAvailable,isHetero,+ workspaceScoped,});// Amp cannot fall back to the cloud sandbox. When a web/legacy config has nodiff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsxindex 36b74e922a3..f73955ac9b8 100644--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx@@ -298,9 +298,11 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ 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 { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);- const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);+ const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {+ workspaceScoped,+ });// The local machine's filesystem is browsable; a remote device's is not.const isLocalDevice = isDesktop && !!targetDeviceId && targetDeviceId === currentDeviceId;@@ -330,6 +332,7 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =legacyAgentWorkingDirectory,topicWorkingDirectory,topicWorkingDirectoryConfig,+ workspaceScoped,});const selectedDir = getWorkingDirectoryPathString(resolvedSelectedDir);diff --git a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsxindex b20abfd905b..19ab3b006af 100644--- a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx+++ b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx@@ -38,9 +38,11 @@ const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agent// 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 { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);- const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);+ const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {+ workspaceScoped,+ });const isLocalDevice = isDesktop && !!targetDeviceId && targetDeviceId === currentDeviceId;const rawEffectiveWorkingDirectory = useEffectiveWorkingDirectory(agentId);diff --git a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx b/src/features/ChatInput/ControlBar/WorkspaceControls.tsxindex ac1e7e81b59..0fa5debaa0e 100644--- a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx+++ b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx@@ -40,14 +40,13 @@ const WorkspaceControls = memo<WorkspaceControlsProps>(// 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 { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);- const isWorkspaceAgent = useAgentStore(agentByIdSelectors.isWorkspaceAgentById(agentId));const effectiveTarget = resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: isDesktop,deviceRoutingAvailable,isHetero: isHeterogeneous,- workspaceScoped: isWorkspaceAgent,+ workspaceScoped,});const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.tsindex 753a0bc3e95..00ee919564d 100644--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts@@ -80,7 +80,8 @@ export const useCommitWorkingDirectory = (agentId: string) => {// 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);+ const { agencyConfig: effectiveAgencyConfig, workspaceScoped } =+ 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@@ -100,7 +101,9 @@ export const useCommitWorkingDirectory = (agentId: string) => {const updateDeviceCwd = useDeviceStore((s) => s.updateDeviceCwd);const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);- const targetDeviceId = resolveTargetDeviceId(effectiveAgencyConfig, currentDeviceId);+ const targetDeviceId = resolveTargetDeviceId(effectiveAgencyConfig, currentDeviceId, {+ workspaceScoped,+ });// A workspace agent resolving to THIS member's personal machine (a `local`// override, LOBE-11689) must not persist its cwd into the workspace-shared@@ -117,6 +120,7 @@ export const useCommitWorkingDirectory = (agentId: string) => {// (no stored target β `resolveTargetDeviceId` falls back to this machine).const isPersonalDeviceTarget =isWorkspaceAgent &&+ !workspaceScoped &&!!targetDeviceId &&(effectiveAgencyConfig?.executionTarget === 'local' || targetDeviceId === currentDeviceId);diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex 3e9fe28a841..73b2dd46833 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -5,6 +5,7 @@ import type {ConversationContext,HeterogeneousProviderConfig,} from '@lobechat/types';+import { resolveAgencyConfig } from '@lobechat/types';import { t } from 'i18next';import { type StateCreator } from 'zustand';@@ -12,6 +13,9 @@ import { message as antdMessage } from '@/components/AntdStaticMethods';import { MESSAGE_CANCEL_FLAT } from '@/const/index';import { saveDraft } from '@/features/ChatInput/draftStorage';import { isHeterogeneousAgentStatusGuideError } from '@/features/Conversation/Error/heterogeneous';+import { resolveAgentWorkingDirectory } from '@/helpers/agentWorkingDirectory';+import { resolveWorkspaceScoped } from '@/helpers/executionTarget';+import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';import { messageService } from '@/services/message';import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';@@ -32,6 +36,7 @@ import {} from '@/store/chat/utils/activeTopicDocumentContext';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { getElectronStoreState } from '@/store/electron';+import { getUserStoreState } from '@/store/user';import { type Store as ConversationStore } from '../../action';import { MAX_HETERO_AUTO_RETRIES } from './heteroRetryConfig';@@ -87,6 +92,20 @@ const settleGenerationEntry = (notify?.();};+const getEffectiveAgencyConfig = (agentId: string) => {+ const agentState = getAgentStoreState();+ const sharedAgencyConfig = agentSelectors.getAgentConfigById(agentId)(agentState)?.agencyConfig;+ const isWorkspaceAgent = agentByIdSelectors.isWorkspaceAgentById(agentId)(agentState);+ const deviceOverride = isWorkspaceAgent+ ? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]+ : undefined;++ return {+ agencyConfig: resolveAgencyConfig(sharedAgencyConfig, deviceOverride),+ workspaceScoped: resolveWorkspaceScoped(isWorkspaceAgent, deviceOverride),+ };+};+/*** Prompt that resumes an interrupted hetero run instead of restarting it.*@@ -113,10 +132,16 @@ const resolveHeteroRunContext = (? topicSelectors.getTopicById(context.topicId)(chatStore): undefined;const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;- const agentWorkingDirectory = agentByIdSelectors.getAgentWorkingDirectoryById(- agentId,+ const agentState = getAgentStoreState();+ const desktopContext = globalAgentContextManager.getContext();+ const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(agentId);+ const agentWorkingDirectory = resolveAgentWorkingDirectory({+ agencyConfig,currentDeviceId,- )(getAgentStoreState());+ fallback: desktopContext?.desktopPath ?? desktopContext?.homePath,+ legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],+ workspaceScoped,+ });const workingDirectory = topic?.metadata?.workingDirectory || agentWorkingDirectory;// Drops the saved sessionId when its bound cwd disagrees with the current@@ -498,15 +523,13 @@ export const generationSlice: StateCreator<if (shouldProceed === false) return;}- const agentConfig = agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState());+ const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(context.agentId);const runtimeType = selectRuntimeType({- boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,- executionTarget: agentConfig?.agencyConfig?.executionTarget,- heterogeneousProvider: agentConfig?.agencyConfig?.heterogeneousProvider,+ boundDeviceId: agencyConfig?.boundDeviceId,+ executionTarget: agencyConfig?.executionTarget,+ heterogeneousProvider: agencyConfig?.heterogeneousProvider,isGatewayMode: chatStore.isGatewayModeEnabled(context.agentId),- isWorkspaceAgent: agentByIdSelectors.isWorkspaceAgentById(context.agentId)(- getAgentStoreState(),- ),+ isWorkspaceAgent: workspaceScoped,});// Hetero CLIs (CC / Codex) have no "continue a cut-off response" primitive@@ -573,20 +596,14 @@ export const generationSlice: StateCreator<// tool/provider error on a grouped reply is not resumable this way.if (!isHeterogeneousAgentStatusGuideError(erroredStep.error?.body)) return;- const agentConfig = agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState());- const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;+ const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(context.agentId);+ const heterogeneousProvider = agencyConfig?.heterogeneousProvider;const runtimeType = selectRuntimeType({- boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,- executionTarget: agentConfig?.agencyConfig?.executionTarget,+ boundDeviceId: agencyConfig?.boundDeviceId,+ executionTarget: agencyConfig?.executionTarget,heterogeneousProvider,isGatewayMode: chatStore.isGatewayModeEnabled(context.agentId),- // Workspace agents never run in-process on this member's desktop β a- // local/unset target coerces to sandbox/device. Omitting this would- // classify the retry as local hetero and spawn the CLI on the wrong- // machine; with it, gateway-routed runs take the whole-turn fallback.- isWorkspaceAgent: agentByIdSelectors.isWorkspaceAgentById(context.agentId)(- getAgentStoreState(),- ),+ isWorkspaceAgent: workspaceScoped,});const agentId = context.agentId;@@ -959,16 +976,14 @@ export const generationSlice: StateCreator<);if (postSwitchOp && postSwitchOp.status !== 'running') return;- const agentConfig = agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState());- const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;+ const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(context.agentId);+ const heterogeneousProvider = agencyConfig?.heterogeneousProvider;const runtimeType = selectRuntimeType({- boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,- executionTarget: agentConfig?.agencyConfig?.executionTarget,+ boundDeviceId: agencyConfig?.boundDeviceId,+ executionTarget: agencyConfig?.executionTarget,heterogeneousProvider,isGatewayMode: chatStore.isGatewayModeEnabled(context.agentId),- isWorkspaceAgent: agentByIdSelectors.isWorkspaceAgentById(context.agentId)(- getAgentStoreState(),- ),+ isWorkspaceAgent: workspaceScoped,});// ββ Gateway mode: trigger server-side regeneration ββdiff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.tsindex 35a3a106864..0f696f82d3e 100644--- a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts@@ -18,16 +18,20 @@ vi.mock(}),);-// Mirrors the real routing rule that matters here: a workspace-scoped agent's-// local/unset target coerces away from in-process execution (β gateway), so the-// test fails if `continueHeteroAfterError` stops passing `isWorkspaceAgent`.-const mockSelectRuntimeType = vi.fn((ctx: any) => (ctx?.isWorkspaceAgent ? 'gateway' : 'hetero'));+// The action must route from the merged effective config. A current member's+// private local override runs in-process even if the shared workspace row points+// at the gateway.+const mockSelectRuntimeType = vi.fn((ctx: any) =>+ ctx?.executionTarget === 'local' && !ctx?.isWorkspaceAgent ? 'hetero' : 'gateway',+);vi.mock('@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher', () => ({selectRuntimeType: (ctx: any) => mockSelectRuntimeType(ctx),}));let mockResumeSessionId: string | undefined = 'sess-1';let mockIsWorkspaceAgent = false;+let mockSharedExecutionTarget: 'device' | 'local' = 'local';+let mockWorkspaceOverride: { boundDeviceId: string; executionTarget: 'local' } | undefined;vi.mock('@/store/chat/slices/agentRun/actions/transports/hetero/heteroResume', () => ({resolveHeteroResume: () => ({ cwdChanged: false, resumeSessionId: mockResumeSessionId }),}));@@ -55,18 +59,24 @@ vi.mock('@/services/message', () => ({},}));-vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({}) }));+vi.mock('@/store/agent', () => ({+ getAgentStoreState: () => ({ localAgentWorkingDirectoryMap: {} }),+}));vi.mock('@/store/agent/selectors', () => ({agentByIdSelectors: {- getAgentWorkingDirectoryById: () => () => '/work/dir',isWorkspaceAgentById: () => () => mockIsWorkspaceAgent,},agentSelectors: {getAgentConfigById: () => () => ({agencyConfig: {- executionTarget: 'local',+ boundDeviceId: 'workspace-device',+ executionTarget: mockSharedExecutionTarget,heterogeneousProvider: { type: 'claude-code' },+ workingDirByDevice: {+ 'personal-device': '/Users/me/project',+ 'workspace-device': '/workspace/project',+ },},}),},@@ -77,7 +87,15 @@ vi.mock('@/store/chat/selectors', () => ({}));vi.mock('@/store/electron', () => ({- getElectronStoreState: () => ({ gatewayDeviceInfo: { deviceId: 'device-1' } }),+ getElectronStoreState: () => ({ gatewayDeviceInfo: { deviceId: 'personal-device' } }),+}));++vi.mock('@/store/user', () => ({+ getUserStoreState: () => ({+ workspaceUserPreference: {+ agentDeviceOverrides: mockWorkspaceOverride ? { 'agent-1': mockWorkspaceOverride } : {},+ },+ }),}));vi.mock('@/components/AntdStaticMethods', () => ({@@ -143,6 +161,8 @@ describe('continueHeteroAfterError', () => {vi.clearAllMocks();mockResumeSessionId = 'sess-1';mockIsWorkspaceAgent = false;+ mockSharedExecutionTarget = 'local';+ mockWorkspaceOverride = undefined;});it('keeps a tail step that did work: clears its error and chains the continuation onto it', async () => {@@ -224,11 +244,13 @@ describe('continueHeteroAfterError', () => {expect(executorParams().message).toBe(USER_MESSAGE.content);});- it('routes a workspace-scoped agent through the whole-turn fallback, never the local executor', async () => {- // Workspace agents never execute in-process on this member's desktop:- // selectRuntimeType must see the workspace scope (β gateway) so the retry- // neither mutates the preserved steps locally nor spawns the local CLI.+ it('resumes locally when a workspace member overrides the shared device with this desktop', async () => {mockIsWorkspaceAgent = true;+ mockSharedExecutionTarget = 'device';+ mockWorkspaceOverride = {+ boundDeviceId: 'personal-device',+ executionTarget: 'local',+ };const store = buildGroupStore([{ content: 'looking', id: 'step-1', tools: [{ id: 'call-1' }] },{ content: '', error: HETERO_RATE_LIMIT, id: 'step-2' },@@ -238,16 +260,40 @@ describe('continueHeteroAfterError', () => {await store.getState().continueHeteroAfterError('step-1');});- // The routing decision saw the workspace scope.expect(mockSelectRuntimeType).toHaveBeenCalledWith(- expect.objectContaining({ isWorkspaceAgent: true }),+ expect.objectContaining({+ boundDeviceId: 'personal-device',+ executionTarget: 'local',+ isWorkspaceAgent: false,+ }),);- // No local mutation of the failed run's steps.expect(mockUpdateMessage).not.toHaveBeenCalled();- expect(mockRemoveMessages).not.toHaveBeenCalled();- // Whole-turn fallback: the turn is replaced and regenerated via the- // gateway with the ORIGINAL user prompt β the local executor never runs.- expect(mockChatDeleteMessage).toHaveBeenCalledWith('step-1', { operationId: 'op-id' });+ expect(mockRemoveMessages).toHaveBeenCalledWith(['step-2'], CONTEXT);+ expect(mockChatDeleteMessage).not.toHaveBeenCalled();+ expect(mockExecuteGatewayAgent).not.toHaveBeenCalled();+ expect(mockExecuteHeterogeneousAgent).toHaveBeenCalledTimes(1);+ expect(executorParams().workingDirectory).toBe('/Users/me/project');+ });++ it('falls back through the gateway for a workspace shared-local target without an override', async () => {+ mockIsWorkspaceAgent = true;+ mockSharedExecutionTarget = 'local';+ const store = buildGroupStore([+ { content: 'looking', id: 'step-1', tools: [{ id: 'call-1' }] },+ { content: '', error: HETERO_RATE_LIMIT, id: 'step-2' },+ ]);++ await act(async () => {+ await store.getState().continueHeteroAfterError('step-1');+ });++ expect(mockSelectRuntimeType).toHaveBeenCalledWith(+ expect.objectContaining({+ boundDeviceId: 'workspace-device',+ executionTarget: 'local',+ isWorkspaceAgent: true,+ }),+ );expect(mockExecuteGatewayAgent).toHaveBeenCalledWith(expect.objectContaining({ message: USER_MESSAGE.content }),);diff --git a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.tsindex f4aef130a98..5306dda82f0 100644--- a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts+++ b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts@@ -42,11 +42,12 @@ vi.mock('@/services/message', () => ({messageService: { createMessage: vi.fn(async () => ({ id: 'assistant-new' })) },}));-vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({}) }));+vi.mock('@/store/agent', () => ({+ getAgentStoreState: () => ({ localAgentWorkingDirectoryMap: {} }),+}));vi.mock('@/store/agent/selectors', () => ({agentByIdSelectors: {- getAgentWorkingDirectoryById: () => () => '/work/dir',isWorkspaceAgentById: () => () => false,},agentSelectors: {@@ -54,6 +55,7 @@ vi.mock('@/store/agent/selectors', () => ({agencyConfig: {executionTarget: 'local',heterogeneousProvider: { type: 'claude-code' },+ workingDirByDevice: { 'device-1': '/work/dir' },},}),},diff --git a/src/helpers/agentWorkingDirectory.test.ts b/src/helpers/agentWorkingDirectory.test.tsindex 3b579c2560e..0dd3eecbed4 100644--- a/src/helpers/agentWorkingDirectory.test.ts+++ b/src/helpers/agentWorkingDirectory.test.ts@@ -38,6 +38,28 @@ describe('resolveTargetDeviceId', () => {it('returns undefined when device target has no boundDeviceId', () => {expect(resolveTargetDeviceId(cfg({ executionTarget: 'device' }), 'cur')).toBeUndefined();});++ it('uses only the shared binding when workspace coercion is preserved', () => {+ expect(+ resolveTargetDeviceId(+ cfg({ boundDeviceId: 'workspace-device', executionTarget: 'local' }),+ 'member-device',+ { workspaceScoped: true },+ ),+ ).toBe('workspace-device');+ expect(+ resolveTargetDeviceId(cfg({ executionTarget: 'local' }), 'member-device', {+ workspaceScoped: true,+ }),+ ).toBe(undefined);+ expect(+ resolveTargetDeviceId(+ cfg({ boundDeviceId: 'stale-device', executionTarget: 'sandbox' }),+ 'member-device',+ { workspaceScoped: true },+ ),+ ).toBeUndefined();+ });});describe('resolveAgentWorkingDirectory', () => {@@ -89,6 +111,52 @@ describe('resolveAgentWorkingDirectory', () => {);});+ it('keys a shared local fallback by its bound workspace device', () => {+ const agencyConfig = cfg({+ boundDeviceId: 'workspace-device',+ executionTarget: 'local',+ workingDirByDevice: {+ 'member-device': '/member-project',+ 'workspace-device': '/workspace-project',+ },+ });++ expect(+ resolveAgentWorkingDirectory({+ agencyConfig,+ currentDeviceId: 'member-device',+ workspaceScoped: true,+ }),+ ).toBe('/workspace-project');+ });++ it('does not leak member-local fallback paths into a workspace-scoped run', () => {+ const agencyConfig = cfg({+ boundDeviceId: 'workspace-device',+ executionTarget: 'local',+ });++ expect(+ resolveAgentWorkingDirectory({+ agencyConfig,+ currentDeviceId: 'member-device',+ deviceDefaultCwd: '/workspace-default',+ fallback: '/Users/member',+ legacyAgentWorkingDirectory: '/Users/member/project',+ workspaceScoped: true,+ }),+ ).toBe('/workspace-default');+ expect(+ resolveAgentWorkingDirectory({+ agencyConfig,+ currentDeviceId: 'member-device',+ fallback: '/Users/member',+ legacyAgentWorkingDirectory: '/Users/member/project',+ workspaceScoped: true,+ }),+ ).toBeUndefined();+ });+it('uses the active worktree from the per-device source entry as the effective cwd', () => {const agencyConfig = cfg({executionTarget: 'local',diff --git a/src/helpers/agentWorkingDirectory.ts b/src/helpers/agentWorkingDirectory.tsindex 805cd625864..c53c764367c 100644--- a/src/helpers/agentWorkingDirectory.ts+++ b/src/helpers/agentWorkingDirectory.ts@@ -5,6 +5,10 @@ import type {} from '@lobechat/types';import { getWorkingDirEffectivePath, getWorkingDirSourcePath } from '@lobechat/types';+interface ResolveTargetDeviceIdOptions {+ workspaceScoped?: boolean;+}+/*** The device a run targets: an explicitly bound remote device, this machine,* or (on web) a desktop-local binding synced from the desktop app.@@ -14,12 +18,22 @@ import { getWorkingDirEffectivePath, getWorkingDirSourcePath } from '@lobechat/texport const resolveTargetDeviceId = (agencyConfig: LobeAgentAgencyConfig | undefined,currentDeviceId: string | undefined,-): string | undefined =>- agencyConfig?.executionTarget === 'device'+ { workspaceScoped = false }: ResolveTargetDeviceIdOptions = {},+): string | undefined => {+ if (workspaceScoped) {+ return agencyConfig?.executionTarget === 'local' ||+ agencyConfig?.executionTarget === 'device' ||+ agencyConfig?.executionTarget === 'auto'+ ? agencyConfig.boundDeviceId+ : undefined;+ }++ return agencyConfig?.executionTarget === 'device'? agencyConfig?.boundDeviceId: agencyConfig?.executionTarget === 'local'? currentDeviceId || agencyConfig?.boundDeviceId: currentDeviceId;+};const toWorkingDirConfig = (value: WorkingDirConfigValue | null | undefined,@@ -48,6 +62,7 @@ export const resolveAgentWorkingDirectoryConfig = (params: {legacyAgentWorkingDirectory?: string;topicWorkingDirectory?: string;topicWorkingDirectoryConfig?: WorkingDirConfig;+ workspaceScoped?: boolean;}): WorkingDirConfig | undefined => {const {agencyConfig,@@ -57,18 +72,24 @@ export const resolveAgentWorkingDirectoryConfig = (params: {legacyAgentWorkingDirectory,topicWorkingDirectory,topicWorkingDirectoryConfig,+ workspaceScoped,} = params;if (topicWorkingDirectoryConfig) return topicWorkingDirectoryConfig;if (topicWorkingDirectory) return { path: topicWorkingDirectory };- const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);+ const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {+ workspaceScoped,+ });const agentChoice = toWorkingDirConfig(targetDeviceId ? agencyConfig?.workingDirByDevice?.[targetDeviceId] : undefined,);if (agentChoice) return agentChoice;- if (legacyAgentWorkingDirectory) return { path: legacyAgentWorkingDirectory };+ // Legacy + desktop/home fallbacks belong to the current member's machine.+ // They are invalid when an unoverridden workspace config routes to a shared+ // device (or sandbox), where only shared/device-scoped paths are meaningful.+ if (!workspaceScoped && legacyAgentWorkingDirectory) return { path: legacyAgentWorkingDirectory };if (deviceDefaultCwd) return { path: deviceDefaultCwd };- if (fallback) return { path: fallback };+ if (!workspaceScoped && fallback) return { path: fallback };};export const resolveAgentWorkingDirectory = (diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.tsindex a40342ce3cb..68d484ede19 100644--- a/src/helpers/executionTarget.test.ts+++ b/src/helpers/executionTarget.test.ts@@ -9,6 +9,7 @@ import {resolveExecutionPlan,resolveExecutionTarget,resolveRuntimeMode,+ resolveWorkspaceScoped,} from './executionTarget';const cfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfig => ({ ...over });@@ -17,6 +18,16 @@ const ampCfg = (over: Partial<LobeAgentAgencyConfig> = {}): LobeAgentAgencyConfi...over,});+describe('resolveWorkspaceScoped', () => {+ it('preserves shared-row coercion until a workspace member explicitly selects a target', () => {+ expect(resolveWorkspaceScoped(false, undefined)).toBe(false);+ expect(resolveWorkspaceScoped(true, undefined)).toBe(true);+ expect(resolveWorkspaceScoped(true, { boundDeviceId: 'member-device' })).toBe(true);+ expect(resolveWorkspaceScoped(true, { executionTarget: 'local' })).toBe(false);+ expect(resolveWorkspaceScoped(true, { executionTarget: 'device' })).toBe(false);+ });+});+describe('resolveExecutionTarget', () => {it('returns the stored target verbatim when set', () => {expect(diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.tsindex 9bc482ab639..0cf96a48e23 100644--- a/src/helpers/executionTarget.ts+++ b/src/helpers/executionTarget.ts@@ -1,4 +1,5 @@import type {+ AgentDeviceOverride,DeviceExecutionTarget,LobeAgentAgencyConfig,LobeAgentChatConfig,@@ -6,6 +7,16 @@ import type {} from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';+/**+ * Whether a workspace config still needs the shared-row safety coercion.+ * A member opts out only by explicitly choosing an execution target; a missing+ * or bound-device-only override still inherits the raw shared target.+ */+export const resolveWorkspaceScoped = (+ isWorkspaceAgent: boolean,+ deviceOverride: AgentDeviceOverride | null | undefined,+): boolean => isWorkspaceAgent && deviceOverride?.executionTarget === undefined;+/*** The agent's tool mode β explicit `chatConfig.toolMode` wins; otherwise derive* from `enableAgentMode` (undefined = agent). `chat` = no execution@@ -84,16 +95,16 @@ export interface ResolveExecutionTargetOptions {*/trigger?: RequestTrigger;/**- * The agent belongs to a workspace (`agent.workspaceId` is set). Every- * member runs a workspace agent through the shared device pool, so the- * CURRENT member's own client is never a valid execution host β `local`- * would silently run the shared agent on whichever personal machine opened- * it. Treats client execution as unavailable: an unset target no longer- * defaults to `local`, and a stored `local` (synced from before the agent- * joined the workspace) coerces to `sandbox` when supported (otherwise- * `none`) β or, for hetero agents, to `device` when a (grandfathered)- * `boundDeviceId` pins a machine, matching the write-time guard in- * `AgentModel.assertWorkspaceDeviceBinding`.+ * The supplied config is the raw workspace-shared fallback and has NOT been+ * merged with the current member's `agentDeviceOverrides`. Such a config+ * must not run `local` on whichever member happened to open it, so this+ * treats client execution as unavailable and coerces legacy local values to+ * sandbox/device as appropriate.+ *+ * Set this to `false` only when the current member has an explicit+ * `executionTarget` override. Calling `resolveAgencyConfig` alone is not+ * sufficient: without an override it returns the raw shared config unchanged.+ * `useEffectiveAgencyConfig` exposes this distinction as `workspaceScoped`.*/workspaceScoped?: boolean;}@@ -153,8 +164,9 @@ export const resolveExecutionTarget = (workspaceScoped,}: ResolveExecutionTargetOptions,): DeviceExecutionTarget => {- // A workspace agent never executes on the current member's own client β see- // `workspaceScoped` above. Same coercions as a client-less environment.+ // An unmerged workspace-shared config never executes on the current member's+ // own client β see `workspaceScoped` above. Same coercions as a client-less+ // environment.const clientAvailable = clientExecutionAvailable && !workspaceScoped;const sandboxAvailable =sandboxExecutionAvailable ?? agencyConfig?.heterogeneousProvider?.type !== 'amp';diff --git a/src/hooks/useEffectiveAgencyConfig.test.ts b/src/hooks/useEffectiveAgencyConfig.test.tsindex f7002fcf477..48e00092d00 100644--- a/src/hooks/useEffectiveAgencyConfig.test.ts+++ b/src/hooks/useEffectiveAgencyConfig.test.ts@@ -66,6 +66,7 @@ describe('useEffectiveAgencyConfig', () => {const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));expect(result.current.agencyConfig).toEqual(sharedConfig);+ expect(result.current.workspaceScoped).toBe(false);});it('merges the caller override over the shared config for workspace agents', () => {@@ -80,6 +81,7 @@ describe('useEffectiveAgencyConfig', () => {boundDeviceId: 'my-device',executionTarget: 'local',});+ expect(result.current.workspaceScoped).toBe(false);});it('falls back to the shared config when a workspace agent has no override', () => {@@ -88,6 +90,16 @@ describe('useEffectiveAgencyConfig', () => {const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));expect(result.current.agencyConfig).toEqual(sharedConfig);+ expect(result.current.workspaceScoped).toBe(true);+ });++ it('preserves workspace scope when an override has no explicit execution target', () => {+ setupStores({ override: { boundDeviceId: 'my-device' }, workspaceId: 'ws-1' });++ const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));++ expect(result.current.agencyConfig?.boundDeviceId).toBe('my-device');+ expect(result.current.workspaceScoped).toBe(true);});it('reports preference loading only for workspace agents', () => {@@ -137,5 +149,6 @@ describe('useEffectiveAgencyConfig', () => {expect(result.current.agencyConfig).toBeUndefined();expect(result.current.isPreferenceLoading).toBe(false);+ expect(result.current.workspaceScoped).toBe(false);});});diff --git a/src/hooks/useEffectiveAgencyConfig.ts b/src/hooks/useEffectiveAgencyConfig.tsindex 444bb13eb6a..40998e9b824 100644--- a/src/hooks/useEffectiveAgencyConfig.ts+++ b/src/hooks/useEffectiveAgencyConfig.ts@@ -1,6 +1,7 @@import type { LobeAgentAgencyConfig } from '@lobechat/types';import { resolveAgencyConfig } from '@lobechat/types';+import { resolveWorkspaceScoped } from '@/helpers/executionTarget';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { useUserStore } from '@/store/user';@@ -15,6 +16,13 @@ export interface UseEffectiveAgencyConfigResult {* should wait instead of acting on a value that may flip.*/isPreferenceLoading: boolean;+ /**+ * The effective config still comes from the workspace-shared fallback because+ * this member has not explicitly selected an execution target. Callers must+ * preserve workspace coercion so a legacy shared `local` value cannot execute+ * on whichever member happens to open the agent.+ */+ workspaceScoped: boolean;}/**@@ -60,5 +68,6 @@ export const useEffectiveAgencyConfig = (agentId?: string): UseEffectiveAgencyCoreturn {agencyConfig: resolveAgencyConfig(sharedAgencyConfig, isWorkspaceAgent ? override : undefined),isPreferenceLoading: isWorkspaceAgent && isLoading,+ workspaceScoped: resolveWorkspaceScoped(isWorkspaceAgent, override),};};diff --git a/src/hooks/useEffectiveWorkingDirectory.ts b/src/hooks/useEffectiveWorkingDirectory.tsindex f3a63147217..fee8fad41e5 100644--- a/src/hooks/useEffectiveWorkingDirectory.ts+++ b/src/hooks/useEffectiveWorkingDirectory.ts@@ -35,7 +35,7 @@ export const useEffectiveWorkingDirectory = (agentId?: string): string | undefin// 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 { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);const legacyAgentWorkingDirectory = useAgentStore((s) =>agentId ? s.localAgentWorkingDirectoryMap[agentId] : undefined,);@@ -44,7 +44,9 @@ export const useEffectiveWorkingDirectory = (agentId?: string): string | undefin(s) => topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,);const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);- const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);+ const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {+ workspaceScoped,+ });const deviceDefaultCwd = useDeviceStore(deviceSelectors.getDeviceDefaultCwd(targetDeviceId));// Home is the last-resort default, desktop-only (matches the legacy selector).@@ -59,5 +61,6 @@ export const useEffectiveWorkingDirectory = (agentId?: string): string | undefinlegacyAgentWorkingDirectory,topicWorkingDirectory,topicWorkingDirectoryConfig,+ workspaceScoped,});};diff --git a/src/hooks/useRemoteAgentDeviceGuard.test.ts b/src/hooks/useRemoteAgentDeviceGuard.test.tsindex 4dcdb91c068..706fa8dd023 100644--- a/src/hooks/useRemoteAgentDeviceGuard.test.ts+++ b/src/hooks/useRemoteAgentDeviceGuard.test.ts@@ -30,6 +30,7 @@ describe('useRemoteAgentDeviceGuard', () => {heterogeneousProvider: { type: 'codex' },},isPreferenceLoading: false,+ workspaceScoped: false,});mockedListDevices.mockResolvedValue([{ deviceId: 'creator-device', online: false },@@ -49,6 +50,7 @@ describe('useRemoteAgentDeviceGuard', () => {heterogeneousProvider: { type: 'claude-code' },},isPreferenceLoading: false,+ workspaceScoped: false,});mockedListDevices.mockResolvedValue([{ deviceId: 'my-device', online: false }] as never);@@ -65,6 +67,7 @@ describe('useRemoteAgentDeviceGuard', () => {heterogeneousProvider: { type: 'codex' },},isPreferenceLoading: true,+ workspaceScoped: true,});const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));@@ -77,6 +80,7 @@ describe('useRemoteAgentDeviceGuard', () => {mockedUseEffectiveAgencyConfig.mockReturnValue({agencyConfig: { heterogeneousProvider: { type: 'codex' } },isPreferenceLoading: false,+ workspaceScoped: false,});const { result } = renderHook(() => useRemoteAgentDeviceGuard({ agentId: 'agent-1' }));diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsxindex f271335371d..366766ff2c9 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroControlBar.tsx@@ -131,8 +131,7 @@ const HeteroControlBar = memo(() => {const isLoading = useAgentStore(agentByIdSelectors.isAgentConfigLoadingById(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));+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);// On web there's no full-access badge / skeleton β just the workspace controls// (the cloud repo switcher is rendered inside WorkspaceControls). The CLI@@ -169,7 +168,7 @@ const HeteroControlBar = memo(() => {resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: isDesktop,isHetero: true,- workspaceScoped: isWorkspaceAgent,+ workspaceScoped,}) === 'local';const shouldShowCodexQuota = heteroProvider?.type === 'codex' && isLocalHeteroExecution;const shouldShowClaudeQuota = heteroProvider?.type === 'claude-code' && isLocalHeteroExecution;diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsxindex ae21d28f308..b923618de65 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu.test.tsx@@ -1,13 +1,15 @@/*** @vitest-environment happy-dom*/-import type { ClaudeCodeQuotaSnapshot, CodexQuotaSnapshot } from '@lobechat/electron-client-ipc';+import type * as LobechatConstModule from '@lobechat/const';+import type * as ElectronClientIpcModule from '@lobechat/electron-client-ipc';import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';import CodexQuotaMenu from './CodexQuotaMenu';+import HeteroControlBar from './HeteroControlBar';const mockService = vi.hoisted(() => ({consumeCodexRateLimitResetCredit: vi.fn(),@@ -15,6 +17,49 @@ const mockService = vi.hoisted(() => ({getCodexQuota: vi.fn(),}));+const effectiveAgencyConfig = vi.hoisted(() => ({+ current: {+ boundDeviceId: 'personal-device',+ executionTarget: 'local' as const,+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ },+ workspaceScoped: false,+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<typeof LobechatConstModule>()),+ isDesktop: true,+}));++vi.mock('@lobechat/electron-client-ipc', async (importOriginal) => ({+ ...(await importOriginal<typeof ElectronClientIpcModule>()),+ useWatchBroadcast: vi.fn(),+}));++vi.mock('@/features/ChatInput/ControlBar/WorkspaceControls', () => ({+ default: () => <div data-testid="workspace-controls" />,+}));++vi.mock('@/features/ChatInput/hooks/useAgentId', () => ({ useAgentId: () => 'agent-1' }));++vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => ({+ agencyConfig: effectiveAgencyConfig.current,+ workspaceScoped: effectiveAgencyConfig.workspaceScoped,+ }),+}));++vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (state: Record<string, unknown>) => unknown) => selector({}),+}));++vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ isAgentConfigLoadingById: () => () => false,+ isWorkspaceAgentById: () => () => true,+ },+}));+const { confirmModalMock, toastErrorMock, toastSuccessMock } = vi.hoisted(() => ({confirmModalMock: vi.fn(),toastErrorMock: vi.fn(),@@ -101,8 +146,8 @@ vi.mock('@lobehub/ui/base-ui', () => ({}));const claudeSnapshot = (- overrides: Partial<ClaudeCodeQuotaSnapshot> = {},-): ClaudeCodeQuotaSnapshot => ({+ overrides: Partial<ElectronClientIpcModule.ClaudeCodeQuotaSnapshot> = {},+): ElectronClientIpcModule.ClaudeCodeQuotaSnapshot => ({error: null,provider: 'claude-code',scopedWeekly: null,@@ -113,7 +158,9 @@ const claudeSnapshot = (...overrides,});-const codexSnapshot = (overrides: Partial<CodexQuotaSnapshot> = {}): CodexQuotaSnapshot => ({+const codexSnapshot = (+ overrides: Partial<ElectronClientIpcModule.CodexQuotaSnapshot> = {},+): ElectronClientIpcModule.CodexQuotaSnapshot => ({error: null,provider: 'codex',rateLimitResetCredits: null,@@ -125,6 +172,12 @@ const codexSnapshot = (overrides: Partial<CodexQuotaSnapshot> = {}): CodexQuotaS});beforeEach(() => {+ effectiveAgencyConfig.current = {+ boundDeviceId: 'personal-device',+ executionTarget: 'local',+ heterogeneousProvider: { command: 'codex', type: 'codex' },+ };+ effectiveAgencyConfig.workspaceScoped = false;confirmModalMock.mockReset();mockService.consumeCodexRateLimitResetCredit.mockReset();mockService.getClaudeCodeQuota.mockReset();@@ -133,6 +186,35 @@ beforeEach(() => {toastSuccessMock.mockReset();});+describe('HeteroControlBar', () => {+ it('shows local Codex quota for a workspace member local-device override', async () => {+ mockService.getCodexQuota.mockResolvedValue(+ codexSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),+ );++ render(<HeteroControlBar />);++ expect(+ await screen.findByRole('button', { name: 'heteroAgent.codexQuota.tooltip' }),+ ).toBeTruthy();+ expect(mockService.getCodexQuota).toHaveBeenCalledWith({ command: 'codex', env: undefined });+ });++ it('does not show local quota for a workspace shared-local fallback without an override', () => {+ effectiveAgencyConfig.current = {+ boundDeviceId: 'workspace-device',+ executionTarget: 'local',+ heterogeneousProvider: { command: 'codex', type: 'codex' },+ };+ effectiveAgencyConfig.workspaceScoped = true;++ render(<HeteroControlBar />);++ expect(screen.queryByRole('button', { name: 'heteroAgent.codexQuota.tooltip' })).toBeNull();+ expect(mockService.getCodexQuota).not.toHaveBeenCalled();+ });+});+describe('ClaudeCodeQuotaMenu', () => {it('renders session, weekly, and model-scoped windows from the snapshot', async () => {mockService.getClaudeCodeQuota.mockResolvedValue(@@ -353,10 +435,10 @@ describe('ClaudeCodeQuotaMenu', () => {});it('ignores stale request loading updates after switching Claude Code credential source', async () => {- const requests: Array<(snapshot: ClaudeCodeQuotaSnapshot) => void> = [];+ const requests: Array<(snapshot: ElectronClientIpcModule.ClaudeCodeQuotaSnapshot) => void> = [];mockService.getClaudeCodeQuota.mockImplementation(() =>- new Promise<ClaudeCodeQuotaSnapshot>((resolve) => {+ new Promise<ElectronClientIpcModule.ClaudeCodeQuotaSnapshot>((resolve) => {requests.push(resolve);}),);@@ -612,7 +694,7 @@ describe('CodexQuotaMenu', () => {});it('clears refresh loading when a reset supersedes an in-flight quota request', async () => {- const requests: Array<(snapshot: CodexQuotaSnapshot) => void> = [];+ const requests: Array<(snapshot: ElectronClientIpcModule.CodexQuotaSnapshot) => void> = [];mockService.getCodexQuota.mockResolvedValueOnce(codexSnapshot({@@ -622,7 +704,7 @@ describe('CodexQuotaMenu', () => {).mockImplementationOnce(() =>- new Promise<CodexQuotaSnapshot>((resolve) => {+ new Promise<ElectronClientIpcModule.CodexQuotaSnapshot>((resolve) => {requests.push(resolve);}),);diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsxindex 3cf51327dda..49373232aa3 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx@@ -23,8 +23,6 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { resolveExecutionTarget } from '@/helpers/executionTarget';import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useRemoteAgentDeviceGuard } from '@/hooks/useRemoteAgentDeviceGuard';-import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import HeteroControlBar from './HeteroControlBar';@@ -98,13 +96,12 @@ const HeterogeneousChatInput = memo(() => {// 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 { agencyConfig, isPreferenceLoading, workspaceScoped } = useEffectiveAgencyConfig(agentId);const providerType = agencyConfig?.heterogeneousProvider?.type;- const isWorkspaceAgent = useAgentStore(agentByIdSelectors.isWorkspaceAgentById(agentId));const executionTarget = resolveExecutionTarget(agencyConfig, {isHetero: !!providerType,clientExecutionAvailable: isDesktop,- workspaceScoped: isWorkspaceAgent,+ workspaceScoped,});const isRemoteAgent = !!providerType && isRemoteHeterogeneousType(providerType);const ampDeviceSelectionRequired = providerType === 'amp' && executionTarget === 'none';diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsxindex d431ff5382b..828e2b876e3 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx@@ -22,7 +22,19 @@ const rightPanel = vi.hoisted(() => ({const agentStore = vi.hoisted(() => ({activeAgentId: undefined as string | undefined,- isLocalSystemEnabled: false,+ isHeterogeneous: false,+ rawAgencyConfig: undefined as+ { boundDeviceId?: string; executionTarget?: 'device' | 'local' } | undefined,+}));++const effectiveConfig = vi.hoisted(() => ({+ agencyConfig: undefined as+ { boundDeviceId?: string; executionTarget?: 'device' | 'local' } | undefined,+ workspaceScoped: false,+}));++const filesProps = vi.hoisted(() => ({+ current: undefined as { deviceId?: string; workingDirectory: string } | undefined,}));const reviewState = vi.hoisted(() => ({@@ -51,7 +63,12 @@ vi.mock('@/features/RightPanel', () => ({// βββ stub every downstream dependency so the sidebar renders deterministically ββ-vi.mock('../Files', () => ({ default: () => <div /> }));+vi.mock('../Files', () => ({+ default: (props: { deviceId?: string; workingDirectory: string }) => {+ filesProps.current = props;+ return <div data-testid="files" />;+ },+}));vi.mock('../Review', () => ({ default: () => <div /> }));vi.mock('../ProgressSection', () => ({ default: () => <div /> }));vi.mock('../ResourcesSection', () => ({ default: () => <div /> }));@@ -64,15 +81,14 @@ vi.mock('@/store/agent', () => ({}));vi.mock('@/store/agent/selectors', () => ({agentByIdSelectors: {- getAgencyConfigById: () => () => undefined,+ getAgencyConfigById: () => () => agentStore.rawAgencyConfig,isWorkspaceAgentById: () => () => false,},agentSelectors: {- isCurrentAgentHeterogeneous: () => false,+ isCurrentAgentHeterogeneous: () => agentStore.isHeterogeneous,},chatConfigByIdSelectors: {isChatModeById: () => () => false,- isLocalSystemEnabledById: () => () => agentStore.isLocalSystemEnabled,},}));vi.mock('@/store/global', () => ({@@ -96,11 +112,22 @@ vi.mock('@/features/ChatInput/ControlBar/useRepoType', () => ({vi.mock('@/hooks/useEffectiveWorkingDirectory', () => ({useEffectiveWorkingDirectory: () => reviewState.workingDirectory,}));+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => ({+ agencyConfig: effectiveConfig.agencyConfig,+ workspaceScoped: effectiveConfig.workspaceScoped,+ }),+}));vi.mock('@/hooks/useLocalStorageState', () => ({useLocalStorageState: () => [reviewState.showTree, vi.fn()],}));vi.mock('@/helpers/agentWorkingDirectory', () => ({ resolveTargetDeviceId: () => undefined }));-vi.mock('@/helpers/executionTarget', () => ({ resolveExecutionTarget: () => 'local' }));+vi.mock('@/helpers/executionTarget', () => ({+ resolveExecutionTarget: (+ agencyConfig: { executionTarget?: 'device' | 'local' } | undefined,+ options: { workspaceScoped?: boolean },+ ) => (options.workspaceScoped ? 'device' : (agencyConfig?.executionTarget ?? 'local')),+}));vi.mock('@/helpers/gatewayMode', () => ({ useIsGatewayModeEnabled: () => false }));vi.mock('react-i18next', () => ({@@ -118,7 +145,11 @@ vi.mock('antd-style', () => ({beforeEach(() => {agentStore.activeAgentId = undefined;- agentStore.isLocalSystemEnabled = false;+ agentStore.isHeterogeneous = false;+ agentStore.rawAgencyConfig = undefined;+ effectiveConfig.agencyConfig = undefined;+ effectiveConfig.workspaceScoped = false;+ filesProps.current = undefined;reviewState.repoType = undefined;reviewState.showTree = false;reviewState.workingDirectory = undefined;@@ -158,7 +189,6 @@ describe('AgentWorkingSidebar β controlled panel width', () => {it('clamps two-pane Review width without overwriting the persisted preference', () => {agentStore.activeAgentId = 'agent';- agentStore.isLocalSystemEnabled = true;reviewState.repoType = 'git';reviewState.showTree = true;reviewState.workingDirectory = 'C:\\repo';@@ -220,4 +250,48 @@ describe('AgentWorkingSidebar β controlled panel width', () => {expect(rightPanel.current?.width).toBe(360);expect(globalStore.updateSystemStatus).not.toHaveBeenCalled();});++ it('indexes a workspace-local project on this desktop instead of the shared bound device', () => {+ agentStore.activeAgentId = 'agent';+ agentStore.isHeterogeneous = true;+ // The shared row can still point at a workspace device. This member's+ // private override selects their own desktop and must win for both the cwd+ // and the file transport.+ agentStore.rawAgencyConfig = {+ boundDeviceId: 'workspace-device',+ executionTarget: 'device',+ };+ effectiveConfig.agencyConfig = {+ boundDeviceId: 'personal-device',+ executionTarget: 'local',+ };+ reviewState.workingDirectory = '/Users/me/project';+ globalStore.status.workingSidebarTab = 'files';++ render(<AgentWorkingSidebar />);++ expect(filesProps.current).toEqual({+ deviceId: undefined,+ workingDirectory: '/Users/me/project',+ });+ });++ it('keeps a shared local fallback on its bound workspace device without a member override', () => {+ agentStore.activeAgentId = 'agent';+ agentStore.isHeterogeneous = true;+ effectiveConfig.agencyConfig = {+ boundDeviceId: 'workspace-device',+ executionTarget: 'local',+ };+ effectiveConfig.workspaceScoped = true;+ reviewState.workingDirectory = '/workspace/project';+ globalStore.status.workingSidebarTab = 'files';++ render(<AgentWorkingSidebar />);++ expect(filesProps.current).toEqual({+ deviceId: 'workspace-device',+ workingDirectory: '/workspace/project',+ });+ });});diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsxindex 749667c6c5d..7acf78acda9 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx@@ -12,14 +12,11 @@ import RightPanel from '@/features/RightPanel';import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';import { useLocalStorageState } from '@/hooks/useLocalStorageState';import { useAgentStore } from '@/store/agent';-import {- agentByIdSelectors,- agentSelectors,- chatConfigByIdSelectors,-} from '@/store/agent/selectors';+import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { useElectronStore } from '@/store/electron';import { useGlobalStore } from '@/store/global';@@ -112,9 +109,6 @@ const AgentWorkingSidebar = memo(() => {]);const activeAgentId = useAgentStore((s) => s.activeAgentId);const topicId = useChatStore((s) => s.activeTopicId);- const isLocalSystemEnabled = useAgentStore((s) =>- activeAgentId ? chatConfigByIdSelectors.isLocalSystemEnabledById(activeAgentId)(s) : false,- );const isChatMode = useAgentStore((s) =>activeAgentId ? chatConfigByIdSelectors.isChatModeById(activeAgentId)(s) : false,);@@ -126,21 +120,18 @@ const AgentWorkingSidebar = memo(() => {const workingDirectory = useEffectiveWorkingDirectory(activeAgentId);// Effective target device for git ops β bound device for remote agents, this// machine otherwise. Resolved the same way WorkingDirectoryPicker / GitStatus do.- const agencyConfig = useAgentStore((s) =>- activeAgentId ? agentByIdSelectors.getAgencyConfigById(activeAgentId)(s) : undefined,- );+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(activeAgentId);const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);- const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId);+ const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {+ workspaceScoped,+ });const repoType = useRepoType(workingDirectory, targetDeviceId);const deviceRoutingAvailable = useIsGatewayModeEnabled(activeAgentId);- const isWorkspaceAgent = useAgentStore((s) =>- activeAgentId ? agentByIdSelectors.isWorkspaceAgentById(activeAgentId)(s) : false,- );const effectiveTarget = resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: isDesktop,deviceRoutingAvailable,isHetero,- workspaceScoped: isWorkspaceAgent,+ workspaceScoped,});// Running against a bound device (remote, or this machine as a device): file@@ -152,12 +143,11 @@ const AgentWorkingSidebar = memo(() => {// remote device RPC; local "This device" must keep Electron IPC + file-open// actions enabled.const remoteDeviceId = isDeviceMode ? agencyConfig.boundDeviceId : undefined;+ const isLocalExecution = effectiveTarget === 'local';// Files tab is an agent-mode affordance β in plain chat mode the working// directory is irrelevant to the user, so hide the tab even when one resolves.- const filesAvailable =- !isChatMode && (isLocalSystemEnabled || isDeviceMode) && !!workingDirectory;- const reviewAvailable =- (isLocalSystemEnabled || isDeviceMode) && !!workingDirectory && !!repoType;+ const filesAvailable = !isChatMode && (isLocalExecution || isDeviceMode) && !!workingDirectory;+ const reviewAvailable = (isLocalExecution || isDeviceMode) && !!workingDirectory && !!repoType;const paramsAvailable = !isHetero;// The in-app browser pages are main-process WebContentsViews β desktop only,// and gated behind the Labs toggle while the feature matures.diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex af0708cb7b5..2ea41d3ea2f 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -14,6 +14,7 @@ import { topicMapKey } from '@/store/chat/utils/topicMapKey';import { getSessionStoreState } from '@/store/session';import * as toolStoreModule from '@/store/tool';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';+import { useUserStore } from '@/store/user';import { useChatStore } from '../../../../store';import { createMockAgentConfig, createMockMessage, TEST_CONTENT, TEST_IDS } from './fixtures';@@ -65,6 +66,7 @@ beforeEach(() => {const sessionStore = getSessionStoreState();vi.spyOn(sessionStore, 'triggerSessionUpdate').mockResolvedValue(undefined);vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);+ useUserStore.setState({ workspaceUserPreference: {} });act(() => {useChatStore.setState({@@ -1700,6 +1702,103 @@ describe('ConversationLifecycle actions', () => {);});+ it('runs a workspace Codex local-device override in the desktop heterogeneous runtime', async () => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ boundDeviceId: 'workspace-device',+ executionTarget: 'device',+ heterogeneousProvider: { command: 'codex', type: 'codex' },+ },+ },+ });++ const { agentByIdSelectors } = await import('@/store/agent/selectors');+ vi.spyOn(agentByIdSelectors, 'isWorkspaceAgentById').mockReturnValue(() => true);+ useUserStore.setState({+ workspaceUserPreference: {+ agentDeviceOverrides: {+ [TEST_IDS.SESSION_ID]: {+ boundDeviceId: 'personal-device',+ executionTarget: 'local',+ },+ },+ },+ });++ const executeGatewayAgent = vi.fn();+ act(() => {+ useChatStore.setState({ executeGatewayAgent });+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ topicId: TEST_IDS.TOPIC_ID,+ topics: [],+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);+ executeHeterogeneousAgentMock.mockResolvedValue(undefined);++ const { result } = renderHook(() => useChatStore());+ await act(async () => {+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ context: createTestContext(),+ });+ });++ expect(executeHeterogeneousAgentMock).toHaveBeenCalledTimes(1);+ expect(executeGatewayAgent).not.toHaveBeenCalled();+ });++ it('keeps a workspace shared-local fallback on the gateway without a member override', async () => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ boundDeviceId: 'workspace-device',+ executionTarget: 'local',+ heterogeneousProvider: { command: 'codex', type: 'codex' },+ },+ },+ });++ const { agentByIdSelectors } = await import('@/store/agent/selectors');+ vi.spyOn(agentByIdSelectors, 'isWorkspaceAgentById').mockReturnValue(() => true);++ const executeGatewayAgent = vi.fn().mockResolvedValue(undefined);+ act(() => {+ useChatStore.setState({ executeGatewayAgent });+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ topicId: TEST_IDS.TOPIC_ID,+ topics: [],+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ const { result } = renderHook(() => useChatStore());+ await act(async () => {+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ context: createTestContext(),+ });+ });++ expect(executeGatewayAgent).toHaveBeenCalledTimes(1);+ expect(executeHeterogeneousAgentMock).not.toHaveBeenCalled();+ });+it('should route new-topic heterogeneous streaming updates to the persisted topic key', async () => {mockConstEnv.isDesktop = true;setupMockSelectors({diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex eee37a9c5a0..ea9a0557ee3 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -35,7 +35,7 @@ import {resolveAgentWorkingDirectory,resolveAgentWorkingDirectoryConfig,} from '@/helpers/agentWorkingDirectory';-import { resolveExecutionTarget } from '@/helpers/executionTarget';+import { resolveExecutionTarget, resolveWorkspaceScoped } from '@/helpers/executionTarget';import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';import { agentService } from '@/services/agent';import { aiChatService } from '@/services/aiChat';@@ -277,14 +277,24 @@ export class ConversationLifecycleActionImpl {if (!agentId) return;- const agentConfig = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());- const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;+ const agentState = getAgentStoreState();+ const agentConfig = agentSelectors.getAgentConfigById(agentId)(agentState);+ const isWorkspaceAgent = agentByIdSelectors.isWorkspaceAgentById(agentId)(agentState);+ const deviceOverride = isWorkspaceAgent+ ? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]+ : undefined;+ const workspaceScoped = resolveWorkspaceScoped(isWorkspaceAgent, deviceOverride);+ // Runtime selection must use the same per-user device override as the+ // switcher. A workspace-local pick is intentionally private to this member+ // and is therefore safe to execute in-process on their desktop.+ const agencyConfig = resolveAgencyConfig(agentConfig?.agencyConfig, deviceOverride);+ const heterogeneousProvider = agencyConfig?.heterogeneousProvider;const runtimeType = selectRuntimeType({- boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,- executionTarget: agentConfig?.agencyConfig?.executionTarget,+ boundDeviceId: agencyConfig?.boundDeviceId,+ executionTarget: agencyConfig?.executionTarget,heterogeneousProvider,isGatewayMode: this.#get().isGatewayModeEnabled(agentId),- isWorkspaceAgent: agentByIdSelectors.isWorkspaceAgentById(agentId)(getAgentStoreState()),+ isWorkspaceAgent: workspaceScoped,// Callers that need to pin the runtime (e.g. task topics that were// started server-side via runTask) pass `forceRuntime` to override// the agent's local/cloud preference.@@ -588,16 +598,6 @@ export class ConversationLifecycleActionImpl {? topicSelectors.getTopicById(operationContext.topicId)(this.#get()): undefined;const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;- const agentState = getAgentStoreState();- // 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@@ -609,7 +609,7 @@ export class ConversationLifecycleActionImpl {? resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: isDesktop,isHetero: true,- workspaceScoped: isWorkspaceAgentForCwd,+ workspaceScoped,}): undefined;const resolvesHeteroCwd =@@ -629,6 +629,7 @@ export class ConversationLifecycleActionImpl {currentDeviceId,fallback: heteroCwdContext?.desktopPath ?? heteroCwdContext?.homePath,legacyAgentWorkingDirectory: agentState.localAgentWorkingDirectoryMap[agentId],+ workspaceScoped,}: undefined;const agentWorkingDirectory = heteroCwdParams