Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

Revert "fix(agent): persist default execution target from Agent entry" (#19594)

Tsuki86de358e9f10
diff --git a/locales/en-US/common.json b/locales/en-US/common.json
index a49197ac6f3..782ad80019f 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -458,7 +458,6 @@
"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.json
index 059a80e8916..eabee66a23b 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -458,7 +458,6 @@
"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.ts
index 08f474bb390..8c6d7050a6c 100644
--- a/packages/locales/src/default/common.ts
+++ b/packages/locales/src/default/common.ts
@@ -331,8 +331,6 @@ 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.ts
index 56f58f627d3..74f335629df 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
@@ -4,54 +4,21 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useSelectExecutionTarget } from './useSelectExecutionTarget';
const state = vi.hoisted(() => ({
- 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(),
+ config: {
+ agencyConfig: { executionTarget: 'local', boundDeviceId: 'device-a' },
+ canSelectExecutionTarget: true,
},
chat: {
- activeAgentId: 'agent-id',
+ activeAgentId: 'agent',
activeTopicId: 'topic-a' as string | undefined,
createTopic: vi.fn(),
updateTopicMetadata: vi.fn(),
switchTopic: vi.fn(),
},
- desktop: false,
+ desktop: true,
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;
@@ -59,24 +26,7 @@ vi.mock('@lobechat/const', () => ({
}));
vi.mock('@lobehub/ui/base-ui', () => ({ toast: { error: state.toast } }));
vi.mock('i18next', () => ({ t: (key: string) => key }));
-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('@/hooks/useTopicAgencyConfig', () => ({ useTopicAgencyConfig: () => state.config }));
vi.mock('@/store/chat', () => ({
useChatStore: Object.assign(
(selector: (s: typeof state.chat) => unknown) => selector(state.chat),
@@ -84,381 +34,99 @@ vi.mock('@/store/chat', () => ({
),
}));
vi.mock('@/store/electron', () => ({
- useElectronStore: (selector: (s: typeof state.electron) => unknown) => selector(state.electron),
+ useElectronStore: (selector: (s: object) => unknown) =>
+ selector({ gatewayDeviceInfo: undefined }),
}));
-vi.mock('@/store/user', () => ({
- useUserStore: (selector: (s: typeof state.user) => unknown) => selector(state.user),
+vi.mock('@/services/electron/gatewayConnection', () => ({
+ gatewayConnectionService: { getDeviceInfo: state.deviceInfo },
}));
-describe('useSelectExecutionTarget', () => {
+describe('Topic execution selection', () => {
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);
- state.desktop = false;
- state.electron.gatewayDeviceInfo = undefined;
- state.topicConfig.agencyConfig = {
+ });
+ 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',
- };
- state.topicConfig.canSelectExecutionTarget = true;
- state.user.updateWorkspaceUserPreference = vi.fn();
- state.user.workspaceUserPreference = {};
- });
-
- 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');
});
});
-
- 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();
- });
+ 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();
+ });
+ 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.ts
index fc88d9fdfdd..22084b95c7f 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
@@ -4,17 +4,11 @@ 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;
@@ -22,214 +16,54 @@ export interface SelectExecutionTargetOptions {
silent?: boolean;
}
-/**
- * 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.
- */
+/** Capture the destination before device discovery or persistence can yield. */
export const useSelectExecutionTarget = (agentId: string) => {
- const workspaceDefaultSaveQueueRef = useSingleton(() => ({ current: Promise.resolve() }));
- const { agencyConfig: topicAgencyConfig, canSelectExecutionTarget } =
- useTopicAgencyConfig(agentId);
+ const { agencyConfig, canSelectExecutionTarget } = useTopicAgencyConfig(agentId);
const topicId = useChatStore((s) => (s.activeAgentId === agentId ? s.activeTopicId : 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;
+ 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;
if (target === 'local') {
- nextBoundDeviceId = currentDeviceId;
- if (!nextBoundDeviceId) {
- try {
- nextBoundDeviceId = (await gatewayConnectionService.getDeviceInfo())?.deviceId;
- } catch {
- nextBoundDeviceId = undefined;
- }
- }
- if (isHetero && !nextBoundDeviceId) return;
+ boundDeviceId =
+ (isDesktop ? currentDeviceId : undefined) ??
+ (await gatewayConnectionService.getDeviceInfo())?.deviceId;
+ if (!boundDeviceId) return;
}
-
- // 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 (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 }),
+ },
+ });
if (
- usesWorkspaceMemberSelection ||
- (isWorkspaceAgent && target === 'local') ||
- updatesOnlyWorkspaceSandboxSettings
+ !topicId &&
+ useChatStore.getState().activeAgentId === agentId &&
+ !useChatStore.getState().activeTopicId
) {
- 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;
+ await useChatStore.getState().switchTopic(destination);
}
-
- 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,
- ],
- );
+ } catch {
+ if (!options?.silent) toast.error(t('saveAgentConfigFail', { ns: 'common' }));
+ }
+ };
};