🤯 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
⏪️ revert(chat): remove topic execution isolation (#19596)
Tsukif8cba5f95e6b
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 49ca5606ab8..407009c57ee 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -497,8 +497,8 @@ export const topicRouter = router({favorite: z.boolean().optional(),groupId: z.string().nullish(),messages: z.array(z.string()).optional(),- // Execution routing and reasoning snapshots belong to this Topic;- // other metadata keys are server-owned.+ // The pinned reasoning snapshot taken next to the pinned model+ // (`snapshotAgentReasoning`); other metadata keys are server-owned.metadata: chatTopicCreateMetadataSchema.optional(),// The topic's pinned model snapshot, persisted to the top-level// `topics.model`/`provider` columns (config source of truth).diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.tsindex 391c7651c0d..a48d367df02 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts@@ -573,16 +573,7 @@ describe('AiAgentService.execAgent - device auto-activation', () => {expect(mockCreateOperation.mock.calls[0][0].activeDeviceId).toBeUndefined();expect(topicMock.create).toHaveBeenCalledWith(- expect.objectContaining({- metadata: {- boundDeviceId: undefined,- executionConfig: {- boundDeviceId: undefined,- executionTarget: 'sandbox',- inheritWorkspaceScope: true,- },- },- }),+ expect.objectContaining({ metadata: undefined }),undefined,);});diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.tsindex 3e4641c27f9..f81ac675d67 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts@@ -1,4 +1,3 @@-import type { ChatTopicMetadata } from '@lobechat/types';import type * as ModelBankModule from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -113,7 +112,6 @@ vi.mock('@/database/models/topic', () => ({create: mockTopicCreate,armScheduledRun: vi.fn().mockResolvedValue(undefined),findById: mockTopicFindById,- updateMetadata: vi.fn(async (_id: string, metadata: ChatTopicMetadata) => [{ metadata }]),};}),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.tsindex a964875f970..6febaa91891 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.ts@@ -203,24 +203,6 @@ describe('AiAgentService.execAgent - topic history loading', () => {mockTopicFindById.mockClear();});- it('keeps a continued topic on its snapshotted execution target', async () => {- mockTopicFindById.mockResolvedValue({- id: 'topic-existing',- metadata: { executionConfig: { executionTarget: 'none' } },- });- mockMessageQuery.mockResolvedValue([]);- await service.execAgent({- agentId: 'agent-1',- appContext: { topicId: 'topic-existing' },- prompt: 'Continue',- deviceId: 'another-desktop',- });- expect(mockCreateOperation).toHaveBeenCalled();- expect(mockCreateOperation.mock.calls[0][0].agentConfig.agencyConfig).toMatchObject({- executionTarget: 'none',- });- });-describe('when topicId is provided (follow-up message in existing thread)', () => {it('should load history messages from the topic and include them in initialMessages', async () => {// Simulate existing conversation history in the topicdiff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 0c681b21fd6..d5893be1a51 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1074,7 +1074,7 @@ export class AiAgentService {parentOperationId,pinnedHeterogeneousTopicModel: turn.pinnedHeterogeneousTopicModel,requestTrigger: requestTriggerMetadata.trigger,- requestedDeviceId: turn.effectiveRequestedDeviceId,+ requestedDeviceId,runAttachments,selfMessageIds,topicStartOwnerOperationId: params.topicStartOwnerOperationId,@@ -1197,7 +1197,7 @@ export class AiAgentService {loadHistoryMessages,localDeviceId,requestTrigger: requestTriggerMetadata.trigger,- requestedDeviceId: turn.effectiveRequestedDeviceId,+ requestedDeviceId,selectedToolIds,throwIfExecutionAborted,topicBoundDeviceId: turn.topicBoundDeviceId,diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex 955f37b8c91..34f9e2019e1 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -10,11 +10,9 @@ import type {HeterogeneousTopicPin,} from '@lobechat/types';import {- applyTopicExecutionConfig,ChatErrorType,RequestTrigger,resolveHeterogeneousProviderTopicModel,- snapshotTopicExecutionConfig,} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -426,8 +424,10 @@ export const setupTurn = async (!!deps.workspaceId && agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed';const isFixedDeviceTarget =isFixedExecutionTargetSelection && agentConfig.agencyConfig?.executionTarget === 'device';- let effectiveRequestedDeviceId = isFixedExecutionTargetSelection ? undefined : requestedDeviceId;- let topicBoundDeviceId = isFixedDeviceTarget+ const effectiveRequestedDeviceId = isFixedExecutionTargetSelection+ ? undefined+ : requestedDeviceId;+ const topicBoundDeviceId = isFixedDeviceTarget? agentConfig.agencyConfig?.boundDeviceId: isFixedExecutionTargetSelection? undefined@@ -472,25 +472,30 @@ export const setupTurn = async (// never be attributed afterwards, which is why it is stamped even though// nothing filters on it yet.const { editingAgentId, editingGroupId } = appContext ?? {};- const metadata = {- bot: botContext,- executionConfig: snapshotTopicExecutionConfig({- ...agentConfig.agencyConfig,- ...(effectiveRequestedDeviceId && { boundDeviceId: effectiveRequestedDeviceId }),- }),- boundDeviceId: topicBoundDeviceId,- cronJobId: cronJobId || undefined,- ...(editingAgentId && { editingAgentId }),- ...(editingGroupId && { editingGroupId }),- taskId: operationTaskId,- ...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),- ...(initialTopicMeta?.workingDirectory && {- workingDirectory: initialTopicMeta.workingDirectory,- }),- ...(initialTopicMeta?.workingDirectoryConfig && {- workingDirectoryConfig: initialTopicMeta.workingDirectoryConfig,- }),- };+ const metadata =+ cronJobId ||+ operationTaskId ||+ botContext ||+ topicBoundDeviceId ||+ initialTopicMeta ||+ editingGroupId ||+ editingAgentId+ ? {+ bot: botContext,+ boundDeviceId: topicBoundDeviceId,+ cronJobId: cronJobId || undefined,+ ...(editingAgentId && { editingAgentId }),+ ...(editingGroupId && { editingGroupId }),+ taskId: operationTaskId,+ ...(initialTopicMeta?.repos && { repos: initialTopicMeta.repos }),+ ...(initialTopicMeta?.workingDirectory && {+ workingDirectory: initialTopicMeta.workingDirectory,+ }),+ ...(initialTopicMeta?.workingDirectoryConfig && {+ workingDirectoryConfig: initialTopicMeta.workingDirectoryConfig,+ }),+ }+ : undefined;const fallbackTitleSource = markdownToTxt(prompt);const snapshot = await resolveNewTopicSnapshot(deps, agentConfig);@@ -576,33 +581,6 @@ export const setupTurn = async (throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });}- if (existingTopic && !shareGate) {- let executionConfig = existingTopic.metadata?.executionConfig;- if (!executionConfig) {- const fallback = snapshotTopicExecutionConfig({- ...agentConfig.agencyConfig,- ...(effectiveRequestedDeviceId && { boundDeviceId: effectiveRequestedDeviceId }),- });- const rows = await deps.topicModel.updateMetadata(- topicId,- { executionConfig: fallback },- {- executionConfigIfAbsent: true,- },- );- executionConfig = rows?.[0]?.metadata?.executionConfig ?? fallback;- }- agentConfig.agencyConfig = applyTopicExecutionConfig(- agentConfig.agencyConfig,- executionConfig,- );- // A client hint cannot redirect a conversation pinned by another surface.- effectiveRequestedDeviceId = isFixedExecutionTargetSelection- ? undefined- : agentConfig.agencyConfig?.boundDeviceId;- topicBoundDeviceId = agentConfig.agencyConfig?.boundDeviceId;- }-/** A group topic pins its owning agent; member runs keep their own model and effort. */const canUseTopicPin = !existingTopic?.groupId || existingTopic.agentId === resolvedAgentId;const pinnedModel = canUseTopicPin ? existingTopic?.model : undefined;diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex a3e8f7ba763..bd43a104930 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -1138,24 +1138,6 @@ describe('TopicModel', () => {});describe('updateMetadata', () => {- it('does not overwrite a user selection when initializing a legacy topic', async () => {- const topic = await topicModel.create({ title: 'execution' });- await topicModel.updateMetadata(topic.id, {- executionConfig: { executionTarget: 'device', boundDeviceId: 'chosen' },- });- const [updated] = await topicModel.updateMetadata(- topic.id,- {- executionConfig: { executionTarget: 'sandbox' },- },- { executionConfigIfAbsent: true },- );- expect(updated.metadata?.executionConfig).toEqual({- executionTarget: 'device',- boundDeviceId: 'chosen',- });- });-it('merges new metadata into existing metadata', async () => {const topic = await topicModel.create({metadata: { model: 'gpt-4', provider: 'openai' },diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 85f24f08a0d..74fe0047a78 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1930,11 +1930,7 @@ export class TopicModel {* Update topic metadata with merge logic* This method merges new metadata with existing metadata instead of replacing it*/- updateMetadata = async (- id: string,- metadata: TopicMetadataPatch,- options?: { executionConfigIfAbsent?: boolean },- ) => {+ updateMetadata = async (id: string, metadata: TopicMetadataPatch) => {// Merge into the existing metadata under a row lock so concurrent writers// can't lose each other's keys. The old read-then-write was a non-atomic// read-modify-write: a hetero run seeds `metadata.runningOperation` while@@ -1966,9 +1962,6 @@ export class TopicModel {const mergedMetadata = {...existing.metadata,...metadata,- ...(options?.executionConfigIfAbsent && existing.metadata?.executionConfig- ? { executionConfig: existing.metadata.executionConfig }- : {}),...(mergedOnboardingSession && { onboardingSession: mergedOnboardingSession }),} as ChatTopicMetadata;diff --git a/packages/types/src/topic/topic.test.ts b/packages/types/src/topic/topic.test.tsindex af8899aa0aa..153cc6d7f69 100644--- a/packages/types/src/topic/topic.test.ts+++ b/packages/types/src/topic/topic.test.ts@@ -173,15 +173,3 @@ describe('parseTopicScheduledRun', () => {expect(parseTopicScheduledRun(null)).toBeNull();});});--it('preserves execution selection alongside reasoning when creating a topic', () => {- const metadata = {- executionConfig: {- executionTarget: 'device',- boundDeviceId: 'selected-device',- inheritWorkspaceScope: false,- },- reasoningConfig: { gpt5ReasoningEffort: 'high' },- };- expect(chatTopicCreateMetadataSchema.parse(metadata)).toEqual(metadata);-});diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 49f02f653a1..6169345a9d2 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -2,7 +2,6 @@ import type { AiModelReasoningConfig } from 'model-bank';import { AiModelReasoningConfigSchema } from 'model-bank/aiModel';import { z } from 'zod';-import type { LobeAgentAgencyConfig } from '../agent';import type { HeterogeneousReasoningEffort } from '../agent/heteroSelectorCapabilities';import type { SerializedAgentHook } from '../agentHook';import { serializedAgentHookSchema } from '../agentHook';@@ -114,43 +113,6 @@ export interface OnboardingSessionSnapshot {version: number;}-/** Execution routing belongs to a conversation; Agent config supplies defaults only. */-export const topicExecutionConfigSchema = z.object({- /** Automatic snapshots retain the workspace default's execution restrictions. */- inheritWorkspaceScope: z.boolean().optional(),- boundDeviceId: z.string().optional(),- executionTarget: z.enum(['auto', 'device', 'local', 'none', 'sandbox']).optional(),- localSandbox: z.boolean().optional(),- localSandboxNetwork: z.boolean().optional(),-});--export type TopicExecutionConfig = z.infer<typeof topicExecutionConfigSchema>;--/** Replace routing as a unit so an absent device never inherits an Agent's device. */-export const applyTopicExecutionConfig = (- defaults: LobeAgentAgencyConfig | undefined,- execution: TopicExecutionConfig | null | undefined,-): LobeAgentAgencyConfig | undefined => {- if (!execution || defaults?.executionTargetSelectionPolicy === 'fixed') return defaults;- return {- ...defaults,- boundDeviceId: execution.boundDeviceId,- executionTarget: execution.executionTarget,- localSandbox: execution.localSandbox,- localSandboxNetwork: execution.localSandboxNetwork,- };-};--export const snapshotTopicExecutionConfig = (- config: LobeAgentAgencyConfig | undefined,-): TopicExecutionConfig => ({- inheritWorkspaceScope: true,- boundDeviceId: config?.boundDeviceId,- executionTarget: config?.executionTarget,- localSandbox: config?.localSandbox,- localSandboxNetwork: config?.localSandboxNetwork,-});-export interface ChatTopicMetadata {/** Watermark written by the background topic-summary workflow. */autoSummary?: {@@ -186,7 +148,6 @@ export interface ChatTopicMetadata {editingGroupId?: string;/** Restored-history tail used as the source message for eval attempt threads. */evalHistoryTailMessageId?: string;- executionConfig?: TopicExecutionConfig;/*** Scoped pointer to the currently active assistant message for a running* heterogeneous agent operation. Includes `operationId` so cold-start@@ -535,7 +496,6 @@ export const parseTopicScheduledRun = (raw: unknown): TopicScheduledRun | null =};export const chatTopicMetadataUpdateSchema = z.object({- executionConfig: topicExecutionConfigSchema.optional(),boundDeviceId: z.string().optional(),heteroEffort: z.custom<HeterogeneousReasoningEffort>((value) => typeof value === 'string')@@ -625,11 +585,10 @@ export const chatTopicMetadataUpdateSchema = z.object({});/**- * Metadata a client may seed when creating a topic: execution routing and the- * reasoning snapshot taken alongside the pinned model (see `snapshotAgentModel`).+ * Metadata a client may seed when creating a topic: the pinned reasoning+ * snapshot taken alongside the pinned model (see `snapshotAgentModel`).*/export const chatTopicCreateMetadataSchema = chatTopicMetadataUpdateSchema.pick({- executionConfig: true,heteroEffort: true,reasoningConfig: true,});diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsxindex 828e176076f..ab6837fa70e 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx@@ -69,8 +69,8 @@ vi.mock('@/features/ChatInput/hooks/useChatInputResourceAccess', () => ({}),}));-vi.mock('@/hooks/useTopicAgencyConfig', () => ({- useTopicAgencyConfig: () => ({+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => ({agencyConfig: effectiveAgencyConfig.current,workspaceScoped: effectiveAgencyConfig.workspaceScoped,}),diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsxindex 2b3dad41856..eeca16cb760 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx@@ -19,7 +19,7 @@ import WorkspaceControls from '@/features/ChatInput/ControlBar/WorkspaceControlsimport { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';import { resolveExecutionTarget } from '@/helpers/executionTarget';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';@@ -142,7 +142,7 @@ const HeteroControlBar = memo(() => {const isLoading = useAgentStore(agentByIdSelectors.isAgentConfigLoadingById(agentId));// Effective config = shared row + this member's device override,// so the quota badges gate on where THIS member's run actually executes.- const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);const heteroProvider = agencyConfig?.heterogeneousProvider;const executionTarget = resolveExecutionTarget(agencyConfig, {diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex f3db036bbbb..0a854380d2e 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -37,8 +37,8 @@ import {resolveExecutionTarget,} from '@/helpers/executionTarget';import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';import { localFileService } from '@/services/electron/localFileService';import { useAgentStore } from '@/store/agent';import { useElectronStore } from '@/store/electron';@@ -388,7 +388,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {canSelectExecutionTarget,isPreferenceLoading: isWorkspacePreferenceLoading,workspaceScoped,- } = useTopicAgencyConfig(agentId);+ } = useEffectiveAgencyConfig(agentId);const canShowExecutionTarget = canUseResource && canDisplayExecutionTarget;const canShowExecutionTargetSelector = canShowExecutionTarget && canSelectExecutionTarget;diff --git a/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsxindex 60b0ab5ca0b..0725ffeeb73 100644--- a/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx+++ b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx@@ -41,8 +41,8 @@ import { useTranslation } from 'react-i18next';import { isDesktop } from '@/const/version';import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';import { resolveExecutionTarget } from '@/helpers/executionTarget';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';import { useDeviceStore } from '@/store/device';import { useElectronStore } from '@/store/electron';import { useUserStore } from '@/store/user';@@ -171,7 +171,8 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(handleOpenChangeComplete: completeOpenChange,open,} = useMenuContentLifecycle(onSelect);- const { agencyConfig, isPreferenceLoading, workspaceScoped } = useTopicAgencyConfig(agentId);+ const { agencyConfig, isPreferenceLoading, workspaceScoped } =+ useEffectiveAgencyConfig(agentId);const isLogin = useUserStore(authSelectors.isLogin);const { isLoading: isDeviceListLoading } = useDeviceStore((s) => s.useFetchDevices)(isLogin || isDesktop,diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsxindex 6b49ee4f3bb..e01dc22e628 100644--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx@@ -29,7 +29,7 @@ import {getWorkingDirectoryName,getWorkingDirectoryPathString,} from '@/helpers/workingDirectoryPath';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { deviceService } from '@/services/device';import { electronSystemService } from '@/services/electron/system';import { useAgentStore } from '@/store/agent';@@ -304,7 +304,7 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =// Effective config (shared row + this member's device override)// so recents / default cwd / the selected-repo label all resolve against the// device THIS member's run actually targets.- const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {workspaceScoped,diff --git a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsxindex cbcc2907790..0b3f52b345f 100644--- a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx+++ b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx@@ -8,8 +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 { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';import { deviceSelectors, useDeviceStore } from '@/store/device';@@ -38,7 +38,7 @@ const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agent// Effective config (shared row + this member's device override)// so GitStatus probes the same device `useEffectiveWorkingDirectory` resolved// the cwd from — raw shared config could point them at different machines.- const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {workspaceScoped,diff --git a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsxindex 37f275d6596..942b949b782 100644--- a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx@@ -19,8 +19,8 @@ const testState = vi.hoisted(() => ({},}));-vi.mock('@/hooks/useTopicAgencyConfig', () => ({- useTopicAgencyConfig: () => testState.effective,+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => testState.effective,}));vi.mock('@/store/agent', () => ({diff --git a/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.ts b/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.tsindex b8970811707..20d8e8db923 100644--- a/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.ts+++ b/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.ts@@ -11,7 +11,7 @@ import { useAgentStore } from '@/store/agent';import { resolveWorkspaceSurface, useWorkspaceSurface } from '../useWorkspaceSurface';// The EFFECTIVE config (shared row + this member's per-user device override),-// as `useTopicAgencyConfig` would resolve it. The raw shared row lives in+// as `useEffectiveAgencyConfig` would resolve it. The raw shared row lives in// the real agent store so store-derived selectors see what they see in prod.const effective = vi.hoisted(() => ({agencyConfig: undefined as LobeAgentAgencyConfig | undefined,@@ -28,8 +28,8 @@ vi.mock('@/helpers/gatewayMode', () => ({useIsGatewayModeEnabled: () => true,}));-vi.mock('@/hooks/useTopicAgencyConfig', () => ({- useTopicAgencyConfig: () => ({+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => ({agencyConfig: effective.agencyConfig,workspaceScoped: effective.workspaceScoped,}),diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.tsindex e7e45ac8907..99b5499d7f1 100644--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts@@ -12,7 +12,7 @@ import type { PartialDeep } from 'type-fest';import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';import { getHeteroSessionIdForWorkingDirectory } from '@/helpers/heteroSessionByWorkingDirectory';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -91,7 +91,8 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string// The EFFECTIVE config (override merged) — 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, workspaceScoped } = useTopicAgencyConfig(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 thediff --git a/src/features/ChatInput/ControlBar/useWorkspaceSurface.ts b/src/features/ChatInput/ControlBar/useWorkspaceSurface.tsindex b813f079881..4aedf77f635 100644--- a/src/features/ChatInput/ControlBar/useWorkspaceSurface.ts+++ b/src/features/ChatInput/ControlBar/useWorkspaceSurface.ts@@ -3,7 +3,7 @@ import type { LobeAgentAgencyConfig } from '@lobechat/types';import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';@@ -76,7 +76,7 @@ export const useWorkspaceSurface = (alwaysShowWorkspace = false,): WorkspaceSurface => {const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));- const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);return resolveWorkspaceSurface({diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.tsindex 74f335629df..65bc1bcf59b 100644--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts@@ -1,132 +1,640 @@+import { toast } from '@lobehub/ui/base-ui';import { renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import { useSelectExecutionTarget } from './useSelectExecutionTarget';-const state = vi.hoisted(() => ({- config: {- agencyConfig: { executionTarget: 'local', boundDeviceId: 'device-a' },- canSelectExecutionTarget: true,+const testState = vi.hoisted(() => ({+ access: {+ canManageAgent: true,+ isAccessLoading: false,},- chat: {- activeAgentId: 'agent',- activeTopicId: 'topic-a' as string | undefined,- createTopic: vi.fn(),- updateTopicMetadata: vi.fn(),- switchTopic: vi.fn(),+ agent: {+ agencyConfig: undefined as+ | {+ boundDeviceId?: string;+ executionTargetSelectionPolicy?: 'fixed' | 'member';+ executionTarget?: string;+ heterogeneousProvider?: { type: string };+ localSandbox?: boolean;+ }+ | undefined,+ agentMap: {} as Record<+ string,+ { visibility?: 'private' | 'public'; workspaceId?: string | null }+ >,+ isHetero: false,+ updateAgentConfigById: vi.fn(),+ },+ electron: {+ gatewayDeviceInfo: undefined as { deviceId?: string } | undefined,+ },+ getDeviceInfo: vi.fn(),+ isDesktop: false,+ user: {+ updateWorkspaceUserPreference: vi.fn(),+ workspaceUserPreference: {} as {+ agentDeviceOverrides?: Record<+ string,+ { boundDeviceId?: string; executionTarget?: string; localSandbox?: boolean }+ >;+ },},- desktop: true,- deviceInfo: vi.fn(),- toast: vi.fn(),}));+vi.mock('@lobechat/const', () => ({get isDesktop() {- return state.desktop;+ return testState.isDesktop;},}));-vi.mock('@lobehub/ui/base-ui', () => ({ toast: { error: state.toast } }));-vi.mock('i18next', () => ({ t: (key: string) => key }));-vi.mock('@/hooks/useTopicAgencyConfig', () => ({ useTopicAgencyConfig: () => state.config }));-vi.mock('@/store/chat', () => ({- useChatStore: Object.assign(- (selector: (s: typeof state.chat) => unknown) => selector(state.chat),- { getState: () => state.chat },- ),++vi.mock('@lobehub/ui/base-ui', () => ({+ toast: { error: vi.fn() },}));-vi.mock('@/store/electron', () => ({- useElectronStore: (selector: (s: object) => unknown) =>- selector({ gatewayDeviceInfo: undefined }),++vi.mock('i18next', () => ({+ t: (key: string) => key,}));+vi.mock('@/services/electron/gatewayConnection', () => ({- gatewayConnectionService: { getDeviceInfo: state.deviceInfo },+ gatewayConnectionService: {+ getDeviceInfo: () => testState.getDeviceInfo(),+ },}));-describe('Topic execution selection', () => {+vi.mock('@/features/ResourcePermission/useAgentManagementAccess', () => ({+ useAgentManagementAccess: () => testState.access,+}));++vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (s: typeof testState.agent) => unknown) => selector(testState.agent),+}));++vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ getAgencyConfigById: () => (s: typeof testState.agent) => s.agencyConfig,+ isAgentHeterogeneousById: () => (s: typeof testState.agent) => s.isHetero,+ },+}));++vi.mock('@/store/electron', () => ({+ useElectronStore: (selector: (s: typeof testState.electron) => unknown) =>+ selector(testState.electron),+}));++vi.mock('@/store/user', () => ({+ useUserStore: (selector: (s: typeof testState.user) => unknown) => selector(testState.user),+}));++describe('useSelectExecutionTarget', () => {beforeEach(() => {- vi.clearAllMocks();- state.chat.activeTopicId = 'topic-a';- state.chat.activeAgentId = 'agent';- state.config.canSelectExecutionTarget = true;- state.chat.createTopic.mockResolvedValue('new-topic');- state.chat.updateTopicMetadata.mockResolvedValue(undefined);+ testState.access.canManageAgent = true;+ testState.access.isAccessLoading = false;+ testState.agent.agencyConfig = undefined;+ testState.agent.agentMap = {};+ testState.agent.isHetero = false;+ testState.agent.updateAgentConfigById = vi.fn();+ testState.electron.gatewayDeviceInfo = undefined;+ testState.getDeviceInfo = vi.fn();+ testState.isDesktop = false;+ testState.user.workspaceUserPreference = {};+ testState.user.updateWorkspaceUserPreference = vi.fn();});- it('saves only the selected Topic and clears its device for sandbox', async () => {- const { result } = renderHook(() => useSelectExecutionTarget('agent'));- await result.current('sandbox');- expect(state.chat.updateTopicMetadata).toHaveBeenCalledWith('topic-a', {- executionConfig: {- executionTarget: 'sandbox',- inheritWorkspaceScope: false,- boundDeviceId: undefined,- localSandbox: undefined,- localSandboxNetwork: undefined,- },- });- expect(state.config.agencyConfig).toEqual({- executionTarget: 'local',- boundDeviceId: 'device-a',++ describe('personal agent — writes to the shared agencyConfig', () => {+ it('persists the target as-is when switching to sandbox, keeping any existing boundDeviceId', async () => {+ testState.agent.agencyConfig = { boundDeviceId: 'device-1', executionTarget: 'local' };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: { boundDeviceId: 'device-1', executionTarget: 'sandbox' },+ },+ { rethrow: true },+ );+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();+ });++ it('pins the given deviceId when switching to a specific device', async () => {+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('device', 'device-2');++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: { boundDeviceId: 'device-2', executionTarget: 'device' },+ },+ { rethrow: true },+ );+ });++ it("stores 'local' verbatim (not pre-resolved to 'device') to preserve the in-process IPC path", async () => {+ testState.isDesktop = true;+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local');++ expect(testState.getDeviceInfo).not.toHaveBeenCalled();+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' },+ },+ { rethrow: true },+ );+ });++ it('falls back to the gateway connection service when no gateway deviceId is cached yet', async () => {+ testState.isDesktop = true;+ testState.getDeviceInfo.mockResolvedValue({ deviceId: 'resolved-device' });+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local');++ expect(testState.getDeviceInfo).toHaveBeenCalled();+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: { boundDeviceId: 'resolved-device', executionTarget: 'local' },+ },+ { rethrow: true },+ );+ });++ it('keeps the previous boundDeviceId when the local device cannot be resolved for a non-hetero agent', async () => {+ testState.agent.agencyConfig = { boundDeviceId: 'stale-device', executionTarget: 'sandbox' };+ testState.getDeviceInfo.mockRejectedValue(new Error('no gateway'));+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local');++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: { boundDeviceId: 'stale-device', executionTarget: 'local' },+ },+ { rethrow: true },+ );+ });++ // automatic corrections must not trigger phantom save-error toasts: the device switcher defaults an unset target to `local` on+ // mount. In a workspace that write can be rejected (edit lock / resource+ // access), and the generic failure toast then claims the user's change was+ // not applied — on an agent they only opened, having changed nothing.+ it('suppresses the failure toast when the target is being defaulted automatically', async () => {+ testState.isDesktop = true;+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local', undefined, { silent: true });++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ { agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' } },+ { rethrow: true, showErrorMessage: false },+ );+ });++ it("keeps the failure toast for a user's own pick", async () => {+ testState.isDesktop = true;+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local');++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' },+ },+ { rethrow: true },+ );+ });++ it('records the sandbox choice alongside a local pick', async () => {+ testState.isDesktop = true;+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local', undefined, { localSandbox: true });++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: {+ boundDeviceId: 'this-machine',+ executionTarget: 'local',+ localSandbox: true,+ },+ },+ { rethrow: true },+ );+ });++ it('clears the sandbox when the plain local row is picked', async () => {+ // Switching back has to be an explicit `false`, not an omission — a+ // leftover `true` would keep fencing a run the user just un-fenced.+ testState.isDesktop = true;+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };+ testState.agent.agencyConfig = { executionTarget: 'local', localSandbox: true };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local', undefined, { localSandbox: false });++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: {+ boundDeviceId: 'this-machine',+ executionTarget: 'local',+ localSandbox: false,+ },+ },+ { rethrow: true },+ );+ });++ it('leaves the stored sandbox choice dormant when switching to another environment', async () => {+ // Cloud Sandbox has no opinion about how the user's own machine is+ // fenced, so flipping away and back must not silently forget it.+ testState.agent.agencyConfig = { executionTarget: 'local', localSandbox: true };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: { executionTarget: 'sandbox', localSandbox: true },+ },+ { rethrow: true },+ );+ });++ it('does not switch a heterogeneous agent to local when no device can be resolved', async () => {+ testState.agent.isHetero = true;+ testState.getDeviceInfo.mockRejectedValue(new Error('no gateway'));+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local');++ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();});});- it('does not write B when device discovery finishes after switching away from A', async () => {- let resolve!: (value: { deviceId: string }) => void;- state.deviceInfo.mockReturnValue(- new Promise((r) => {- resolve = r;- }),- );- const { result } = renderHook(() => useSelectExecutionTarget('agent'));- const selection = result.current('local');- state.chat.activeTopicId = 'topic-b';- resolve({ deviceId: 'device-a' });- await selection;- expect(state.chat.updateTopicMetadata).toHaveBeenCalledWith(- 'topic-a',- expect.objectContaining({- executionConfig: expect.objectContaining({ boundDeviceId: 'device-a' }),- }),- );- });- it('creates a Topic for an explicit choice in the empty composer', async () => {- state.chat.activeTopicId = undefined;- const { result } = renderHook(() => useSelectExecutionTarget('agent'));- await result.current('none');- expect(state.chat.updateTopicMetadata).toHaveBeenCalledWith('new-topic', expect.anything());- expect(state.chat.switchTopic).toHaveBeenCalledWith('new-topic');- });- it('does not create a Topic for automatic defaults or bypass fixed policy', async () => {- state.chat.activeTopicId = undefined;- const { result } = renderHook(() => useSelectExecutionTarget('agent'));- await result.current('local', undefined, { silent: true });- state.config.canSelectExecutionTarget = false;- const fixed = renderHook(() => useSelectExecutionTarget('agent'));- await fixed.result.current('sandbox');- expect(state.chat.createTopic).not.toHaveBeenCalled();- expect(state.chat.updateTopicMetadata).not.toHaveBeenCalled();++ describe('workspace agent — writes to workspace_user_settings.preference.agentDeviceOverrides ', () => {+ beforeEach(() => {+ testState.access.canManageAgent = false;+ testState.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },+ };+ });++ it('routes a workspace device pick into the workspace-scoped caller preference, never the shared config', async () => {+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('device', 'ws-device-1');++ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: {+ 'agent-id': { boundDeviceId: 'ws-device-1', executionTarget: 'device' },+ },+ });+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });++ it('reports an explicit workspace preference save failure without leaking a rejection', async () => {+ testState.user.updateWorkspaceUserPreference = vi+ .fn()+ .mockRejectedValue(new Error('save failed'));+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await expect(result.current('sandbox')).resolves.toBeUndefined();++ expect(toast.error).toHaveBeenCalledWith('saveAgentConfigFail');+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });++ it('keeps an automatic workspace preference save failure silent', async () => {+ testState.user.updateWorkspaceUserPreference = vi+ .fn()+ .mockRejectedValue(new Error('save failed'));+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await expect(result.current('sandbox', undefined, { silent: true })).resolves.toBeUndefined();++ expect(toast.error).not.toHaveBeenCalled();+ });++ it('does not write a member override while the shared execution target is fixed', async () => {+ testState.agent.agencyConfig = {+ boundDeviceId: 'fixed-device',+ executionTargetSelectionPolicy: 'fixed',+ executionTarget: 'device',+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('device', 'another-device');++ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });++ it("accepts 'local' for a workspace agent and stores it in the workspace-scoped preference", async () => {+ testState.isDesktop = true;+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local');++ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: {+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },+ },+ });+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });++ it('preserves other agents overrides in the same workspace when writing this one', async () => {+ testState.user.workspaceUserPreference = {+ agentDeviceOverrides: {+ 'other-agent': { boundDeviceId: 'other-device', executionTarget: 'device' },+ },+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: {+ 'other-agent': { boundDeviceId: 'other-device', executionTarget: 'device' },+ 'agent-id': { executionTarget: 'sandbox' },+ },+ });+ });++ it("keeps a member's own sandbox choice in their override when they switch environment", async () => {+ // One member fencing their own machine is theirs alone — it must live in+ // the per-user override and survive a target switch, never reach the+ // shared row where it would apply to everyone.+ testState.user.workspaceUserPreference = {+ agentDeviceOverrides: {+ 'agent-id': {+ boundDeviceId: 'this-machine',+ executionTarget: 'local',+ localSandbox: true,+ },+ },+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: {+ 'agent-id': {+ boundDeviceId: 'this-machine',+ executionTarget: 'sandbox',+ localSandbox: true,+ },+ },+ });+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });++ it('drops boundDeviceId when it cannot be resolved (e.g. web caller picks local)', async () => {+ testState.isDesktop = false;+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: { 'agent-id': { executionTarget: 'sandbox' } },+ });+ });++ it('lets the author or Workspace admin update the shared target while members are fixed', async () => {+ testState.access.canManageAgent = true;+ testState.agent.agencyConfig = {+ boundDeviceId: 'fixed-device',+ executionTargetSelectionPolicy: 'fixed',+ executionTarget: 'device',+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: {+ boundDeviceId: 'fixed-device',+ executionTarget: 'sandbox',+ executionTargetSelectionPolicy: 'fixed',+ },+ },+ { rethrow: true },+ );+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();+ });});- it('surfaces a failed save without navigating to another topic', async () => {- state.chat.updateTopicMetadata.mockRejectedValue(new Error('network'));- const { result } = renderHook(() => useSelectExecutionTarget('agent'));- await result.current('sandbox');- expect(state.toast).toHaveBeenCalled();- expect(state.chat.switchTopic).not.toHaveBeenCalled();++ describe("workspace agent — a manager's or owner's `local` pick stays per-user", () => {+ // The regression behind "用户在 Workspace 中无法切换个人的本地设备": a `local`+ // pick binds this member's PERSONAL desktop device, which the shared row+ // must never reference — the server rejects it with+ // `WorkspaceAgentRequiresWorkspaceDevice` and the picker surfaces+ // "Failed to save agent settings". So even callers who manage the shared+ // config route `local` into their per-user override.+ it("routes a manager's 'local' pick into the per-user override, never the shared config", async () => {+ testState.access.canManageAgent = true;+ testState.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },+ };+ testState.isDesktop = true;+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local');++ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: {+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },+ },+ });+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });++ it("routes a private Workspace agent owner's 'local' pick into the per-user override", async () => {+ testState.agent.agentMap = {+ 'agent-id': { visibility: 'private', workspaceId: 'ws-1' },+ };+ testState.isDesktop = true;+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local');++ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: {+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },+ },+ });+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });++ it("clears the manager's own routing override when they pick a shared target", async () => {+ // Without this, the earlier `local` override would keep shadowing the+ // shared target the manager just wrote. The sandbox fence stays dormant —+ // it qualifies their machine, not this pick.+ testState.access.canManageAgent = true;+ testState.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },+ };+ testState.user.workspaceUserPreference = {+ agentDeviceOverrides: {+ 'agent-id': {+ boundDeviceId: 'this-machine',+ executionTarget: 'local',+ localSandbox: true,+ },+ },+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: { executionTarget: 'sandbox' },+ },+ { rethrow: true },+ );+ expect(testState.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: {+ 'agent-id': { localSandbox: true },+ },+ });+ });++ it('keeps the routing override intact when the shared save fails', async () => {+ // The store rolls the optimistic config back and toasts on failure; the+ // caller's previously valid `local` pick must survive it — clearing the+ // override for a save that never happened would silently reroute them to+ // the old shared target.+ testState.access.canManageAgent = true;+ testState.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },+ };+ testState.agent.updateAgentConfigById = vi.fn().mockRejectedValue(new Error('save failed'));+ testState.user.workspaceUserPreference = {+ agentDeviceOverrides: {+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },+ },+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledTimes(1);+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();+ });++ it('restores the shared config when clearing the override fails after a successful save', async () => {+ // The shared save persisted but the override clear rolled back — the old+ // `local` override would shadow the new shared target (split state), so+ // the hook compensates by writing the previous shared config back.+ testState.access.canManageAgent = true;+ testState.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },+ };+ testState.agent.agencyConfig = { executionTarget: 'device', boundDeviceId: 'ws-device' };+ testState.user.updateWorkspaceUserPreference = vi+ .fn()+ .mockRejectedValue(new Error('clear failed'));+ testState.user.workspaceUserPreference = {+ agentDeviceOverrides: {+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },+ },+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(testState.agent.updateAgentConfigById).toHaveBeenNthCalledWith(+ 1,+ 'agent-id',+ {+ agencyConfig: {+ boundDeviceId: 'ws-device',+ executionTarget: 'sandbox',+ },+ },+ { rethrow: true },+ );+ expect(testState.agent.updateAgentConfigById).toHaveBeenNthCalledWith(+ 2,+ 'agent-id',+ {+ agencyConfig: { boundDeviceId: 'ws-device', executionTarget: 'device' },+ },+ { showErrorMessage: false },+ );+ });++ it('leaves the preference untouched when a manager picks a shared target with no override', async () => {+ testState.access.canManageAgent = true;+ testState.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'ws-1' },+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: { executionTarget: 'sandbox' },+ },+ { rethrow: true },+ );+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();+ });});-});-it('does not reparent another Topic messages after leaving an empty composer', async () => {- state.chat.activeTopicId = undefined;- state.chat.activeAgentId = 'agent';- state.config.canSelectExecutionTarget = true;- state.chat.createTopic.mockClear();- let resolve!: (value: { deviceId: string }) => void;- state.deviceInfo.mockReturnValue(- new Promise((r) => {- resolve = r;- }),- );- const { result } = renderHook(() => useSelectExecutionTarget('agent'));- const selection = result.current('local');- state.chat.activeTopicId = 'topic-b';- resolve({ deviceId: 'device-a' });- await selection;- expect(state.chat.createTopic).not.toHaveBeenCalled();+ describe('private Workspace agent — writes to the owner-controlled shared config', () => {+ it('switches target directly even when the future public policy is fixed', async () => {+ testState.agent.agentMap = {+ 'agent-id': { visibility: 'private', workspaceId: 'ws-1' },+ };+ testState.agent.agencyConfig = {+ boundDeviceId: 'owner-device',+ executionTarget: 'device',+ executionTargetSelectionPolicy: 'fixed',+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ {+ agencyConfig: {+ boundDeviceId: 'owner-device',+ executionTarget: 'sandbox',+ executionTargetSelectionPolicy: 'fixed',+ },+ },+ { rethrow: true },+ );+ expect(testState.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();+ });+ });});diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.tsindex 22084b95c7f..a0e7b54a458 100644--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts@@ -1,69 +1,250 @@'use client';import { isDesktop } from '@lobechat/const';-import { type DeviceExecutionTarget, snapshotTopicExecutionConfig } from '@lobechat/types';+import type { DeviceExecutionTarget } from '@lobechat/types';import { toast } from '@lobehub/ui/base-ui';import { t } from 'i18next';+import { useCallback } from 'react';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';+import { useAgentManagementAccess } from '@/features/ResourcePermission/useAgentManagementAccess';import { gatewayConnectionService } from '@/services/electron/gatewayConnection';-import { useChatStore } from '@/store/chat';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';import { useElectronStore } from '@/store/electron';+import { useUserStore } from '@/store/user';export interface SelectExecutionTargetOptions {+ /**+ * Confine this agent's shell commands to the device sandbox. Only meaningful+ * alongside `target: 'local'`; the picker passes `false` for the plain local+ * row so switching back off is an explicit write rather than a leftover.+ *+ * Omitted entirely for the other targets, which leaves any stored value+ * dormant — flipping to Cloud Sandbox and back must not silently forget that+ * the user had fenced their machine.+ */localSandbox?: boolean;+ /**+ * Let sandboxed commands reach the package-registry allowlist. Same+ * omitted-means-untouched rule as {@link localSandbox}.+ */localSandboxNetwork?: boolean;+ /**+ * The call is an automatic default (agent has no target yet), not a user's+ * pick. Persistence failures stay silent — a generic "your change was not+ * applied" toast would be about a change the user never made.+ */silent?: boolean;}-/** Capture the destination before device discovery or persistence can yield. */+/**+ * Persist an execution-target selection for an agent. Shared by the device+ * switcher and the sandbox notice so the `local` device-id resolution (which+ * has to find this machine's gateway `deviceId`) lives in one place.+ *+ * `executionTarget` is the single source of truth — the server tool gate ++ * client `getRuntimeModeById` derive `runtimeMode` from it.+ *+ * Storage split:+ * - **Personal agent** — writes go straight into the shared+ * `agents.agencyConfig` (there's only ever one owner, so there's nothing to+ * isolate).+ * - **Public Workspace agent** — writes go into+ * `workspace_user_settings.preference.agentDeviceOverrides[agentId]`+ * (per-user per-workspace) so each member's Cloud Sandbox / workspace-device+ * / this-machine choice stays independent. The shared `agents.agencyConfig`+ * is left as-is, becoming the group-wide fallback for members who haven't+ * chosen anything yet. Reads / writes are cached through the+ * `workspaceUserSettings` slice of the user store, keyed on the active+ * workspaceId.+ * - **Private Workspace agent** — like a personal agent, writes go directly to+ * `agents.agencyConfig`; the member-selection policy takes effect only after+ * the Agent is published.+ * - **`local` on ANY workspace agent** — always the per-user override, even for+ * managers and private-agent owners who otherwise write the shared row: a+ * `local` pick binds this member's personal desktop device, and the server+ * rejects a workspace agent whose shared config references a device not+ * enrolled in the workspace (`WorkspaceAgentRequiresWorkspaceDevice`).+ * Conversely, a manager's shared-target pick clears their own override's+ * routing keys so a previous `local` pick cannot keep shadowing it.+ *+ * `local` is stored verbatim (`{ executionTarget: 'local', boundDeviceId: <me> }`)+ * so both desktop dispatch (in-process IPC — the fast path) and web dispatch+ * (server-side coercion to `device` via the existing gateway rule) keep their+ * respective semantics. That's why the old+ * `if (target === 'local' && isWorkspaceAgent) return;` guard is gone: with+ * per-user overrides my choice can't hurt other members.+ */export const useSelectExecutionTarget = (agentId: string) => {- const { agencyConfig, canSelectExecutionTarget } = useTopicAgencyConfig(agentId);- const topicId = useChatStore((s) => (s.activeAgentId === agentId ? s.activeTopicId : undefined));- const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);+ const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));+ const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));+ const isWorkspaceAgent = useAgentStore((s) => Boolean(s.agentMap[agentId]?.workspaceId));+ const isPublicWorkspaceAgent = useAgentStore((s) => {+ const agent = s.agentMap[agentId];+ return !!agent?.workspaceId && agent.visibility !== 'private';+ });+ const { canManageAgent, isAccessLoading } = useAgentManagementAccess(agentId);+ const usesWorkspaceMemberSelection = isPublicWorkspaceAgent && !canManageAgent;+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);- return async (- target: DeviceExecutionTarget,- deviceId?: string,- options?: SelectExecutionTargetOptions,- ) => {- if (!canSelectExecutionTarget) return;- // An automatic default must not create an empty conversation on mount.- if (options?.silent && !topicId) return;- try {- let boundDeviceId = target === 'device' ? deviceId : undefined;+ const updateWorkspaceUserPreference = useUserStore((s) => s.updateWorkspaceUserPreference);+ // Latest known bucket so the write below can splice a single agentId leaf+ // without stomping any of the caller's other agent overrides in this+ // workspace. Optimistic merge inside the action keeps this in sync.+ const workspaceUserPreference = useUserStore((s) => s.workspaceUserPreference);++ // The current machine's own gateway deviceId (desktop only); used to pin a+ // `local` selection to this device.+ const gatewayDeviceInfo = useElectronStore((s) => s.gatewayDeviceInfo);+ const currentDeviceId = isDesktop ? gatewayDeviceInfo?.deviceId : undefined;++ return useCallback(+ async (+ target: DeviceExecutionTarget,+ deviceId?: string,+ options?: SelectExecutionTargetOptions,+ ) => {+ if (isAccessLoading) return;++ // Fixed workspace agents are author-controlled. Keep any existing member+ // override dormant (so switching back to member choice restores it), but+ // never let this picker create or update an override while fixed.+ if (usesWorkspaceMemberSelection && agencyConfig?.executionTargetSelectionPolicy === 'fixed')+ return;++ const boundDeviceId = agencyConfig?.boundDeviceId;+ let nextBoundDeviceId = target === 'device' ? deviceId : boundDeviceId;if (target === 'local') {- boundDeviceId =- (isDesktop ? currentDeviceId : undefined) ??- (await gatewayConnectionService.getDeviceInfo())?.deviceId;- if (!boundDeviceId) return;+ nextBoundDeviceId = currentDeviceId;+ if (!nextBoundDeviceId) {+ try {+ nextBoundDeviceId = (await gatewayConnectionService.getDeviceInfo())?.deviceId;+ } catch {+ nextBoundDeviceId = undefined;+ }+ }+ // Hetero agents must execute somewhere; without a resolvable local+ // device there is nothing to pin `local` to, so don't switch.+ if (isHetero && !nextBoundDeviceId) return;}- if (target === 'device' && !boundDeviceId) return;- const store = useChatStore.getState();- if (!topicId && (store.activeAgentId !== agentId || store.activeTopicId)) return;- const destination = topicId ?? (await store.createTopic(agentId));- if (!destination) return;- await useChatStore.getState().updateTopicMetadata(destination, {- executionConfig: {- ...snapshotTopicExecutionConfig(agencyConfig),- inheritWorkspaceScope: false,- boundDeviceId,++ // Store the intent verbatim (`local` stays `local`), not a+ // pre-resolved `device`. Two reasons:+ //+ // 1. Semantic parity with personal agents. `local` and `device` are+ // distinct at dispatch time — `local` runs in-process on the+ // desktop, `device` tunnels through the gateway (even when the+ // bound device *is* this desktop). Persisting `device` would rob a+ // workspace-mode `local` pick of the faster in-process path when+ // the run happens on this desktop, and change personal-agent+ // behaviour (which used to store `local` verbatim).+ // 2. On surfaces without a client (web / server dispatch),+ // `resolveExecutionTarget` already coerces a stored `local` ++ // `boundDeviceId` to `device` when a gateway is available, so the+ // server-side dispatch path Just Works — no need to pre-coerce here.+ // `undefined` leaves the stored value untouched; `false` actively clears+ // it. Only the two local rows have an opinion, so a Cloud Sandbox pick+ // never rewrites the fence the user set on their own machine.+ const localSandboxPatch = {+ ...(options?.localSandbox === undefined ? {} : { localSandbox: options.localSandbox }),+ ...(options?.localSandboxNetwork === undefined+ ? {}+ : { localSandboxNetwork: options.localSandboxNetwork }),+ };++ // A `local` pick on a workspace agent is always this caller's own+ // machine — a personal device the workspace-shared row must never+ // reference (the server rejects it) — so it routes to the per-user+ // override even for managers and private-agent owners.+ if (usesWorkspaceMemberSelection || (isWorkspaceAgent && target === 'local')) {+ const nextOverrides = {+ ...workspaceUserPreference.agentDeviceOverrides,+ [agentId]: {+ ...workspaceUserPreference.agentDeviceOverrides?.[agentId],+ executionTarget: target,+ ...(nextBoundDeviceId ? { boundDeviceId: nextBoundDeviceId } : {}),+ ...localSandboxPatch,+ },+ };+ try {+ await updateWorkspaceUserPreference({ agentDeviceOverrides: nextOverrides });+ } catch {+ if (!options?.silent) toast.error(t('saveAgentConfigFail', { ns: 'common' }));+ }+ return;+ }++ const nextConfig = {+ agencyConfig: {+ ...agencyConfig,executionTarget: target,- ...(options?.localSandbox === undefined ? {} : { localSandbox: options.localSandbox }),- ...(options?.localSandboxNetwork === undefined- ? {}- : { localSandboxNetwork: options.localSandboxNetwork }),+ ...(nextBoundDeviceId ? { boundDeviceId: nextBoundDeviceId } : {}),+ ...localSandboxPatch,},- });+ };++ // A silent caller is defaulting the target on mount, not answering a+ // pick — telling the user "your change was not applied" would be+ // reporting a change they never made (automatic corrections must not trigger phantom save-error toasts).+ //+ // `rethrow` so a failed shared save (network error, server validation)+ // stops here: the store already rolled the optimistic config back and+ // toasted, and clearing the caller's override below would additionally+ // destroy their previously valid personal target over a save that never+ // happened.+ try {+ await updateAgentConfigById(agentId, nextConfig, {+ rethrow: true,+ ...(options?.silent ? { showErrorMessage: false } : {}),+ });+ } catch {+ return;+ }++ // A manager's earlier `local` pick lives in their own override and would+ // keep shadowing the shared target they just wrote — drop the override's+ // routing keys. The sandbox fence stays: it qualifies their machine, not+ // this pick.+ const prevOverride = workspaceUserPreference.agentDeviceOverrides?.[agentId];if (- !topicId &&- useChatStore.getState().activeAgentId === agentId &&- !useChatStore.getState().activeTopicId+ isWorkspaceAgent &&+ prevOverride &&+ (prevOverride.executionTarget !== undefined || prevOverride.boundDeviceId !== undefined)) {- await useChatStore.getState().switchTopic(destination);+ const { boundDeviceId: _device, executionTarget: _target, ...dormant } = prevOverride;+ try {+ await updateWorkspaceUserPreference({+ agentDeviceOverrides: {+ ...workspaceUserPreference.agentDeviceOverrides,+ [agentId]: dormant,+ },+ });+ } catch {+ // The preference store rolled the override back, so the old `local`+ // pick would keep shadowing the shared target that DID persist —+ // split state. Compensate by restoring the previous shared config+ // (best effort, no double toast) so the surviving override shadows+ // the same target the user had before this pick.+ await updateAgentConfigById(+ agentId,+ { agencyConfig: { ...agencyConfig } },+ { showErrorMessage: false },+ );+ if (!options?.silent) toast.error(t('saveAgentConfigFail', { ns: 'common' }));+ }}- } catch {- if (!options?.silent) toast.error(t('saveAgentConfigFail', { ns: 'common' }));- }- };+ },+ [+ agentId,+ agencyConfig,+ currentDeviceId,+ isHetero,+ isAccessLoading,+ isWorkspaceAgent,+ updateAgentConfigById,+ updateWorkspaceUserPreference,+ usesWorkspaceMemberSelection,+ workspaceUserPreference,+ ],+ );};diff --git a/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.tsindex 967abeb7ce3..a5e6c418c6f 100644--- a/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts+++ b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts@@ -3,8 +3,8 @@ import { useCallback } from 'react';import { isDesktop } from '@/const/version';import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -157,7 +157,7 @@ export const useOpenEditedFile = () => {const activeAgentId = useAgentStore((s) => s.activeAgentId);const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);const workingDirectory = useEffectiveWorkingDirectory(activeAgentId);- const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(activeAgentId);+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(activeAgentId);const deviceRoutingAvailable = useIsGatewayModeEnabled(activeAgentId);const effectiveTarget = resolveExecutionTarget(agencyConfig, {diff --git a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsxindex 8c70691f746..4edba46b457 100644--- a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx+++ b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx@@ -242,8 +242,8 @@ vi.mock('@/features/ChatInput/ControlBar/useRepoType', async () => {vi.mock('@/hooks/useEffectiveWorkingDirectory', () => ({useEffectiveWorkingDirectory: () => reviewState.workingDirectory,}));-vi.mock('@/hooks/useTopicAgencyConfig', () => ({- useTopicAgencyConfig: () => ({+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => ({agencyConfig: effectiveConfig.agencyConfig,workspaceScoped: effectiveConfig.workspaceScoped,}),diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex 2812baa560f..249b36e6075 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -53,9 +53,9 @@ import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';import { getWorkingDirectoryPathString } from '@/helpers/workingDirectoryPath';import { useDeferredMount } from '@/hooks/useDeferredMount';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';import { useLocalStorageState } from '@/hooks/useLocalStorageState';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';import type { NativeContextMenuItem } from '@/libs/contextMenu/types';import { useAgentStore } from '@/store/agent';import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';@@ -313,7 +313,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })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, workspaceScoped } = useTopicAgencyConfig(activeAgentId);+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(activeAgentId);const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {workspaceScoped,diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.tsindex 92b7b06ec9d..a6ac15c2287 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -33,7 +33,6 @@ const mockExecuteGatewayAgent = vi.fn();vi.mock('@/store/chat', () => ({useChatStore: {getState: vi.fn(() => ({- topicDataMap: {},messagesMap: {'session-1-': [{ id: 'msg-1', role: 'user', content: 'Hello' },@@ -209,7 +208,6 @@ describe('Generation Actions', () => {it('should continue generation from assistantGroup message with last child as blockId', async () => {// Reset mock to ensure all required functions are availablevi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -271,7 +269,6 @@ describe('Generation Actions', () => {it('should not continue if message is not assistantGroup', async () => {// Reset mock to ensure all required functions are availablevi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -310,7 +307,6 @@ describe('Generation Actions', () => {it('should not continue if assistantGroup has no children', async () => {// Reset mock to ensure all required functions are availablevi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -351,7 +347,6 @@ describe('Generation Actions', () => {it('should call onBeforeContinue hook and respect false return', async () => {// Reset mock to ensure all required functions are availablevi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -400,7 +395,6 @@ describe('Generation Actions', () => {it('should call onContinueComplete hook after continuation', async () => {// Reset mock to ensure all required functions are availablevi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -447,7 +441,6 @@ describe('Generation Actions', () => {it('should not continue if message is not found', async () => {// Reset mock to ensure all required functions are availablevi.mocked(await import('@/store/chat').then((m) => m.useChatStore.getState)).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -498,7 +491,6 @@ describe('Generation Actions', () => {const mockChatStore = async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},dbMessagesMap: {},operations: {},@@ -683,7 +675,6 @@ describe('Generation Actions', () => {// Re-setup mock to ensure all required functions are availableconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -750,7 +741,6 @@ describe('Generation Actions', () => {// Re-setup mock to track call orderconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -822,7 +812,6 @@ describe('Generation Actions', () => {it('should not proceed if assistant message has no parentId', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -868,7 +857,6 @@ describe('Generation Actions', () => {// this sub-second window and applies to the fresh run instead).let operationCount = 0;const chatState: any = {- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -958,7 +946,6 @@ describe('Generation Actions', () => {});const chatState: any = {dbMessagesMap: { [oldContextKey]: [oldUserMessage, oldAssistantMessage] },- topicDataMap: {},messagesMap: { [oldContextKey]: [oldUserMessage, oldAssistantMessage] },operations: {},operationsByMessage: {},@@ -1020,7 +1007,6 @@ describe('Generation Actions', () => {let operationCount = 0;const executeClientAgent = vi.fn().mockRejectedValue(new Error('boom'));const chatState: any = {- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1076,7 +1062,6 @@ describe('Generation Actions', () => {// Re-setup mock to ensure startOperation is availableconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1131,7 +1116,6 @@ describe('Generation Actions', () => {// Re-setup mock with all required propertiesconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1191,7 +1175,6 @@ describe('Generation Actions', () => {// Re-setup mock with all required propertiesconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1242,7 +1225,6 @@ describe('Generation Actions', () => {it('should bail out if the interim op was cancelled during preflight (Stop pressed)', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},// Simulate the user hitting Stop during the preflight awaits: stopGenerating// has already flipped the interim regenerate op to 'cancelled'.@@ -1295,7 +1277,6 @@ describe('Generation Actions', () => {// The op passes the preflight guard as 'running', then a Stop lands while// switchMessageBranch is awaiting — flip it to cancelled inside the mock.const chatState: any = {- topicDataMap: {},messagesMap: {},operations: { 'test-op-id': { id: 'test-op-id', status: 'running' } },operationsByMessage: {},@@ -1344,7 +1325,6 @@ describe('Generation Actions', () => {it('should restore mention-based initialContext when regenerating a user message', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1419,7 +1399,6 @@ describe('Generation Actions', () => {it('should use executeGatewayAgent when gateway mode is enabled', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1491,7 +1470,6 @@ describe('Generation Actions', () => {it('should call onRegenerateComplete hook after gateway regeneration', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1536,7 +1514,6 @@ describe('Generation Actions', () => {it('should fall back to client mode when gateway is disabled', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1579,7 +1556,6 @@ describe('Generation Actions', () => {it('should not regenerate if the message already has a running regenerate op', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {'op-1': {@@ -1624,7 +1600,6 @@ describe('Generation Actions', () => {it('regenerates despite an unrelated running op left on the message', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},dbMessagesMap: {},operations: {@@ -1696,10 +1671,12 @@ describe('Generation Actions', () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},+ // topicSelectors.getTopicById reads topicDataMap during workingDirectory+ // resolution; an empty map keeps the selector chain from throwing.+ topicDataMap: {},startOperation: mockHeteroStartOperation,completeOperation: mockCompleteOperation,@@ -1962,7 +1939,6 @@ describe('Generation Actions', () => {it('returns early without starting an operation or dispatching any runtime', async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({- topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex f1662682ebc..e864995df59 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -23,7 +23,6 @@ import {import { resolveAgentWorkingDirectory } from '@/helpers/agentWorkingDirectory';import { resolveWorkspaceScoped } from '@/helpers/executionTarget';import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';-import { getTopicAgencyConfig, getTopicWorkspaceScoped } from '@/helpers/topicExecutionConfig';import { messageService } from '@/services/message';import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';@@ -123,7 +122,7 @@ const ensureEffectiveAgencyAccess = async (agentId: string) => {});};-const getEffectiveAgencyConfig = (agentId: string, topicId?: string | null) => {+const getEffectiveAgencyConfig = (agentId: string) => {const agentState = getAgentStoreState();const sharedAgencyConfig = agentSelectors.getAgentConfigById(agentId)(agentState)?.agencyConfig;const agent = agentByIdSelectors.getAgentById(agentId)(agentState);@@ -147,21 +146,14 @@ const getEffectiveAgencyConfig = (agentId: string, topicId?: string | null) => {: undefined;return {- agencyConfig: getTopicAgencyConfig(- resolveAgentAgencyConfig(sharedAgencyConfig, deviceOverride, {- canManage,- visibility: agent?.visibility,- workspaceId: agent?.workspaceId,- }),- topicId,- ),+ agencyConfig: resolveAgentAgencyConfig(sharedAgencyConfig, deviceOverride, {+ canManage,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ }),/** True workspace membership — stays true for the author, unlike `workspaceScoped`. */isWorkspaceAgent: !!agent?.workspaceId,- workspaceScoped: getTopicWorkspaceScoped(- sharedAgencyConfig,- topicId,- resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),- ),+ workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),};};@@ -193,7 +185,7 @@ const resolveHeteroRunContext = (const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;const agentState = getAgentStoreState();const desktopContext = globalAgentContextManager.getContext();- const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(agentId, context.topicId);+ const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(agentId);const agentWorkingDirectory = resolveAgentWorkingDirectory({agencyConfig,currentDeviceId,@@ -429,7 +421,6 @@ const regenerateUserMessageFromSource = async (await ensureEffectiveAgencyAccess(context.agentId);const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(context.agentId,- context.topicId,);const heterogeneousProvider = agencyConfig?.heterogeneousProvider;const runtimeType = selectRuntimeType({@@ -820,7 +811,6 @@ export const generationSlice: StateCreator<await ensureEffectiveAgencyAccess(context.agentId);const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(context.agentId,- context.topicId,);const runtimeType = selectRuntimeType({boundDeviceId: agencyConfig?.boundDeviceId,@@ -912,7 +902,6 @@ export const generationSlice: StateCreator<await ensureEffectiveAgencyAccess(context.agentId);const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(context.agentId,- context.topicId,);const heterogeneousProvider = agencyConfig?.heterogeneousProvider;const runtimeType = selectRuntimeType({diff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.tsindex bb6886c00b5..9388c906a07 100644--- a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts@@ -120,8 +120,6 @@ const noop = vi.fn();vi.mock('@/store/chat', () => ({useChatStore: {getState: vi.fn(() => ({- topicDataMap: {},- topicDetailMap: mockTopic ? { [mockTopic.id]: mockTopic } : {},operations: {},operationsByMessage: {},diff --git a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.tsindex 71d7a1a9a16..ea5e62845ed 100644--- a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts+++ b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts@@ -83,8 +83,6 @@ const noop = vi.fn();vi.mock('@/store/chat', () => ({useChatStore: {getState: vi.fn(() => ({- topicDataMap: {},- topicDetailMap: {},operations: {},operationsByMessage: {},diff --git a/src/features/Conversation/useLocalPathReference.ts b/src/features/Conversation/useLocalPathReference.tsindex 6a94791560d..7aa292d75a9 100644--- a/src/features/Conversation/useLocalPathReference.ts+++ b/src/features/Conversation/useLocalPathReference.ts@@ -7,8 +7,8 @@ import {canExecutionTargetReadLocalPaths,resolveExecutionTarget,} from '@/helpers/executionTarget';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -31,7 +31,7 @@ export const useLocalPathReference = (agentId: string, topicId?: string | null)chatConfigByIdSelectors.isLocalSystemEnabledById(agentId),);const workingDirectory = useEffectiveWorkingDirectory(agentId, { topicId });- const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);const executionTarget = resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: isDesktop,diff --git a/src/helpers/localSandbox.ts b/src/helpers/localSandbox.tsindex cc167958f4d..f065dd44965 100644--- a/src/helpers/localSandbox.ts+++ b/src/helpers/localSandbox.ts@@ -4,7 +4,6 @@ import { resolveAgentAgencyConfig } from '@lobechat/types';import { getRuntimeCanManageAgent } from '@/helpers/agentManagementAccess';import { isLocalSandboxEnabled, resolveExecutionTarget } from '@/helpers/executionTarget';-import { getTopicAgencyConfig } from '@/helpers/topicExecutionConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { useUserStore } from '@/store/user';@@ -57,10 +56,7 @@ const isFenced = (agencyConfig: LobeAgentAgencyConfig | undefined): boolean =>* relaxation, by contrast, follows only the resolved reading: it widens what* a fenced command can reach, so it must match what the user's picker showed.*/-export const resolveClientLocalSandbox = (- agentId?: string,- topicId?: string | null,-): ClientLocalSandboxDecision => {+export const resolveClientLocalSandbox = (agentId?: string): ClientLocalSandboxDecision => {if (!isDesktop || !agentId) return unfenced;const state = useAgentStore.getState();@@ -75,20 +71,14 @@ export const resolveClientLocalSandbox = (currentUserId: userProfileSelectors.userId(userState),});const context = { visibility: agent?.visibility, workspaceId: agent?.workspaceId ?? undefined };- const resolved = getTopicAgencyConfig(- resolveAgentAgencyConfig(sharedAgencyConfig, override, {- ...context,- canManage,- }),- topicId,- );- const otherRole = getTopicAgencyConfig(- resolveAgentAgencyConfig(sharedAgencyConfig, override, {- ...context,- canManage: !canManage,- }),- topicId,- );+ const resolved = resolveAgentAgencyConfig(sharedAgencyConfig, override, {+ ...context,+ canManage,+ });+ const otherRole = resolveAgentAgencyConfig(sharedAgencyConfig, override, {+ ...context,+ canManage: !canManage,+ });const fenced = isFenced(resolved) || isFenced(otherRole);if (!fenced) return unfenced;diff --git a/src/helpers/topicExecutionConfig.test.ts b/src/helpers/topicExecutionConfig.test.tsdeleted file mode 100644index f2d1685beb6..00000000000--- a/src/helpers/topicExecutionConfig.test.ts+++ /dev/null@@ -1,81 +0,0 @@-import { applyTopicExecutionConfig, snapshotTopicExecutionConfig } from '@lobechat/types';-import { describe, expect, it, vi } from 'vitest';--import { resolveExecutionTarget } from './executionTarget';-import { resolveTopicAgencyConfig } from './topicExecutionConfig';--describe('Topic execution isolation', () => {- it('keeps A on its device when B or the Agent default switches to sandbox', () => {- const defaults = { executionTarget: 'local' as const, boundDeviceId: 'device-a' };- const topicA = snapshotTopicExecutionConfig(defaults);- const changedDefaults = { executionTarget: 'sandbox' as const, boundDeviceId: 'device-b' };- expect(applyTopicExecutionConfig(changedDefaults, topicA)).toMatchObject(defaults);- expect(applyTopicExecutionConfig(defaults, { executionTarget: 'sandbox' })).toMatchObject({- executionTarget: 'sandbox',- boundDeviceId: undefined,- });- expect(defaults.boundDeviceId).toBe('device-a');- });- it('does not inherit stale device or sandbox flags into an explicit Topic selection', () => {- expect(- applyTopicExecutionConfig(- { boundDeviceId: 'a', localSandbox: true },- {- executionTarget: 'auto',- },- ),- ).toEqual({- executionTarget: 'auto',- boundDeviceId: undefined,- localSandbox: undefined,- localSandboxNetwork: undefined,- });- });- it('keeps fixed policy authoritative and preserves legacy defaults', () => {- const fixed = {- executionTarget: 'device' as const,- boundDeviceId: 'fixed',- executionTargetSelectionPolicy: 'fixed' as const,- };- expect(applyTopicExecutionConfig(fixed, { executionTarget: 'sandbox' })).toBe(fixed);- expect(applyTopicExecutionConfig(fixed, undefined)).toBe(fixed);- });-});--vi.mock('@/store/chat', () => ({ useChatStore: { getState: () => ({}) } }));--it('uses Topic scope for a workspace member without an Agent override', () => {- const selection = resolveTopicAgencyConfig(- { executionTarget: 'sandbox' },- {- executionTarget: 'local',- boundDeviceId: 'this-machine',- },- true,- );- expect(selection.workspaceScoped).toBe(false);- expect(selection.agencyConfig).toMatchObject({- executionTarget: 'local',- boundDeviceId: 'this-machine',- });-});--it.each([undefined, 'local'] as const)(- 'keeps an inherited %s workspace target from becoming local execution',- (executionTarget) => {- const defaults = { executionTarget };- const selection = resolveTopicAgencyConfig(- defaults,- snapshotTopicExecutionConfig(defaults),- true,- );- expect(selection.workspaceScoped).toBe(true);- expect(- resolveExecutionTarget(selection.agencyConfig, {- clientExecutionAvailable: true,- isHetero: true,- workspaceScoped: selection.workspaceScoped,- }),- ).toBe('sandbox');- },-);diff --git a/src/helpers/topicExecutionConfig.ts b/src/helpers/topicExecutionConfig.tsdeleted file mode 100644index 1e67832a7cb..00000000000--- a/src/helpers/topicExecutionConfig.ts+++ /dev/null@@ -1,45 +0,0 @@-import {- applyTopicExecutionConfig,- type LobeAgentAgencyConfig,- type TopicExecutionConfig,-} from '@lobechat/types';--import { useChatStore } from '@/store/chat';-import { topicSelectors } from '@/store/chat/slices/topic/selectors';--export const getTopicAgencyConfig = (- defaults: LobeAgentAgencyConfig | undefined,- topicId?: string | null,-) =>- applyTopicExecutionConfig(- defaults,- topicId- ? topicSelectors.getTopicById(topicId)(useChatStore.getState())?.metadata?.executionConfig- : undefined,- );--export const getTopicWorkspaceScoped = (- defaults: LobeAgentAgencyConfig | undefined,- topicId: string | null | undefined,- fallback: boolean,-) => {- const execution = topicId- ? topicSelectors.getTopicById(topicId)(useChatStore.getState())?.metadata?.executionConfig- : undefined;- return resolveTopicAgencyConfig(defaults, execution, fallback).workspaceScoped;-};--/** Keep the UI and dispatch interpretation of a Topic selection identical. */-export const resolveTopicAgencyConfig = (- defaults: LobeAgentAgencyConfig | undefined,- execution: TopicExecutionConfig | undefined,- workspaceScoped: boolean,-) => ({- agencyConfig: applyTopicExecutionConfig(defaults, execution),- workspaceScoped:- execution &&- !execution.inheritWorkspaceScope &&- defaults?.executionTargetSelectionPolicy !== 'fixed'- ? false- : workspaceScoped,-});diff --git a/src/hooks/useEffectiveWorkingDirectory.test.ts b/src/hooks/useEffectiveWorkingDirectory.test.tsindex aa60038b98d..d3aa5cfc9ba 100644--- a/src/hooks/useEffectiveWorkingDirectory.test.ts+++ b/src/hooks/useEffectiveWorkingDirectory.test.ts@@ -25,8 +25,8 @@ const effectiveAgencyConfig = vi.hoisted(() => ({workspaceScoped: false,}));-vi.mock('@/hooks/useTopicAgencyConfig', () => ({- useTopicAgencyConfig: () => effectiveAgencyConfig,+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => effectiveAgencyConfig,}));vi.mock('@/store/agent', () => ({ useAgentStore: vi.fn() }));diff --git a/src/hooks/useEffectiveWorkingDirectory.ts b/src/hooks/useEffectiveWorkingDirectory.tsindex 674baecb92a..f3bf27e932b 100644--- a/src/hooks/useEffectiveWorkingDirectory.ts+++ b/src/hooks/useEffectiveWorkingDirectory.ts@@ -5,7 +5,7 @@ import {resolveTargetDeviceId,} from '@/helpers/agentWorkingDirectory';import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';@@ -51,7 +51,7 @@ export const useEffectiveWorkingDirectory = (// Effective config = shared row + this member's device override,// so `resolveTargetDeviceId` targets the device THIS member's run goes to —// not whichever machine landed on the workspace-shared row.- const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(agentId, topicId);+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);const legacyAgentWorkingDirectory = useAgentStore((s) =>agentId ? s.localAgentWorkingDirectoryMap[agentId] : undefined,);diff --git a/src/hooks/useRemoteAgentDeviceGuard.test.ts b/src/hooks/useRemoteAgentDeviceGuard.test.tsindex a6248c5e184..8c6ebb82d97 100644--- a/src/hooks/useRemoteAgentDeviceGuard.test.ts+++ b/src/hooks/useRemoteAgentDeviceGuard.test.ts@@ -1,17 +1,17 @@import { renderHook, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { deviceService } from '@/services/device';import { useRemoteAgentDeviceGuard } from './useRemoteAgentDeviceGuard';-vi.mock('@/hooks/useTopicAgencyConfig', () => ({ useTopicAgencyConfig: vi.fn() }));+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({ useEffectiveAgencyConfig: vi.fn() }));vi.mock('@/services/device', () => ({deviceService: { checkCapability: vi.fn(), listDevices: vi.fn() },}));-const mockedUseEffectiveAgencyConfig = vi.mocked(useTopicAgencyConfig);+const mockedUseEffectiveAgencyConfig = vi.mocked(useEffectiveAgencyConfig);const mockedCheckCapability = vi.mocked(deviceService.checkCapability);const mockedListDevices = vi.mocked(deviceService.listDevices);diff --git a/src/hooks/useRemoteAgentDeviceGuard.ts b/src/hooks/useRemoteAgentDeviceGuard.tsindex 6a3a6360af3..eb0b6edc143 100644--- a/src/hooks/useRemoteAgentDeviceGuard.ts+++ b/src/hooks/useRemoteAgentDeviceGuard.ts@@ -1,7 +1,7 @@import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';import { useCallback, useEffect, useState } from 'react';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { deviceService } from '@/services/device';export type RemoteAgentDeviceStatus =@@ -31,7 +31,7 @@ export const useRemoteAgentDeviceGuard = ({//. 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 } = useTopicAgencyConfig(agentId);+ const { agencyConfig, isPreferenceLoading } = useEffectiveAgencyConfig(agentId);const boundDeviceId = agencyConfig?.boundDeviceId;const providerType = agencyConfig?.heterogeneousProvider?.type;diff --git a/src/hooks/useTopicAgencyConfig.ts b/src/hooks/useTopicAgencyConfig.tsdeleted file mode 100644index 20d3db8d9f7..00000000000--- a/src/hooks/useTopicAgencyConfig.ts+++ /dev/null@@ -1,22 +0,0 @@-import { resolveTopicAgencyConfig } from '@/helpers/topicExecutionConfig';-import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';-import { useChatStore } from '@/store/chat';-import { topicSelectors } from '@/store/chat/slices/topic/selectors';--/** Chat-only overlay; Agent profile settings continue to edit defaults. */-export const useTopicAgencyConfig = (agentId?: string, topicId?: string | null) => {- const defaults = useEffectiveAgencyConfig(agentId);- const execution = useChatStore((s) =>- topicId !== undefined- ? topicId- ? topicSelectors.getTopicById(topicId)(s)?.metadata?.executionConfig- : undefined- : s.activeAgentId === agentId && s.activeTopicId- ? topicSelectors.getTopicById(s.activeTopicId)(s)?.metadata?.executionConfig- : undefined,- );- return {- ...defaults,- ...resolveTopicAgencyConfig(defaults.agencyConfig, execution, defaults.workspaceScoped),- };-};diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsxindex 1b05c4fbf9d..7e6a90b05cb 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx@@ -23,8 +23,8 @@ import {resolveExecutionTarget,} from '@/helpers/executionTarget';import { resolveProviderBindingGuard } from '@/helpers/providerBinding';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useRemoteAgentDeviceGuard } from '@/hooks/useRemoteAgentDeviceGuard';-import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';import { useChatStore } from '@/store/chat';import ApiModeModelBar from './ApiModeModelBar';@@ -97,7 +97,7 @@ 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, workspaceScoped } = useTopicAgencyConfig(agentId);+ const { agencyConfig, isPreferenceLoading, workspaceScoped } = useEffectiveAgencyConfig(agentId);const heterogeneousProvider = agencyConfig?.heterogeneousProvider;const providerType = heterogeneousProvider?.type;const isApiAuth = heterogeneousProvider?.authMode === 'api';diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.tsindex eb8f5caffe6..192578acc3b 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts@@ -6,9 +6,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { lambdaClient } from '@/libs/trpc/client';import { heterogeneousAgentService } from '@/services/electron/heterogeneousAgent';import { messageService } from '@/services/message';+import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';+import { useUserStore } from '@/store/user';import { useChatStore } from '../../../../store';import { messageMapKey } from '../../../../utils/messageMapKey';+import * as agentDispatcher from '../dispatch/agentDispatcher';import { createMockMessage, createMockResolvedAgentConfig, TEST_IDS } from './fixtures';import { resetTestEnvironment } from './helpers';@@ -66,6 +69,7 @@ beforeEach(() => {useChatStore.setState({updateTopicStatus: vi.fn().mockResolvedValue(undefined),});+ useUserStore.setState({ user: undefined, workspaceUserPreference: {} });});afterEach(() => {@@ -765,6 +769,82 @@ describe('ConversationControl actions', () => {});describe('server-mode branch', () => {+ it("uses a workspace member's effective device override to choose the resume transport", async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = 'workspace-agent';+ const topicId = 'workspace-topic';+ const chatKey = messageMapKey({ agentId, topicId });+ const toolMessage = createMockMessage({+ id: 'tool-msg-workspace-override',+ plugin: { apiName: 'write', arguments: '{}', identifier: 'fs', type: 'default' },+ role: 'tool',+ tool_call_id: 'call-workspace-override',+ } as any);++ vi.spyOn(agentSelectors, 'getAgentConfigById').mockImplementation(+ () => () =>+ ({+ agencyConfig: {+ executionTarget: 'local',+ heterogeneousProvider: { type: 'codex' },+ },+ }) as any,+ );+ vi.spyOn(agentByIdSelectors, 'getAgentById').mockImplementation(+ () => () =>+ ({+ userId: 'workspace-owner',+ visibility: 'public',+ workspaceId: 'workspace-1',+ }) as any,+ );+ useUserStore.setState({+ workspaceUserPreference: {+ agentDeviceOverrides: { [agentId]: { executionTarget: 'sandbox' } },+ },+ });+ const selectRuntimeTypeSpy = vi+ .spyOn(agentDispatcher, 'selectRuntimeType')+ .mockImplementation((config) =>+ config.executionTarget === 'sandbox' ? 'gateway' : 'hetero',+ );++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ dbMessagesMap: { [chatKey]: [toolMessage] },+ messagesMap: { [chatKey]: [toolMessage] },+ });+ });++ vi.spyOn(result.current, 'isGatewayModeEnabled').mockReturnValue(true);+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);+ const executeGatewayAgentSpy = vi+ .spyOn(result.current, 'executeGatewayAgent')+ .mockResolvedValue({} as any);+ const executeClientAgentSpy = vi+ .spyOn(result.current, 'executeClientAgent')+ .mockResolvedValue(undefined);++ await act(async () => {+ await result.current.approveToolCalling(toolMessage.id, '', {+ agentId,+ topicId,+ });+ });++ expect(selectRuntimeTypeSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ executionTarget: 'sandbox',+ isWorkspaceAgent: true,+ workspaceScoped: false,+ }),+ );+ expect(executeGatewayAgentSpy).toHaveBeenCalled();+ expect(executeClientAgentSpy).not.toHaveBeenCalled();+ });+it('should start a new Gateway op with resumeApproval.decision=approved and NOT run local runtime', async () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex dd269f18b53..47ae76d4cff 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -1899,7 +1899,6 @@ describe('ConversationLifecycle actions', () => {model: expect.any(String),provider: expect.any(String),metadata: {- executionConfig: { inheritWorkspaceScope: true },repos: [selectedRepo],workingDirectory: selectedRepo,workingDirectoryConfig: { path: selectedRepo, repoType: 'github' },@@ -1912,7 +1911,6 @@ describe('ConversationLifecycle actions', () => {model: expect.any(String),provider: expect.any(String),metadata: {- executionConfig: { inheritWorkspaceScope: true },repos: [selectedRepo],workingDirectory: selectedRepo,workingDirectoryConfig: { path: selectedRepo, repoType: 'github' },@@ -2002,11 +2000,6 @@ describe('ConversationLifecycle actions', () => {// run executes in); the config keeps the SOURCE repo, which is what// By-Project groups on.const expectedMetadata = {- executionConfig: {- boundDeviceId: deviceId,- executionTarget: 'local',- inheritWorkspaceScope: true,- },workingDirectory: worktreePath,workingDirectoryConfig: {git: { activeWorktree: worktreePath },@@ -2073,11 +2066,6 @@ describe('ConversationLifecycle actions', () => {expect.objectContaining({optimisticTopic: expect.objectContaining({metadata: {- executionConfig: {- boundDeviceId: deviceId,- executionTarget: 'device',- inheritWorkspaceScope: true,- },workingDirectory: '/repo/default',workingDirectoryConfig: { path: '/repo/default' },},@@ -2131,11 +2119,6 @@ describe('ConversationLifecycle actions', () => {expect.objectContaining({newTopic: expect.objectContaining({metadata: {- executionConfig: {- boundDeviceId: deviceId,- executionTarget: 'local',- inheritWorkspaceScope: true,- },workingDirectory: '/repo/lobehub',workingDirectoryConfig: { path: '/repo/lobehub' },},@@ -2188,15 +2171,7 @@ describe('ConversationLifecycle actions', () => {expect(executeGatewayAgentSpy).toHaveBeenCalledWith(expect.objectContaining({- optimisticTopic: expect.objectContaining({- metadata: {- executionConfig: {- boundDeviceId: deviceId,- executionTarget: 'local',- inheritWorkspaceScope: true,- },- },- }),+ optimisticTopic: expect.not.objectContaining({ metadata: expect.anything() }),}),);});@@ -2291,11 +2266,6 @@ describe('ConversationLifecycle actions', () => {expect.objectContaining({newTopic: expect.objectContaining({metadata: {- executionConfig: {- boundDeviceId: HETERO_DEVICE_ID,- executionTarget: 'local',- inheritWorkspaceScope: true,- },workingDirectory: '/repo/device-default',workingDirectoryConfig: { path: '/repo/device-default' },},diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 90a734797c4..866624ec3a9 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -9,7 +9,6 @@ import { shareChatService } from '@/services/shareChat';import { topicService } from '@/services/topic';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import * as serverConfigStore from '@/store/serverConfig';-import type { ChatTopic } from '@/types/topic';import type { GatewayConnection } from '../transports/gateway/gateway';import { GatewayActionImpl } from '../transports/gateway/gateway';@@ -126,16 +125,6 @@ vi.mock('@/store/agent/selectors', () => ({},}));-// The action is constructed with a test store; Topic routing must not initialize-// the real singleton (which would recursively construct GatewayActionImpl).-const mockChatState = vi.hoisted(() => ({- topicDataMap: {},- topicDetailMap: {} as Record<string, ChatTopic>,-}));-vi.mock('@/store/chat', () => ({- useChatStore: { getState: () => mockChatState },-}));-// ─── Mock Client Factory ───function createMockClient(): GatewayConnection['client'] & {@@ -190,7 +179,6 @@ function createTestAction() {describe('GatewayActionImpl', () => {beforeEach(() => {- mockChatState.topicDetailMap = {};moveChatContextSelections.mockClear();vi.mocked(topicService.settleRunningOperation).mockResolvedValue(undefined as never);mockAgentStore.state = { activeAgentId: undefined, agentMap: {} };@@ -2156,40 +2144,6 @@ describe('GatewayActionImpl', () => {);});- it('uses the Topic device after the Agent default switches to sandbox', async () => {- mockEnv.isDesktop = true;- mockGateway.getDeviceInfo.mockResolvedValue({ deviceId: 'this-desktop' });- mockChatState.topicDetailMap['topic-1'] = {- id: 'topic-1',- metadata: {- executionConfig: { executionTarget: 'local', boundDeviceId: 'topic-device' },- },- } as ChatTopic;-- await send();-- expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(- expect.objectContaining({ deviceId: 'topic-device', localDeviceId: 'this-desktop' }),- expect.anything(),- );- });-- it('does not activate this desktop when the Topic selects sandbox', async () => {- mockEnv.isDesktop = true;- mockRuntime.isLocal = true;- mockChatState.topicDetailMap['topic-1'] = {- id: 'topic-1',- metadata: { executionConfig: { executionTarget: 'sandbox' } },- } as ChatTopic;-- await send();-- expect(mockGateway.getDeviceInfo).not.toHaveBeenCalled();- expect(vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)?.[0]).not.toHaveProperty(- 'deviceId',- );- });-// Regression guard: an explicit sandbox/none/device target must not// preset this machine's deviceId — only a `local` target does.it('does not resolve a deviceId when a non-local runtime mode is selected', async () => {diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.tsindex f5cec0ed6f5..0876f92f5a9 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -1,16 +1,21 @@// Disable the auto sort key eslint rule to make the code more logic and readableimport { type AgentRuntimeContext } from '@lobechat/agent-runtime';-import { MESSAGE_CANCEL_FLAT } from '@lobechat/const';+import { isHeterogeneousAgentModelId, MESSAGE_CANCEL_FLAT } from '@lobechat/const';import {type ChatTopicStatus,type ConversationContext,type MessageMetadata,+ resolveAgentAgencyConfig,type UIChatMessage,} from '@lobechat/types';import { t } from 'i18next';import { type ChatInputEditor } from '@/features/ChatInput';-import { getTopicAgencyConfig } from '@/helpers/topicExecutionConfig';+import {+ ensureAgentManagementAccess,+ getRuntimeCanManageAgent,+} from '@/helpers/agentManagementAccess';+import { resolveWorkspaceScoped } from '@/helpers/executionTarget';import { lambdaClient } from '@/libs/trpc/client';import {type AgentInterventionSourceAction,@@ -18,7 +23,7 @@ import {type ResolveAgentInterventionBySourceResult,} from '@/services/aiAgent';import { getAgentStoreState } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';import { displayMessageSelectors } from '@/store/chat/selectors';import {type AgentRuntimeType,@@ -33,6 +38,7 @@ import { type ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { type StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';import { buildRunLifecycle } from '../lifecycle/buildRunLifecycle';import { type RunScope } from '../lifecycle/types';@@ -197,17 +203,51 @@ export class ConversationControlActionImpl {* scanning for it would flip us back into client-mode against a live* Gateway backend.*/- #shouldUseGatewayResume = (context: ConversationContext): boolean => {- const agentConfig = context.agentId- ? agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState())+ #shouldUseGatewayResume = async (context: ConversationContext): Promise<boolean> => {+ const agentId = context.agentId;+ if (!agentId) return false;++ const agentState = getAgentStoreState();+ const agentConfig = agentSelectors.getAgentConfigById(agentId)(agentState);+ const agent = agentByIdSelectors.getAgentById(agentId)(agentState);+ const currentUserId = userProfileSelectors.userId(useUserStore.getState());+ await ensureAgentManagementAccess({+ agentId,+ agentUserId: agent?.userId,+ currentUserId,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ });+ const canManage = getRuntimeCanManageAgent({+ agentId,+ agentUserId: agent?.userId,+ currentUserId,+ });+ const usesWorkspaceMemberSelection =+ !!agent?.workspaceId && agent.visibility !== 'private' && !canManage;+ const deviceOverride = agent?.workspaceId+ ? useUserStore.getState().workspaceUserPreference.agentDeviceOverrides?.[agentId]: undefined;- const agencyConfig = getTopicAgencyConfig(agentConfig?.agencyConfig, context.topicId);+ const agencyConfig = resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {+ canManage,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ });+ const isGatewayMode = this.#get().isGatewayModeEnabled(agentId);+ const heterogeneousProvider =+ agencyConfig?.heterogeneousProvider ??+ (!isGatewayMode && isHeterogeneousAgentModelId(agentConfig?.model)+ ? { type: agentConfig.model }+ : undefined);+return (selectRuntimeType({boundDeviceId: agencyConfig?.boundDeviceId,executionTarget: agencyConfig?.executionTarget,- heterogeneousProvider: agencyConfig?.heterogeneousProvider,- isGatewayMode: this.#get().isGatewayModeEnabled(context.agentId),+ heterogeneousProvider,+ isGatewayMode,+ isWorkspaceAgent: !!agent?.workspaceId,+ workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),}) === 'gateway');};@@ -567,7 +607,7 @@ export class ConversationControlActionImpl {});const optimisticContext = { operationId };- const shouldUseGatewayResume = this.#shouldUseGatewayResume(effectiveContext);+ const shouldUseGatewayResume = await this.#shouldUseGatewayResume(effectiveContext);if (!shouldUseGatewayResume) {this.#writeTopicStatus(effectiveContext, 'active');@@ -846,7 +886,7 @@ export class ConversationControlActionImpl {threadId: this.#get().activeThreadId,};- if (!this.#shouldUseGatewayResume(effectiveContext)) {+ if (!(await this.#shouldUseGatewayResume(effectiveContext))) {for (const toolMessageId of toolMessageIds) {await this.approveToolCalling(toolMessageId, '', effectiveContext);}@@ -980,7 +1020,7 @@ export class ConversationControlActionImpl {let resolvedOptions = options;let resolvedResponse = response;const shouldCreateUserMessage = resolvedOptions?.createUserMessage !== false;- const shouldUseGatewayResume = this.#shouldUseGatewayResume(effectiveContext);+ const shouldUseGatewayResume = await this.#shouldUseGatewayResume(effectiveContext);if (!shouldUseGatewayResume) {this.#writeTopicStatus(effectiveContext, 'active');@@ -1268,7 +1308,7 @@ export class ConversationControlActionImpl {});const optimisticContext: OptimisticUpdateContext = { operationId };- const shouldUseGatewayResume = this.#shouldUseGatewayResume(effectiveContext);+ const shouldUseGatewayResume = await this.#shouldUseGatewayResume(effectiveContext);if (!shouldUseGatewayResume) {this.#writeTopicStatus(effectiveContext, 'active');@@ -1455,7 +1495,7 @@ export class ConversationControlActionImpl {const toolMessage = dbMessageSelectors.getDbMessageById(toolMessageId)(this.#get());if (!toolMessage) return;- const shouldUseGatewayStop = this.#shouldUseGatewayResume(effectiveContext);+ const shouldUseGatewayStop = await this.#shouldUseGatewayResume(effectiveContext);const { operationId } = startOperation({type: 'cancelToolInteraction',@@ -1901,7 +1941,7 @@ export class ConversationControlActionImpl {});const optimisticContext = { operationId };- const shouldUseGatewayResume = this.#shouldUseGatewayResume(effectiveContext);+ const shouldUseGatewayResume = await this.#shouldUseGatewayResume(effectiveContext);if (!shouldUseGatewayResume) this.#writeTopicStatus(effectiveContext, 'active');@@ -2016,7 +2056,7 @@ export class ConversationControlActionImpl {// the LLM loop with the rejection content surfaced as user feedback.// Skip the client-mode `rejectToolCalling` chain below — that would fire// a duplicate halting `reject` before this continue signal.- if (this.#shouldUseGatewayResume(effectiveContext)) {+ if (await this.#shouldUseGatewayResume(effectiveContext)) {const requestMetadata = this.#getRequestMetadataFromMessageChain(messageId);const toolCallId = toolMessage.tool_call_id;if (!toolCallId) {diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 073bb5ee810..07476be4a8d 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -21,7 +21,6 @@ import {getWorkingDirEffectivePath,getWorkingDirSourcePath,resolveAgentAgencyConfig,- snapshotTopicExecutionConfig,} from '@lobechat/types';import { generateEntityId, nanoid } from '@lobechat/utils';import { toast } from '@lobehub/ui/base-ui';@@ -43,7 +42,6 @@ import {resolveWorkspaceScoped,} from '@/helpers/executionTarget';import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';-import { getTopicAgencyConfig, getTopicWorkspaceScoped } from '@/helpers/topicExecutionConfig';import { agentService } from '@/services/agent';import { aiAgentService } from '@/services/aiAgent';import { aiChatService } from '@/services/aiChat';@@ -441,22 +439,15 @@ export class ConversationLifecycleActionImpl {const deviceOverride = agent?.workspaceId? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]: undefined;- const workspaceScoped = getTopicWorkspaceScoped(- agentConfig?.agencyConfig,- context.topicId,- resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),- );+ const workspaceScoped = resolveWorkspaceScoped(usesWorkspaceMemberSelection, 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 = getTopicAgencyConfig(- resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {- canManage,- visibility: agent?.visibility,- workspaceId: agent?.workspaceId,- }),- context.topicId,- );+ const agencyConfig = resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {+ canManage,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ });const isGatewayMode = this.#get().isGatewayModeEnabled(agentId);// Legacy agents may only carry `model: '<cli-type>'`. Keep gateway routing// unchanged when it is available. Recover the provider when gateway mode is@@ -1220,11 +1211,9 @@ export class ConversationLifecycleActionImpl {}: undefined;/** First-send persistence bypasses turnSetup, so both runtime paths must carry the effort snapshot. */- const optimisticTopicMetadata: ChatTopicMetadata = {- ...workingDirectoryMetadata,- ...newTopicReasoningSnapshot,- executionConfig: snapshotTopicExecutionConfig(agencyConfig),- };+ const optimisticTopicMetadata = newTopicReasoningSnapshot+ ? { ...workingDirectoryMetadata, ...newTopicReasoningSnapshot }+ : workingDirectoryMetadata;// The sidebar row was already inserted (title + model) before the awaits// above; the cwd/repos metadata only resolves here, so patch it on now.diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex fe0d96ec7be..9950292c893 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -35,7 +35,6 @@ import {import debug from 'debug';import { createAgentToolsEngine } from '@/helpers/toolEngineering';-import { getTopicAgencyConfig } from '@/helpers/topicExecutionConfig';import { aiAgentService } from '@/services/aiAgent';import { isCanUseAudio, isCanUseVideo, isCanUseVision } from '@/services/chat/helper';import { type ResolvedAgentConfig } from '@/services/chat/mecha';@@ -186,11 +185,6 @@ export class StreamingExecutorActionImpl {scope, // Pass scope from operation context});- resolvedAgentConfig.agentConfig = {- ...resolvedAgentConfig.agentConfig,- agencyConfig: getTopicAgencyConfig(resolvedAgentConfig.agentConfig.agencyConfig, topicId),- };-// Resolve the effective model/provider, in precedence order:// 1. `modelOverride` — forced by the spawn site (see runClientSubAgent); not// re-derived here because `isSubAgent` is also set for isolated groupdiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 4347f8adf29..0b35eae355a 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -27,7 +27,6 @@ import {getRuntimeCanManageAgent,} from '@/helpers/agentManagementAccess';import { resolveExecutionTarget, resolveWorkspaceScoped } from '@/helpers/executionTarget';-import { getTopicAgencyConfig, getTopicWorkspaceScoped } from '@/helpers/topicExecutionConfig';import {aiAgentService,type ResumeApprovalParam,@@ -112,7 +111,6 @@ const interruptGatewayTaskOrThrow = async (*/const resolveDesktopDeviceHints = async (agentId?: string,- topicId?: string | null,): Promise<{ deviceId?: string; localDeviceId?: string }> => {if (!isDesktop || !agentId) return {};@@ -152,27 +150,20 @@ const resolveDesktopDeviceHints = async (const deviceOverride = agent?.workspaceId? userState.workspaceUserPreference.agentDeviceOverrides?.[agentId]: undefined;- const agencyConfig = getTopicAgencyConfig(- resolveAgentAgencyConfig(- agentByIdSelectors.getAgencyConfigById(agentId)(agentState),- deviceOverride,- {- canManage,- visibility: agent?.visibility,- workspaceId: agent?.workspaceId,- },- ),- topicId,+ const agencyConfig = resolveAgentAgencyConfig(+ agentByIdSelectors.getAgencyConfigById(agentId)(agentState),+ deviceOverride,+ {+ canManage,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ },);const isPlatformTask = isRemoteHeterogeneousType(agencyConfig?.heterogeneousProvider?.type ?? '');const executionTarget = resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: true,isHetero: !!agencyConfig?.heterogeneousProvider,- workspaceScoped: getTopicWorkspaceScoped(- agencyConfig,- topicId,- resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),- ),+ workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),});// Platform hints are capability claims, not routing overrides. Always send// this desktop best-effort and let the server's authoritative execution plan@@ -184,7 +175,7 @@ const resolveDesktopDeviceHints = async (if (!info?.deviceId) return {};return isPlatformTask? { localDeviceId: info.deviceId }- : { deviceId: agencyConfig?.boundDeviceId ?? info.deviceId, localDeviceId: info.deviceId };+ : { deviceId: info.deviceId, localDeviceId: info.deviceId };} catch {return {};}@@ -795,10 +786,7 @@ export class GatewayActionImpl {? this.#get().getOperationAbortSignal(parentOperationId): undefined;- const desktopDeviceHints = await resolveDesktopDeviceHints(- executionContext.agentId,- executionContext.topicId,- );+ const desktopDeviceHints = await resolveDesktopDeviceHints(executionContext.agentId);const userInterventionConfig = {approvalMode: toolInterventionSelectors.approvalMode(useUserStore.getState()),allowList: toolInterventionSelectors.allowList(useUserStore.getState()),diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.tsindex 3304f962414..e8b275f9e20 100644--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts@@ -205,7 +205,7 @@ export class PluginTypesActionImpl {// Only the in-process desktop path reaches here; gateway-routed runs// get the same decision from the server device-proxy. Both funnel// through `isLocalSandboxEnabled`, so they cannot disagree.- ...resolveClientLocalSandbox(agentId, topicId),+ ...resolveClientLocalSandbox(agentId),messageId: id,operationId,registerAfterCompletion,diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 4d442575905..fccfd4a3835 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -3578,20 +3578,18 @@ describe('topic action', () => {});});-describe('Topic execution save failures', () => {- const key = topicMapKey({ agentId: 'agent-execution' });- const previous = {- executionConfig: { executionTarget: 'device' as const, boundDeviceId: 'device-a' },- };- const selected = { executionConfig: { executionTarget: 'sandbox' as const } };+describe('Topic metadata save failures', () => {+ const key = topicMapKey({ agentId: 'agent-metadata' });+ const previous = { heteroSessionId: 'session-a' };+ const selected = { heteroSessionId: 'session-b' };const setup = () => {useChatStore.setState({- activeAgentId: 'agent-execution',+ activeAgentId: 'agent-metadata',topicDataMap: {[key]: {items: [{- id: 'topic-execution',+ id: 'topic-metadata',title: 'A',createdAt: 1,updatedAt: 1,@@ -3608,18 +3606,20 @@ describe('Topic execution save failures', () => {});vi.spyOn(useChatStore.getState(), 'refreshTopic').mockRejectedValue(new Error('offline'));};- it('restores the saved target if the mutation fails while offline', async () => {++ it('restores the previous metadata if the mutation fails while offline', async () => {setup();vi.spyOn(topicService, 'updateTopicMetadata').mockRejectedValueOnce(new Error('offline'));await expect(- useChatStore.getState().updateTopicMetadata('topic-execution', selected),+ useChatStore.getState().updateTopicMetadata('topic-metadata', selected),).rejects.toThrow('offline');expect(useChatStore.getState().topicDataMap[key].items[0].metadata).toEqual(previous);});- it('keeps the saved selection if only revalidation fails', async () => {++ it('keeps the saved metadata if only revalidation fails', async () => {setup();vi.spyOn(topicService, 'updateTopicMetadata').mockResolvedValueOnce([]);- await useChatStore.getState().updateTopicMetadata('topic-execution', selected);+ await useChatStore.getState().updateTopicMetadata('topic-metadata', selected);expect(useChatStore.getState().topicDataMap[key].items[0].metadata).toEqual(selected);});});