🤯 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(agent): persist default execution target from Agent entry (#19579)
Tsuki4dfc32233b13
diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex 782ad80019f..a49197ac6f3 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -458,6 +458,7 @@"run": "Run","save": "Save","saveAgentConfigFail": "Failed to save agent settings. Your change was not applied.",+ "saveTopicExecutionConfigFail": "Failed to save the topic execution environment. Your change was not applied.","send": "Send","serverVersionOutdated.desc": "Your client version (v{{version}}) requires a newer server version.","serverVersionOutdated.dismiss": "Continue Anyway",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex eabee66a23b..059a80e8916 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -458,6 +458,7 @@"run": "运行","save": "保存","saveAgentConfigFail": "助手设置保存失败,变更未生效",+ "saveTopicExecutionConfigFail": "话题执行环境保存失败,变更未生效","send": "发送","serverVersionOutdated.desc": "当前客户端版本(v{{version}})需要更新的服务端版本。","serverVersionOutdated.dismiss": "继续使用",diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.tsindex 8c6d7050a6c..08f474bb390 100644--- a/packages/locales/src/default/common.ts+++ b/packages/locales/src/default/common.ts@@ -331,6 +331,8 @@ export default {'copySuccess': 'Copied','createdAt': 'Created at {{time}}','saveAgentConfigFail': 'Failed to save agent settings. Your change was not applied.',+ 'saveTopicExecutionConfigFail':+ 'Failed to save the topic execution environment. Your change was not applied.','promptTransform.action': 'Refine Idea','promptTransform.actions.rewrite': 'Expand Details','promptTransform.actions.translate': 'Translate',diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.tsindex 74f335629df..56f58f627d3 100644--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts@@ -4,21 +4,54 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { useSelectExecutionTarget } from './useSelectExecutionTarget';const state = vi.hoisted(() => ({- config: {- agencyConfig: { executionTarget: 'local', boundDeviceId: 'device-a' },- canSelectExecutionTarget: true,+ access: { canManageAgent: true },+ agent: {+ agencyConfig: undefined as+ | {+ boundDeviceId?: string;+ executionTarget?: string;+ executionTargetSelectionPolicy?: 'fixed' | 'member';+ heterogeneousProvider?: { type: string };+ localSandbox?: boolean;+ }+ | undefined,+ agentMap: {} as Record<+ string,+ { visibility?: 'private' | 'public'; workspaceId?: string | null }+ >,+ isHetero: false,+ updateAgentConfigById: vi.fn(),},chat: {- activeAgentId: 'agent',+ activeAgentId: 'agent-id',activeTopicId: 'topic-a' as string | undefined,createTopic: vi.fn(),updateTopicMetadata: vi.fn(),switchTopic: vi.fn(),},- desktop: true,+ desktop: false,deviceInfo: vi.fn(),+ electron: { gatewayDeviceInfo: undefined as { deviceId?: string } | undefined },+ topicConfig: {+ agencyConfig: { executionTarget: 'local', boundDeviceId: 'device-a' } as {+ boundDeviceId?: string;+ executionTarget?: string;+ localSandbox?: boolean;+ },+ canSelectExecutionTarget: true,+ },toast: vi.fn(),+ user: {+ updateWorkspaceUserPreference: vi.fn(),+ workspaceUserPreference: {} as {+ agentDeviceOverrides?: Record<+ string,+ { boundDeviceId?: string; executionTarget?: string; localSandbox?: boolean }+ >;+ },+ },}));+vi.mock('@lobechat/const', () => ({get isDesktop() {return state.desktop;@@ -26,7 +59,24 @@ vi.mock('@lobechat/const', () => ({}));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('@/features/ResourcePermission/useAgentManagementAccess', () => ({+ useAgentManagementAccess: () => state.access,+}));+vi.mock('@/hooks/useTopicAgencyConfig', () => ({+ useTopicAgencyConfig: () => state.topicConfig,+}));+vi.mock('@/services/electron/gatewayConnection', () => ({+ gatewayConnectionService: { getDeviceInfo: () => state.deviceInfo() },+}));+vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (s: typeof state.agent) => unknown) => selector(state.agent),+}));+vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ getAgencyConfigById: () => (s: typeof state.agent) => s.agencyConfig,+ isAgentHeterogeneousById: () => (s: typeof state.agent) => s.isHetero,+ },+}));vi.mock('@/store/chat', () => ({useChatStore: Object.assign((selector: (s: typeof state.chat) => unknown) => selector(state.chat),@@ -34,99 +84,381 @@ vi.mock('@/store/chat', () => ({),}));vi.mock('@/store/electron', () => ({- useElectronStore: (selector: (s: object) => unknown) =>- selector({ gatewayDeviceInfo: undefined }),+ useElectronStore: (selector: (s: typeof state.electron) => unknown) => selector(state.electron),}));-vi.mock('@/services/electron/gatewayConnection', () => ({- gatewayConnectionService: { getDeviceInfo: state.deviceInfo },+vi.mock('@/store/user', () => ({+ useUserStore: (selector: (s: typeof state.user) => unknown) => selector(state.user),}));-describe('Topic execution selection', () => {+describe('useSelectExecutionTarget', () => {beforeEach(() => {vi.clearAllMocks();+ state.access.canManageAgent = true;+ state.agent.agencyConfig = undefined;+ state.agent.agentMap = {};+ state.agent.isHetero = false;+ state.agent.updateAgentConfigById = vi.fn();+ state.chat.activeAgentId = 'agent-id';state.chat.activeTopicId = 'topic-a';- state.chat.activeAgentId = 'agent';- state.config.canSelectExecutionTarget = true;- state.chat.createTopic.mockResolvedValue('new-topic');state.chat.updateTopicMetadata.mockResolvedValue(undefined);- });- 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({+ state.desktop = false;+ state.electron.gatewayDeviceInfo = undefined;+ state.topicConfig.agencyConfig = {executionTarget: 'local',boundDeviceId: 'device-a',- });- });- it('does not write B when device discovery finishes after switching away from A', async () => {- let resolve!: (value: { deviceId: string }) => void;- state.deviceInfo.mockReturnValue(- new Promise((r) => {- resolve = r;- }),- );- const { result } = renderHook(() => useSelectExecutionTarget('agent'));- const selection = result.current('local');- state.chat.activeTopicId = 'topic-b';- resolve({ deviceId: 'device-a' });- await selection;- expect(state.chat.updateTopicMetadata).toHaveBeenCalledWith(- 'topic-a',- expect.objectContaining({- executionConfig: expect.objectContaining({ boundDeviceId: 'device-a' }),- }),- );- });- it('creates a Topic for an explicit choice in the empty composer', async () => {- state.chat.activeTopicId = undefined;- const { result } = renderHook(() => useSelectExecutionTarget('agent'));- await result.current('none');- expect(state.chat.updateTopicMetadata).toHaveBeenCalledWith('new-topic', expect.anything());- expect(state.chat.switchTopic).toHaveBeenCalledWith('new-topic');- });- it('does not create a Topic for automatic defaults or bypass fixed policy', async () => {- state.chat.activeTopicId = undefined;- const { result } = renderHook(() => useSelectExecutionTarget('agent'));- await result.current('local', undefined, { silent: true });- state.config.canSelectExecutionTarget = false;- const fixed = renderHook(() => useSelectExecutionTarget('agent'));- await fixed.result.current('sandbox');- expect(state.chat.createTopic).not.toHaveBeenCalled();- expect(state.chat.updateTopicMetadata).not.toHaveBeenCalled();+ };+ state.topicConfig.canSelectExecutionTarget = true;+ state.user.updateWorkspaceUserPreference = vi.fn();+ state.user.workspaceUserPreference = {};});- it('surfaces a failed save without navigating to another topic', async () => {- state.chat.updateTopicMetadata.mockRejectedValue(new Error('network'));- const { result } = renderHook(() => useSelectExecutionTarget('agent'));- await result.current('sandbox');- expect(state.toast).toHaveBeenCalled();- expect(state.chat.switchTopic).not.toHaveBeenCalled();++ describe('inside an existing Topic', () => {+ it('updates only the captured Topic execution config', async () => {+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(state.chat.updateTopicMetadata).toHaveBeenCalledWith('topic-a', {+ executionConfig: {+ executionTarget: 'sandbox',+ inheritWorkspaceScope: false,+ boundDeviceId: undefined,+ localSandbox: undefined,+ localSandboxNetwork: undefined,+ },+ });+ expect(state.agent.updateAgentConfigById).not.toHaveBeenCalled();+ expect(state.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();+ expect(state.chat.createTopic).not.toHaveBeenCalled();+ });++ it('does not redirect a delayed device selection to another Topic', async () => {+ let resolve!: (value: { deviceId: string }) => void;+ state.deviceInfo.mockReturnValue(+ new Promise((r) => {+ resolve = r;+ }),+ );+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ const selection = result.current('local');+ state.chat.activeTopicId = 'topic-b';+ resolve({ deviceId: 'device-a' });+ await selection;++ expect(state.chat.updateTopicMetadata).toHaveBeenCalledWith(+ 'topic-a',+ expect.objectContaining({+ executionConfig: expect.objectContaining({ boundDeviceId: 'device-a' }),+ }),+ );+ });++ it('uses the Topic-specific failure message', async () => {+ state.chat.updateTopicMetadata.mockRejectedValue(new Error('network'));+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(state.toast).toHaveBeenCalledWith('saveTopicExecutionConfigFail');+ });});-});-it('does not reparent another Topic messages after leaving an empty composer', async () => {- state.chat.activeTopicId = undefined;- state.chat.activeAgentId = 'agent';- state.config.canSelectExecutionTarget = true;- state.chat.createTopic.mockClear();- let resolve!: (value: { deviceId: string }) => void;- state.deviceInfo.mockReturnValue(- new Promise((r) => {- resolve = r;- }),- );- const { result } = renderHook(() => useSelectExecutionTarget('agent'));- const selection = result.current('local');- state.chat.activeTopicId = 'topic-b';- resolve({ deviceId: 'device-a' });- await selection;- expect(state.chat.createTopic).not.toHaveBeenCalled();+ describe('from an Agent entry without a Topic', () => {+ beforeEach(() => {+ state.chat.activeTopicId = undefined;+ });++ it('updates a personal Agent default without creating a Topic', async () => {+ state.agent.agencyConfig = { boundDeviceId: 'device-a', executionTarget: 'local' };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(state.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ { agencyConfig: { boundDeviceId: 'device-a', executionTarget: 'sandbox' } },+ { rethrow: true },+ );+ expect(state.chat.createTopic).not.toHaveBeenCalled();+ expect(state.chat.updateTopicMetadata).not.toHaveBeenCalled();+ expect(state.chat.switchTopic).not.toHaveBeenCalled();+ });++ it('keeps automatic defaults on the Agent and suppresses their failure toast', async () => {+ state.desktop = true;+ state.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local', undefined, { silent: true });++ expect(state.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ { agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' } },+ { rethrow: true, showErrorMessage: false },+ );+ expect(state.chat.createTopic).not.toHaveBeenCalled();+ });++ it('writes a public Workspace member selection to their Agent override', async () => {+ state.access.canManageAgent = false;+ state.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'workspace-id' },+ };+ state.user.workspaceUserPreference = {+ agentDeviceOverrides: { 'other-agent': { executionTarget: 'sandbox' } },+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('device', 'workspace-device');++ expect(state.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: {+ 'agent-id': { boundDeviceId: 'workspace-device', executionTarget: 'device' },+ },+ });+ expect(state.agent.updateAgentConfigById).not.toHaveBeenCalled();+ expect(state.chat.createTopic).not.toHaveBeenCalled();+ });++ it('does not let a Workspace member override a fixed Agent default', async () => {+ state.access.canManageAgent = false;+ state.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'workspace-id' },+ };+ state.agent.agencyConfig = {+ boundDeviceId: 'fixed-device',+ executionTarget: 'device',+ executionTargetSelectionPolicy: 'fixed',+ };+ state.topicConfig.canSelectExecutionTarget = false;+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(state.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();+ expect(state.agent.updateAgentConfigById).not.toHaveBeenCalled();+ expect(state.chat.createTopic).not.toHaveBeenCalled();+ });++ it('does not save while the effective execution selector is unavailable', async () => {+ state.topicConfig.canSelectExecutionTarget = false;+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(state.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();+ expect(state.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });++ it('writes a Workspace manager shared selection to the Agent default', async () => {+ state.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'workspace-id' },+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('device', 'workspace-device');++ expect(state.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ { agencyConfig: { boundDeviceId: 'workspace-device', executionTarget: 'device' } },+ { rethrow: true },+ );+ expect(state.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();+ expect(state.chat.createTopic).not.toHaveBeenCalled();+ });++ it("keeps a Workspace manager's local machine in their Agent override", async () => {+ state.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'workspace-id' },+ };+ state.desktop = true;+ state.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('local');++ expect(state.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: {+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },+ },+ });+ expect(state.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });++ it("keeps a Workspace manager's dormant sandbox settings in their Agent override", async () => {+ state.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'workspace-id' },+ };+ state.user.workspaceUserPreference = {+ agentDeviceOverrides: { 'agent-id': { localSandbox: false } },+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox', undefined, {+ localSandbox: true,+ localSandboxNetwork: true,+ });++ expect(state.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: {+ 'agent-id': { localSandbox: true, localSandboxNetwork: true },+ },+ });+ expect(state.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });++ it("clears a Workspace manager's stale routing override after changing the shared default", async () => {+ state.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'workspace-id' },+ };+ state.user.workspaceUserPreference = {+ agentDeviceOverrides: {+ 'agent-id': {+ boundDeviceId: 'this-machine',+ executionTarget: 'local',+ localSandbox: true,+ },+ },+ };+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(state.user.updateWorkspaceUserPreference).toHaveBeenCalledWith({+ agentDeviceOverrides: { 'agent-id': { localSandbox: true } },+ });+ expect(state.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ { agencyConfig: { executionTarget: 'sandbox' } },+ { rethrow: true },+ );+ expect(state.user.updateWorkspaceUserPreference.mock.invocationCallOrder[0]).toBeLessThan(+ state.agent.updateAgentConfigById.mock.invocationCallOrder[0],+ );+ });++ it("restores a Workspace manager's routing override when the shared save fails", async () => {+ state.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'workspace-id' },+ };+ state.user.workspaceUserPreference = {+ agentDeviceOverrides: {+ 'agent-id': {+ boundDeviceId: 'this-machine',+ executionTarget: 'local',+ localSandbox: true,+ },+ },+ };+ state.agent.updateAgentConfigById.mockRejectedValue(new Error('network'));+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(state.user.updateWorkspaceUserPreference).toHaveBeenNthCalledWith(1, {+ agentDeviceOverrides: { 'agent-id': { localSandbox: true } },+ });+ expect(state.user.updateWorkspaceUserPreference).toHaveBeenNthCalledWith(2, {+ agentDeviceOverrides: {+ 'agent-id': {+ boundDeviceId: 'this-machine',+ executionTarget: 'local',+ localSandbox: true,+ },+ },+ });+ });++ it('does not change the shared default when clearing a manager override fails', async () => {+ state.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'workspace-id' },+ };+ state.user.workspaceUserPreference = {+ agentDeviceOverrides: {+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },+ },+ };+ state.user.updateWorkspaceUserPreference.mockRejectedValue(new Error('network'));+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(state.agent.updateAgentConfigById).not.toHaveBeenCalled();+ expect(state.toast).toHaveBeenCalledWith('saveAgentConfigFail');+ });++ it('serializes rapid Workspace manager shared-default selections', async () => {+ state.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'workspace-id' },+ };+ state.user.workspaceUserPreference = {+ agentDeviceOverrides: {+ 'agent-id': { boundDeviceId: 'this-machine', executionTarget: 'local' },+ },+ };+ let resolveFirst!: () => void;+ state.agent.updateAgentConfigById+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ resolveFirst = resolve;+ }),+ )+ .mockResolvedValueOnce(undefined);+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ const firstSelection = result.current('sandbox');+ await vi.waitFor(() => expect(state.agent.updateAgentConfigById).toHaveBeenCalledTimes(1));++ const secondSelection = result.current('device', 'workspace-device');+ await Promise.resolve();+ expect(state.agent.updateAgentConfigById).toHaveBeenCalledTimes(1);++ resolveFirst();+ await Promise.all([firstSelection, secondSelection]);++ expect(state.agent.updateAgentConfigById).toHaveBeenNthCalledWith(+ 2,+ 'agent-id',+ { agencyConfig: { boundDeviceId: 'workspace-device', executionTarget: 'device' } },+ { rethrow: true },+ );+ expect(state.user.updateWorkspaceUserPreference).toHaveBeenCalledTimes(2);+ });++ it('reports an Agent-setting failure when a Workspace member override cannot be saved', async () => {+ state.access.canManageAgent = false;+ state.agent.agentMap = {+ 'agent-id': { visibility: 'public', workspaceId: 'workspace-id' },+ };+ state.user.updateWorkspaceUserPreference.mockRejectedValue(new Error('network'));+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ await result.current('sandbox');++ expect(state.toast).toHaveBeenCalledWith('saveAgentConfigFail');+ expect(state.chat.createTopic).not.toHaveBeenCalled();+ });++ it('does not save after device discovery if the user has entered a Topic', async () => {+ state.desktop = true;+ let resolve!: (value: { deviceId: string }) => void;+ state.deviceInfo.mockReturnValue(+ new Promise((r) => {+ resolve = r;+ }),+ );+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));++ const selection = result.current('local');+ state.chat.activeTopicId = 'topic-b';+ resolve({ deviceId: 'device-a' });+ await selection;++ expect(state.agent.updateAgentConfigById).not.toHaveBeenCalled();+ expect(state.user.updateWorkspaceUserPreference).not.toHaveBeenCalled();+ expect(state.chat.createTopic).not.toHaveBeenCalled();+ });+ });});diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.tsindex 22084b95c7f..fc88d9fdfdd 100644--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts@@ -4,11 +4,17 @@ import { isDesktop } from '@lobechat/const';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 { useSingleton } from '@/hooks/useSingleton';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 {localSandbox?: boolean;@@ -16,54 +22,214 @@ export interface SelectExecutionTargetOptions {silent?: boolean;}-/** Capture the destination before device discovery or persistence can yield. */+/**+ * Persist an execution-target selection at the scope represented by the chat+ * input: an existing Topic owns an isolated snapshot, while the empty Agent+ * entry edits the Agent default that future Topics inherit.+ */export const useSelectExecutionTarget = (agentId: string) => {- const { agencyConfig, canSelectExecutionTarget } = useTopicAgencyConfig(agentId);+ const workspaceDefaultSaveQueueRef = useSingleton(() => ({ current: Promise.resolve() }));+ const { agencyConfig: topicAgencyConfig, canSelectExecutionTarget } =+ useTopicAgencyConfig(agentId);const topicId = useChatStore((s) => (s.activeAgentId === agentId ? s.activeTopicId : undefined));- const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);-- 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;++ // Agent-default writes deliberately use the shared row rather than the+ // effective Topic/member overlay. Workspace routing below decides whether a+ // pick belongs in that row or in this member's per-Agent preference.+ 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 updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);+ const { canManageAgent } = useAgentManagementAccess(agentId);+ const usesWorkspaceMemberSelection = isPublicWorkspaceAgent && !canManageAgent;++ const updateWorkspaceUserPreference = useUserStore((s) => s.updateWorkspaceUserPreference);+ const workspaceUserPreference = useUserStore((s) => s.workspaceUserPreference);++ const gatewayDeviceInfo = useElectronStore((s) => s.gatewayDeviceInfo);+ const currentDeviceId = isDesktop ? gatewayDeviceInfo?.deviceId : undefined;++ return useCallback(+ async (+ target: DeviceExecutionTarget,+ deviceId?: string,+ options?: SelectExecutionTargetOptions,+ ) => {+ if (!canSelectExecutionTarget) return;++ const localSandboxPatch = {+ ...(options?.localSandbox === undefined ? {} : { localSandbox: options.localSandbox }),+ ...(options?.localSandboxNetwork === undefined+ ? {}+ : { localSandboxNetwork: options.localSandboxNetwork }),+ };++ if (topicId) {+ try {+ let boundDeviceId = target === 'device' ? deviceId : undefined;+ if (target === 'local') {+ boundDeviceId =+ currentDeviceId ?? (await gatewayConnectionService.getDeviceInfo())?.deviceId;+ if (!boundDeviceId) return;+ }+ if (target === 'device' && !boundDeviceId) return;++ await useChatStore.getState().updateTopicMetadata(topicId, {+ executionConfig: {+ ...snapshotTopicExecutionConfig(topicAgencyConfig),+ inheritWorkspaceScope: false,+ boundDeviceId,+ executionTarget: target,+ ...localSandboxPatch,+ },+ });+ } catch {+ if (!options?.silent) toast.error(t('saveTopicExecutionConfigFail', { ns: 'common' }));+ }+ return;+ }++ const previousBoundDeviceId = agencyConfig?.boundDeviceId;+ let nextBoundDeviceId = target === 'device' ? deviceId : previousBoundDeviceId;if (target === 'local') {- boundDeviceId =- (isDesktop ? currentDeviceId : undefined) ??- (await gatewayConnectionService.getDeviceInfo())?.deviceId;- if (!boundDeviceId) return;+ nextBoundDeviceId = currentDeviceId;+ if (!nextBoundDeviceId) {+ try {+ nextBoundDeviceId = (await gatewayConnectionService.getDeviceInfo())?.deviceId;+ } catch {+ nextBoundDeviceId = undefined;+ }+ }+ if (isHetero && !nextBoundDeviceId) return;}- if (target === 'device' && !boundDeviceId) return;- const store = useChatStore.getState();- if (!topicId && (store.activeAgentId !== agentId || store.activeTopicId)) return;- const destination = topicId ?? (await store.createTopic(agentId));- if (!destination) return;- await useChatStore.getState().updateTopicMetadata(destination, {- executionConfig: {- ...snapshotTopicExecutionConfig(agencyConfig),- inheritWorkspaceScope: false,- boundDeviceId,- executionTarget: target,- ...(options?.localSandbox === undefined ? {} : { localSandbox: options.localSandbox }),- ...(options?.localSandboxNetwork === undefined- ? {}- : { localSandboxNetwork: options.localSandboxNetwork }),- },- });++ // The callback may have yielded while discovering the local device. Do+ // not turn an Agent-default pick into a save after the user entered a+ // Topic (or switched to another Agent).+ const chat = useChatStore.getState();+ if (chat.activeAgentId !== agentId || chat.activeTopicId) return;++ const previousOverride = workspaceUserPreference.agentDeviceOverrides?.[agentId];+ const updatesOnlyWorkspaceSandboxSettings =+ isWorkspaceAgent &&+ target !== 'local' &&+ (options?.localSandbox !== undefined || options?.localSandboxNetwork !== undefined);++ // A member selection is personal to that Workspace member. `local` is+ // also always personal, including for managers/private-Agent owners,+ // because a personal desktop device must never enter the shared row.+ // Sandbox flags are personal too, even when edited while another target+ // is active; in that case preserve the existing routing fields.if (- !topicId &&- useChatStore.getState().activeAgentId === agentId &&- !useChatStore.getState().activeTopicId+ usesWorkspaceMemberSelection ||+ (isWorkspaceAgent && target === 'local') ||+ updatesOnlyWorkspaceSandboxSettings) {- await useChatStore.getState().switchTopic(destination);+ const nextOverride = {+ ...previousOverride,+ ...(updatesOnlyWorkspaceSandboxSettings+ ? {}+ : {+ executionTarget: target,+ ...(nextBoundDeviceId ? { boundDeviceId: nextBoundDeviceId } : {}),+ }),+ ...localSandboxPatch,+ };++ try {+ await updateWorkspaceUserPreference({+ agentDeviceOverrides: { [agentId]: nextOverride },+ });+ } catch {+ if (!options?.silent) toast.error(t('saveAgentConfigFail', { ns: 'common' }));+ }+ return;}- } catch {- if (!options?.silent) toast.error(t('saveAgentConfigFail', { ns: 'common' }));- }- };++ const saveAgentDefault = async () => {+ const currentChat = useChatStore.getState();+ if (currentChat.activeAgentId !== agentId || currentChat.activeTopicId) return;++ // Clear a manager's personal routing override before changing the+ // shared default. If either write fails, other members keep the old+ // shared value; a failed shared write restores this caller's override.+ let clearedRoutingOverride = false;+ if (+ isWorkspaceAgent &&+ previousOverride &&+ (previousOverride.executionTarget !== undefined ||+ previousOverride.boundDeviceId !== undefined)+ ) {+ const { boundDeviceId: _device, executionTarget: _target, ...dormant } = previousOverride;+ try {+ await updateWorkspaceUserPreference({+ agentDeviceOverrides: { [agentId]: dormant },+ });+ clearedRoutingOverride = true;+ } catch {+ if (!options?.silent) toast.error(t('saveAgentConfigFail', { ns: 'common' }));+ return;+ }+ }++ try {+ await updateAgentConfigById(+ agentId,+ {+ agencyConfig: {+ ...agencyConfig,+ executionTarget: target,+ ...(nextBoundDeviceId ? { boundDeviceId: nextBoundDeviceId } : {}),+ ...localSandboxPatch,+ },+ },+ {+ rethrow: true,+ ...(options?.silent ? { showErrorMessage: false } : {}),+ },+ );+ } catch {+ if (clearedRoutingOverride && previousOverride) {+ try {+ await updateWorkspaceUserPreference({+ agentDeviceOverrides: { [agentId]: previousOverride },+ });+ } catch (error) {+ console.error(+ '[useSelectExecutionTarget] Failed to restore workspace override:',+ error,+ );+ }+ }+ }+ };++ if (!isWorkspaceAgent) return saveAgentDefault();++ // Shared saves must not overlap: the Agent store aborts an older update+ // for the same Agent, which would otherwise make its rollback shadow a+ // newer selection with the previous personal override.+ const save = workspaceDefaultSaveQueueRef.current.then(saveAgentDefault, saveAgentDefault);+ workspaceDefaultSaveQueueRef.current = save;+ await save;+ },+ [+ agentId,+ agencyConfig,+ canSelectExecutionTarget,+ currentDeviceId,+ isHetero,+ isWorkspaceAgent,+ topicAgencyConfig,+ topicId,+ updateAgentConfigById,+ updateWorkspaceUserPreference,+ usesWorkspaceMemberSelection,+ workspaceUserPreference,+ ],+ );};