🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: isolate execution settings per topic (#19445)
Tsuki3e47ca73646c
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 407009c57ee..49ca5606ab8 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(),- // The pinned reasoning snapshot taken next to the pinned model- // (`snapshotAgentReasoning`); other metadata keys are server-owned.+ // Execution routing and reasoning snapshots belong to this Topic;+ // 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 a48d367df02..391c7651c0d 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts@@ -573,7 +573,16 @@ describe('AiAgentService.execAgent - device auto-activation', () => {expect(mockCreateOperation.mock.calls[0][0].activeDeviceId).toBeUndefined();expect(topicMock.create).toHaveBeenCalledWith(- expect.objectContaining({ metadata: undefined }),+ expect.objectContaining({+ metadata: {+ boundDeviceId: undefined,+ executionConfig: {+ boundDeviceId: undefined,+ executionTarget: 'sandbox',+ inheritWorkspaceScope: true,+ },+ },+ }),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 f81ac675d67..3e4641c27f9 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts@@ -1,3 +1,4 @@+import type { ChatTopicMetadata } from '@lobechat/types';import type * as ModelBankModule from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -112,6 +113,7 @@ 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 6febaa91891..a964875f970 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.topicHistory.test.ts@@ -203,6 +203,24 @@ 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 3c01069b6e8..1c7c765f9be 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1055,7 +1055,7 @@ export class AiAgentService {parentOperationId,pinnedHeterogeneousTopicModel: turn.pinnedHeterogeneousTopicModel,requestTrigger: requestTriggerMetadata.trigger,- requestedDeviceId,+ requestedDeviceId: turn.effectiveRequestedDeviceId,runAttachments,selfMessageIds,topicStartOwnerOperationId: params.topicStartOwnerOperationId,@@ -1178,7 +1178,7 @@ export class AiAgentService {loadHistoryMessages,localDeviceId,requestTrigger: requestTriggerMetadata.trigger,- requestedDeviceId,+ requestedDeviceId: turn.effectiveRequestedDeviceId,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 c9dd7db8c6e..b9fe95ca14c 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -10,9 +10,11 @@ import type {HeterogeneousTopicPin,} from '@lobechat/types';import {+ applyTopicExecutionConfig,ChatErrorType,RequestTrigger,resolveHeterogeneousProviderTopicModel,+ snapshotTopicExecutionConfig,} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -420,10 +422,8 @@ export const setupTurn = async (!!deps.workspaceId && agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed';const isFixedDeviceTarget =isFixedExecutionTargetSelection && agentConfig.agencyConfig?.executionTarget === 'device';- const effectiveRequestedDeviceId = isFixedExecutionTargetSelection- ? undefined- : requestedDeviceId;- const topicBoundDeviceId = isFixedDeviceTarget+ let effectiveRequestedDeviceId = isFixedExecutionTargetSelection ? undefined : requestedDeviceId;+ let topicBoundDeviceId = isFixedDeviceTarget? agentConfig.agencyConfig?.boundDeviceId: isFixedExecutionTargetSelection? undefined@@ -468,30 +468,25 @@ 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 =- 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 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 fallbackTitleSource = markdownToTxt(prompt);const snapshot = await resolveNewTopicSnapshot(deps, agentConfig);@@ -577,6 +572,33 @@ 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 3ebdbdddbc4..8e58adc76b0 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -1038,6 +1038,24 @@ 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 f7fb4f8ff3f..cf274d9a0ca 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1891,7 +1891,11 @@ 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) => {+ updateMetadata = async (+ id: string,+ metadata: TopicMetadataPatch,+ options?: { executionConfigIfAbsent?: boolean },+ ) => {// 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@@ -1923,6 +1927,9 @@ 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 153cc6d7f69..af8899aa0aa 100644--- a/packages/types/src/topic/topic.test.ts+++ b/packages/types/src/topic/topic.test.ts@@ -173,3 +173,15 @@ 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 6169345a9d2..49f02f653a1 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -2,6 +2,7 @@ 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';@@ -113,6 +114,43 @@ 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?: {@@ -148,6 +186,7 @@ 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@@ -496,6 +535,7 @@ 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')@@ -585,10 +625,11 @@ export const chatTopicMetadataUpdateSchema = z.object({});/**- * Metadata a client may seed when creating a topic: the pinned reasoning- * snapshot taken alongside the pinned model (see `snapshotAgentModel`).+ * Metadata a client may seed when creating a topic: execution routing and the+ * 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 90594c4accb..ddedb61ca50 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/useEffectiveAgencyConfig', () => ({- useEffectiveAgencyConfig: () => ({+vi.mock('@/hooks/useTopicAgencyConfig', () => ({+ useTopicAgencyConfig: () => ({agencyConfig: effectiveAgencyConfig.current,workspaceScoped: effectiveAgencyConfig.workspaceScoped,}),diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsxindex eeca16cb760..2b3dad41856 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 { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';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 } = useEffectiveAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(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 0a854380d2e..f3db036bbbb 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,- } = useEffectiveAgencyConfig(agentId);+ } = useTopicAgencyConfig(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 0725ffeeb73..60b0ab5ca0b 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,8 +171,7 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(handleOpenChangeComplete: completeOpenChange,open,} = useMenuContentLifecycle(onSelect);- const { agencyConfig, isPreferenceLoading, workspaceScoped } =- useEffectiveAgencyConfig(agentId);+ const { agencyConfig, isPreferenceLoading, workspaceScoped } = useTopicAgencyConfig(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 e01dc22e628..6b49ee4f3bb 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 { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';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 } = useEffectiveAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(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 0b3f52b345f..cbcc2907790 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 } = useEffectiveAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(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 942b949b782..37f275d6596 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/useEffectiveAgencyConfig', () => ({- useEffectiveAgencyConfig: () => testState.effective,+vi.mock('@/hooks/useTopicAgencyConfig', () => ({+ useTopicAgencyConfig: () => 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 20d8e8db923..b8970811707 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 `useEffectiveAgencyConfig` would resolve it. The raw shared row lives in+// as `useTopicAgencyConfig` 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/useEffectiveAgencyConfig', () => ({- useEffectiveAgencyConfig: () => ({+vi.mock('@/hooks/useTopicAgencyConfig', () => ({+ useTopicAgencyConfig: () => ({agencyConfig: effective.agencyConfig,workspaceScoped: effective.workspaceScoped,}),diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.tsindex 99b5499d7f1..e7e45ac8907 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 { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -91,8 +91,7 @@ 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 } =- useEffectiveAgencyConfig(agentId);+ const { agencyConfig: effectiveAgencyConfig, workspaceScoped } = useTopicAgencyConfig(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 4aedf77f635..b813f079881 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 { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';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 } = useEffectiveAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(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 7bd1975522e..74f335629df 100644--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts@@ -3,614 +3,130 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { useSelectExecutionTarget } from './useSelectExecutionTarget';-const testState = vi.hoisted(() => ({- access: {- canManageAgent: true,- isAccessLoading: false,+const state = vi.hoisted(() => ({+ config: {+ agencyConfig: { executionTarget: 'local', boundDeviceId: 'device-a' },+ canSelectExecutionTarget: true,},- 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 }- >;- },+ chat: {+ activeAgentId: 'agent',+ activeTopicId: 'topic-a' as string | undefined,+ createTopic: vi.fn(),+ updateTopicMetadata: vi.fn(),+ switchTopic: vi.fn(),},+ desktop: true,+ deviceInfo: vi.fn(),+ toast: vi.fn(),}));-vi.mock('@lobechat/const', () => ({get isDesktop() {- return testState.isDesktop;- },-}));--vi.mock('@lobehub/ui/base-ui', () => ({- toast: { error: vi.fn() },-}));--vi.mock('i18next', () => ({- t: (key: string) => key,-}));--vi.mock('@/services/electron/gatewayConnection', () => ({- gatewayConnectionService: {- getDeviceInfo: () => testState.getDeviceInfo(),+ return state.desktop;},}));--vi.mock('@/features/ResourcePermission/useAgentManagementAccess', () => ({- useAgentManagementAccess: () => testState.access,-}));--vi.mock('@/store/agent', () => ({- useAgentStore: (selector: (s: typeof testState.agent) => unknown) => selector(testState.agent),+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('@/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),+ useElectronStore: (selector: (s: object) => unknown) =>+ selector({ gatewayDeviceInfo: undefined }),}));--vi.mock('@/store/user', () => ({- useUserStore: (selector: (s: typeof testState.user) => unknown) => selector(testState.user),+vi.mock('@/services/electron/gatewayConnection', () => ({+ gatewayConnectionService: { getDeviceInfo: state.deviceInfo },}));-describe('useSelectExecutionTarget', () => {+describe('Topic execution selection', () => {beforeEach(() => {- 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();+ 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);});-- 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('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('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('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('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' }),+ }),+ );});-- 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('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');});-- 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();- });+ 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();});+ 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();+ });+});++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();});diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.tsindex 1fb4783ac98..22084b95c7f 100644--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts@@ -1,246 +1,69 @@'use client';import { isDesktop } from '@lobechat/const';-import type { DeviceExecutionTarget } from '@lobechat/types';+import { type DeviceExecutionTarget, snapshotTopicExecutionConfig } from '@lobechat/types';import { toast } from '@lobehub/ui/base-ui';import { t } from 'i18next';-import { useCallback } from 'react';-import { useAgentManagementAccess } from '@/features/ResourcePermission/useAgentManagementAccess';+import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';import { gatewayConnectionService } from '@/services/electron/gatewayConnection';-import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors } from '@/store/agent/selectors';+import { useChatStore } from '@/store/chat';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;}-/**- * 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.- */+/** Capture the destination before device discovery or persistence can yield. */export const useSelectExecutionTarget = (agentId: string) => {- 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);+ const { agencyConfig, canSelectExecutionTarget } = useTopicAgencyConfig(agentId);+ const topicId = useChatStore((s) => (s.activeAgentId === agentId ? s.activeTopicId : undefined));+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);- 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;+ 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;if (target === 'local') {- 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;+ boundDeviceId =+ (isDesktop ? currentDeviceId : undefined) ??+ (await gatewayConnectionService.getDeviceInfo())?.deviceId;+ if (!boundDeviceId) return;}-- // 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,- },- };- await updateWorkspaceUserPreference({ agentDeviceOverrides: nextOverrides });- return;- }-- const nextConfig = {- agencyConfig: {- ...agencyConfig,+ 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,executionTarget: target,- ...(nextBoundDeviceId ? { boundDeviceId: nextBoundDeviceId } : {}),- ...localSandboxPatch,+ ...(options?.localSandbox === undefined ? {} : { localSandbox: options.localSandbox }),+ ...(options?.localSandboxNetwork === undefined+ ? {}+ : { localSandboxNetwork: options.localSandboxNetwork }),},- };-- // 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 (- isWorkspaceAgent &&- prevOverride &&- (prevOverride.executionTarget !== undefined || prevOverride.boundDeviceId !== undefined)+ !topicId &&+ useChatStore.getState().activeAgentId === agentId &&+ !useChatStore.getState().activeTopicId) {- 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' }));- }+ await useChatStore.getState().switchTopic(destination);}- },- [- agentId,- agencyConfig,- currentDeviceId,- isHetero,- isAccessLoading,- isWorkspaceAgent,- updateAgentConfigById,- updateWorkspaceUserPreference,- usesWorkspaceMemberSelection,- workspaceUserPreference,- ],- );+ } catch {+ if (!options?.silent) toast.error(t('saveAgentConfigFail', { ns: 'common' }));+ }+ };};diff --git a/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.tsindex a5e6c418c6f..967abeb7ce3 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 } = useEffectiveAgencyConfig(activeAgentId);+ const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(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 0504baec9f8..8ce94494dca 100644--- a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx+++ b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx@@ -241,8 +241,8 @@ vi.mock('@/features/ChatInput/ControlBar/useRepoType', async () => {vi.mock('@/hooks/useEffectiveWorkingDirectory', () => ({useEffectiveWorkingDirectory: () => reviewState.workingDirectory,}));-vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({- useEffectiveAgencyConfig: () => ({+vi.mock('@/hooks/useTopicAgencyConfig', () => ({+ useTopicAgencyConfig: () => ({agencyConfig: effectiveConfig.agencyConfig,workspaceScoped: effectiveConfig.workspaceScoped,}),diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex 00650d59538..dd0d4ca418d 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -52,9 +52,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';@@ -328,7 +328,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 } = useEffectiveAgencyConfig(activeAgentId);+ const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(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 a6ac15c2287..92b7b06ec9d 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -33,6 +33,7 @@ const mockExecuteGatewayAgent = vi.fn();vi.mock('@/store/chat', () => ({useChatStore: {getState: vi.fn(() => ({+ topicDataMap: {},messagesMap: {'session-1-': [{ id: 'msg-1', role: 'user', content: 'Hello' },@@ -208,6 +209,7 @@ 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: {},@@ -269,6 +271,7 @@ 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: {},@@ -307,6 +310,7 @@ 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: {},@@ -347,6 +351,7 @@ 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: {},@@ -395,6 +400,7 @@ 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: {},@@ -441,6 +447,7 @@ 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: {},@@ -491,6 +498,7 @@ describe('Generation Actions', () => {const mockChatStore = async () => {const { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ topicDataMap: {},messagesMap: {},dbMessagesMap: {},operations: {},@@ -675,6 +683,7 @@ 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: {},@@ -741,6 +750,7 @@ describe('Generation Actions', () => {// Re-setup mock to track call orderconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -812,6 +822,7 @@ 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: {},@@ -857,6 +868,7 @@ describe('Generation Actions', () => {// this sub-second window and applies to the fresh run instead).let operationCount = 0;const chatState: any = {+ topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -946,6 +958,7 @@ describe('Generation Actions', () => {});const chatState: any = {dbMessagesMap: { [oldContextKey]: [oldUserMessage, oldAssistantMessage] },+ topicDataMap: {},messagesMap: { [oldContextKey]: [oldUserMessage, oldAssistantMessage] },operations: {},operationsByMessage: {},@@ -1007,6 +1020,7 @@ describe('Generation Actions', () => {let operationCount = 0;const executeClientAgent = vi.fn().mockRejectedValue(new Error('boom'));const chatState: any = {+ topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1062,6 +1076,7 @@ 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: {},@@ -1116,6 +1131,7 @@ describe('Generation Actions', () => {// Re-setup mock with all required propertiesconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1175,6 +1191,7 @@ describe('Generation Actions', () => {// Re-setup mock with all required propertiesconst { useChatStore } = await import('@/store/chat');vi.mocked(useChatStore.getState).mockReturnValue({+ topicDataMap: {},messagesMap: {},operations: {},operationsByMessage: {},@@ -1225,6 +1242,7 @@ 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'.@@ -1277,6 +1295,7 @@ 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: {},@@ -1325,6 +1344,7 @@ 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: {},@@ -1399,6 +1419,7 @@ 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: {},@@ -1470,6 +1491,7 @@ 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: {},@@ -1514,6 +1536,7 @@ 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: {},@@ -1556,6 +1579,7 @@ 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': {@@ -1600,6 +1624,7 @@ 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: {@@ -1671,12 +1696,10 @@ 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,@@ -1939,6 +1962,7 @@ 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 e864995df59..f1662682ebc 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -23,6 +23,7 @@ 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';@@ -122,7 +123,7 @@ const ensureEffectiveAgencyAccess = async (agentId: string) => {});};-const getEffectiveAgencyConfig = (agentId: string) => {+const getEffectiveAgencyConfig = (agentId: string, topicId?: string | null) => {const agentState = getAgentStoreState();const sharedAgencyConfig = agentSelectors.getAgentConfigById(agentId)(agentState)?.agencyConfig;const agent = agentByIdSelectors.getAgentById(agentId)(agentState);@@ -146,14 +147,21 @@ const getEffectiveAgencyConfig = (agentId: string) => {: undefined;return {- agencyConfig: resolveAgentAgencyConfig(sharedAgencyConfig, deviceOverride, {- canManage,- visibility: agent?.visibility,- workspaceId: agent?.workspaceId,- }),+ agencyConfig: getTopicAgencyConfig(+ resolveAgentAgencyConfig(sharedAgencyConfig, deviceOverride, {+ canManage,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ }),+ topicId,+ ),/** True workspace membership — stays true for the author, unlike `workspaceScoped`. */isWorkspaceAgent: !!agent?.workspaceId,- workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),+ workspaceScoped: getTopicWorkspaceScoped(+ sharedAgencyConfig,+ topicId,+ resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),+ ),};};@@ -185,7 +193,7 @@ const resolveHeteroRunContext = (const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;const agentState = getAgentStoreState();const desktopContext = globalAgentContextManager.getContext();- const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(agentId, context.topicId);const agentWorkingDirectory = resolveAgentWorkingDirectory({agencyConfig,currentDeviceId,@@ -421,6 +429,7 @@ const regenerateUserMessageFromSource = async (await ensureEffectiveAgencyAccess(context.agentId);const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(context.agentId,+ context.topicId,);const heterogeneousProvider = agencyConfig?.heterogeneousProvider;const runtimeType = selectRuntimeType({@@ -811,6 +820,7 @@ export const generationSlice: StateCreator<await ensureEffectiveAgencyAccess(context.agentId);const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(context.agentId,+ context.topicId,);const runtimeType = selectRuntimeType({boundDeviceId: agencyConfig?.boundDeviceId,@@ -902,6 +912,7 @@ 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 9388c906a07..bb6886c00b5 100644--- a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts@@ -120,6 +120,8 @@ 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 ea5e62845ed..71d7a1a9a16 100644--- a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts+++ b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts@@ -83,6 +83,8 @@ 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 7aa292d75a9..6a94791560d 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 } = useEffectiveAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(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 f065dd44965..cc167958f4d 100644--- a/src/helpers/localSandbox.ts+++ b/src/helpers/localSandbox.ts@@ -4,6 +4,7 @@ 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';@@ -56,7 +57,10 @@ 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): ClientLocalSandboxDecision => {+export const resolveClientLocalSandbox = (+ agentId?: string,+ topicId?: string | null,+): ClientLocalSandboxDecision => {if (!isDesktop || !agentId) return unfenced;const state = useAgentStore.getState();@@ -71,14 +75,20 @@ export const resolveClientLocalSandbox = (agentId?: string): ClientLocalSandboxDcurrentUserId: userProfileSelectors.userId(userState),});const context = { visibility: agent?.visibility, workspaceId: agent?.workspaceId ?? undefined };- const resolved = resolveAgentAgencyConfig(sharedAgencyConfig, override, {- ...context,- canManage,- });- const otherRole = resolveAgentAgencyConfig(sharedAgencyConfig, override, {- ...context,- canManage: !canManage,- });+ const resolved = getTopicAgencyConfig(+ resolveAgentAgencyConfig(sharedAgencyConfig, override, {+ ...context,+ canManage,+ }),+ topicId,+ );+ const otherRole = getTopicAgencyConfig(+ resolveAgentAgencyConfig(sharedAgencyConfig, override, {+ ...context,+ canManage: !canManage,+ }),+ topicId,+ );const fenced = isFenced(resolved) || isFenced(otherRole);if (!fenced) return unfenced;diff --git a/src/helpers/topicExecutionConfig.test.ts b/src/helpers/topicExecutionConfig.test.tsnew file mode 100644index 00000000000..f2d1685beb6--- /dev/null+++ b/src/helpers/topicExecutionConfig.test.ts@@ -0,0 +1,81 @@+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.tsnew file mode 100644index 00000000000..1e67832a7cb--- /dev/null+++ b/src/helpers/topicExecutionConfig.ts@@ -0,0 +1,45 @@+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 d3aa5cfc9ba..aa60038b98d 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/useEffectiveAgencyConfig', () => ({- useEffectiveAgencyConfig: () => effectiveAgencyConfig,+vi.mock('@/hooks/useTopicAgencyConfig', () => ({+ useTopicAgencyConfig: () => effectiveAgencyConfig,}));vi.mock('@/store/agent', () => ({ useAgentStore: vi.fn() }));diff --git a/src/hooks/useEffectiveWorkingDirectory.ts b/src/hooks/useEffectiveWorkingDirectory.tsindex f3bf27e932b..674baecb92a 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 { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';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 } = useEffectiveAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = useTopicAgencyConfig(agentId, topicId);const legacyAgentWorkingDirectory = useAgentStore((s) =>agentId ? s.localAgentWorkingDirectoryMap[agentId] : undefined,);diff --git a/src/hooks/useRemoteAgentDeviceGuard.test.ts b/src/hooks/useRemoteAgentDeviceGuard.test.tsindex 8c6ebb82d97..a6248c5e184 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 { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';import { deviceService } from '@/services/device';import { useRemoteAgentDeviceGuard } from './useRemoteAgentDeviceGuard';-vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({ useEffectiveAgencyConfig: vi.fn() }));+vi.mock('@/hooks/useTopicAgencyConfig', () => ({ useTopicAgencyConfig: vi.fn() }));vi.mock('@/services/device', () => ({deviceService: { checkCapability: vi.fn(), listDevices: vi.fn() },}));-const mockedUseEffectiveAgencyConfig = vi.mocked(useEffectiveAgencyConfig);+const mockedUseEffectiveAgencyConfig = vi.mocked(useTopicAgencyConfig);const mockedCheckCapability = vi.mocked(deviceService.checkCapability);const mockedListDevices = vi.mocked(deviceService.listDevices);diff --git a/src/hooks/useRemoteAgentDeviceGuard.ts b/src/hooks/useRemoteAgentDeviceGuard.tsindex eb0b6edc143..6a3a6360af3 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 { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useTopicAgencyConfig } from '@/hooks/useTopicAgencyConfig';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 } = useEffectiveAgencyConfig(agentId);+ const { agencyConfig, isPreferenceLoading } = useTopicAgencyConfig(agentId);const boundDeviceId = agencyConfig?.boundDeviceId;const providerType = agencyConfig?.heterogeneousProvider?.type;diff --git a/src/hooks/useTopicAgencyConfig.ts b/src/hooks/useTopicAgencyConfig.tsnew file mode 100644index 00000000000..20d3db8d9f7--- /dev/null+++ b/src/hooks/useTopicAgencyConfig.ts@@ -0,0 +1,22 @@+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 7e6a90b05cb..1b05c4fbf9d 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 } = useEffectiveAgencyConfig(agentId);+ const { agencyConfig, isPreferenceLoading, workspaceScoped } = useTopicAgencyConfig(agentId);const heterogeneousProvider = agencyConfig?.heterogeneousProvider;const providerType = heterogeneousProvider?.type;const isApiAuth = heterogeneousProvider?.authMode === 'api';diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex e8501c25d82..857c2d169de 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -1899,6 +1899,7 @@ describe('ConversationLifecycle actions', () => {model: expect.any(String),provider: expect.any(String),metadata: {+ executionConfig: { inheritWorkspaceScope: true },repos: [selectedRepo],workingDirectory: selectedRepo,workingDirectoryConfig: { path: selectedRepo, repoType: 'github' },@@ -1911,6 +1912,7 @@ describe('ConversationLifecycle actions', () => {model: expect.any(String),provider: expect.any(String),metadata: {+ executionConfig: { inheritWorkspaceScope: true },repos: [selectedRepo],workingDirectory: selectedRepo,workingDirectoryConfig: { path: selectedRepo, repoType: 'github' },@@ -2000,6 +2002,11 @@ 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 },@@ -2066,6 +2073,11 @@ describe('ConversationLifecycle actions', () => {expect.objectContaining({optimisticTopic: expect.objectContaining({metadata: {+ executionConfig: {+ boundDeviceId: deviceId,+ executionTarget: 'device',+ inheritWorkspaceScope: true,+ },workingDirectory: '/repo/default',workingDirectoryConfig: { path: '/repo/default' },},@@ -2119,6 +2131,11 @@ describe('ConversationLifecycle actions', () => {expect.objectContaining({newTopic: expect.objectContaining({metadata: {+ executionConfig: {+ boundDeviceId: deviceId,+ executionTarget: 'local',+ inheritWorkspaceScope: true,+ },workingDirectory: '/repo/lobehub',workingDirectoryConfig: { path: '/repo/lobehub' },},@@ -2171,7 +2188,15 @@ describe('ConversationLifecycle actions', () => {expect(executeGatewayAgentSpy).toHaveBeenCalledWith(expect.objectContaining({- optimisticTopic: expect.not.objectContaining({ metadata: expect.anything() }),+ optimisticTopic: expect.objectContaining({+ metadata: {+ executionConfig: {+ boundDeviceId: deviceId,+ executionTarget: 'local',+ inheritWorkspaceScope: true,+ },+ },+ }),}),);});@@ -2266,6 +2291,11 @@ 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 6fd0f60a21b..98e8884fabe 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -8,6 +8,7 @@ import { messageService } from '@/services/message';import { shareChatService } from '@/services/shareChat';import { topicService } from '@/services/topic';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import type { ChatTopic } from '@/types/topic';import type { GatewayConnection } from '../transports/gateway/gateway';import { GatewayActionImpl } from '../transports/gateway/gateway';@@ -122,6 +123,16 @@ 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'] & {@@ -176,6 +187,7 @@ function createTestAction() {describe('GatewayActionImpl', () => {beforeEach(() => {+ mockChatState.topicDetailMap = {};moveChatContextSelections.mockClear();vi.mocked(topicService.settleRunningOperation).mockResolvedValue(undefined as never);mockAgentStore.state = { activeAgentId: undefined, agentMap: {} };@@ -1915,6 +1927,40 @@ 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 f9b26b6351c..f5cec0ed6f5 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -10,6 +10,7 @@ import {import { t } from 'i18next';import { type ChatInputEditor } from '@/features/ChatInput';+import { getTopicAgencyConfig } from '@/helpers/topicExecutionConfig';import { lambdaClient } from '@/libs/trpc/client';import {type AgentInterventionSourceAction,@@ -200,11 +201,12 @@ export class ConversationControlActionImpl {const agentConfig = context.agentId? agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState()): undefined;+ const agencyConfig = getTopicAgencyConfig(agentConfig?.agencyConfig, context.topicId);return (selectRuntimeType({- boundDeviceId: agentConfig?.agencyConfig?.boundDeviceId,- executionTarget: agentConfig?.agencyConfig?.executionTarget,- heterogeneousProvider: agentConfig?.agencyConfig?.heterogeneousProvider,+ boundDeviceId: agencyConfig?.boundDeviceId,+ executionTarget: agencyConfig?.executionTarget,+ heterogeneousProvider: agencyConfig?.heterogeneousProvider,isGatewayMode: this.#get().isGatewayModeEnabled(context.agentId),}) === 'gateway');diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 004ca378a8d..2f4c31987c2 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -21,6 +21,7 @@ import {getWorkingDirEffectivePath,getWorkingDirSourcePath,resolveAgentAgencyConfig,+ snapshotTopicExecutionConfig,} from '@lobechat/types';import { generateEntityId, nanoid } from '@lobechat/utils';import { toast } from '@lobehub/ui/base-ui';@@ -42,6 +43,7 @@ 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';@@ -439,15 +441,22 @@ export class ConversationLifecycleActionImpl {const deviceOverride = agent?.workspaceId? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]: undefined;- const workspaceScoped = resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride);+ const workspaceScoped = getTopicWorkspaceScoped(+ agentConfig?.agencyConfig,+ context.topicId,+ 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 = resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {- canManage,- visibility: agent?.visibility,- workspaceId: agent?.workspaceId,- });+ const agencyConfig = getTopicAgencyConfig(+ resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {+ canManage,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ }),+ context.topicId,+ );const isGatewayMode = this.#get().isGatewayModeEnabled(agentId);// Legacy agents may only carry `model: '<cli-type>'`. Keep gateway routing// unchanged when it is available, but recover the provider before the@@ -1211,9 +1220,11 @@ export class ConversationLifecycleActionImpl {}: undefined;/** First-send persistence bypasses turnSetup, so both runtime paths must carry the effort snapshot. */- const optimisticTopicMetadata = newTopicReasoningSnapshot- ? { ...workingDirectoryMetadata, ...newTopicReasoningSnapshot }- : workingDirectoryMetadata;+ const optimisticTopicMetadata: ChatTopicMetadata = {+ ...workingDirectoryMetadata,+ ...newTopicReasoningSnapshot,+ executionConfig: snapshotTopicExecutionConfig(agencyConfig),+ };// 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 9950292c893..fe0d96ec7be 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -35,6 +35,7 @@ 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';@@ -185,6 +186,11 @@ 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 17d4c396222..6a8c577c768 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -22,6 +22,7 @@ import {getRuntimeCanManageAgent,} from '@/helpers/agentManagementAccess';import { resolveExecutionTarget, resolveWorkspaceScoped } from '@/helpers/executionTarget';+import { getTopicAgencyConfig, getTopicWorkspaceScoped } from '@/helpers/topicExecutionConfig';import {aiAgentService,type ResumeApprovalParam,@@ -97,6 +98,7 @@ const interruptGatewayTaskOrThrow = async (*/const resolveDesktopDeviceHints = async (agentId?: string,+ topicId?: string | null,): Promise<{ deviceId?: string; localDeviceId?: string }> => {if (!isDesktop || !agentId) return {};@@ -136,20 +138,27 @@ const resolveDesktopDeviceHints = async (const deviceOverride = agent?.workspaceId? userState.workspaceUserPreference.agentDeviceOverrides?.[agentId]: undefined;- const agencyConfig = resolveAgentAgencyConfig(- agentByIdSelectors.getAgencyConfigById(agentId)(agentState),- deviceOverride,- {- canManage,- visibility: agent?.visibility,- workspaceId: agent?.workspaceId,- },+ const agencyConfig = getTopicAgencyConfig(+ resolveAgentAgencyConfig(+ agentByIdSelectors.getAgencyConfigById(agentId)(agentState),+ deviceOverride,+ {+ canManage,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ },+ ),+ topicId,);const isPlatformTask = isRemoteHeterogeneousType(agencyConfig?.heterogeneousProvider?.type ?? '');const executionTarget = resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: true,isHetero: !!agencyConfig?.heterogeneousProvider,- workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),+ workspaceScoped: getTopicWorkspaceScoped(+ agencyConfig,+ topicId,+ 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@@ -161,7 +170,7 @@ const resolveDesktopDeviceHints = async (if (!info?.deviceId) return {};return isPlatformTask? { localDeviceId: info.deviceId }- : { deviceId: info.deviceId, localDeviceId: info.deviceId };+ : { deviceId: agencyConfig?.boundDeviceId ?? info.deviceId, localDeviceId: info.deviceId };} catch {return {};}@@ -665,7 +674,10 @@ export class GatewayActionImpl {? this.#get().getOperationAbortSignal(parentOperationId): undefined;- const desktopDeviceHints = await resolveDesktopDeviceHints(executionContext.agentId);+ const desktopDeviceHints = await resolveDesktopDeviceHints(+ executionContext.agentId,+ executionContext.topicId,+ );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 e8b275f9e20..3304f962414 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),+ ...resolveClientLocalSandbox(agentId, topicId),messageId: id,operationId,registerAfterCompletion,diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 81c5d98a567..b5bda6f8de5 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -3497,3 +3497,49 @@ 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 } };+ const setup = () => {+ useChatStore.setState({+ activeAgentId: 'agent-execution',+ topicDataMap: {+ [key]: {+ items: [+ {+ id: 'topic-execution',+ title: 'A',+ createdAt: 1,+ updatedAt: 1,+ favorite: false,+ metadata: previous,+ },+ ],+ currentPage: 1,+ hasMore: false,+ pageSize: 20,+ total: 1,+ },+ },+ });+ vi.spyOn(useChatStore.getState(), 'refreshTopic').mockRejectedValue(new Error('offline'));+ };+ it('restores the saved target if the mutation fails while offline', async () => {+ setup();+ vi.spyOn(topicService, 'updateTopicMetadata').mockRejectedValueOnce(new Error('offline'));+ await expect(+ useChatStore.getState().updateTopicMetadata('topic-execution', selected),+ ).rejects.toThrow('offline');+ expect(useChatStore.getState().topicDataMap[key].items[0].metadata).toEqual(previous);+ });+ it('keeps the saved selection if only revalidation fails', async () => {+ setup();+ vi.spyOn(topicService, 'updateTopicMetadata').mockResolvedValueOnce([]);+ await useChatStore.getState().updateTopicMetadata('topic-execution', selected);+ expect(useChatStore.getState().topicDataMap[key].items[0].metadata).toEqual(selected);+ });+});diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex a6814221648..6a46523f81d 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -425,7 +425,13 @@ export class ChatTopicActionImpl {updateTopicMetadata = async (id: string, metadata: Partial<ChatTopicMetadata>): Promise<void> => {const topic = topicSelectors.getTopicById(id)(this.#get());- if (!topic) return;+ if (!topic) {+ await topicService.updateTopicMetadata(id, metadata);+ await this.#get()+ .refreshTopic()+ .catch(() => undefined);+ return;+ }// Optimistic update with merged metadataconst mergedMetadata = { ...topic.metadata, ...metadata };@@ -435,8 +441,19 @@ export class ChatTopicActionImpl {value: { metadata: mergedMetadata },});- await topicService.updateTopicMetadata(id, metadata);- await this.#get().refreshTopic();+ try {+ await topicService.updateTopicMetadata(id, metadata);+ } catch (error) {+ this.#get().internal_dispatchTopic({+ type: 'updateTopic',+ id,+ value: { metadata: topic.metadata },+ });+ throw error;+ }+ await this.#get()+ .refreshTopic()+ .catch(() => undefined);};updateTopicTitle = async (id: string, title: string): Promise<void> => {