🤯 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): keep a topic on the device it already ran on (#20025)
Arvin Xu0c567014ad39
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.tsindex f2e154f2bf7..a542461d9b8 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts@@ -790,6 +790,28 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>);});+ it('dispatches a reused topic to the device it ran on after the agent moved to the sandbox', async () => {+ heteroAgentConfig.agencyConfig = {+ executionTarget: 'sandbox',+ heterogeneousProvider: { type: 'claude-code' },+ } as any;+ topicMock.findById.mockResolvedValue({+ id: 'topic-existing',+ metadata: { boundDeviceId: 'device-2', workingDirectory: '/Users/alice/work' },+ });++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-existing' },+ prompt: 'Keep going where you were',+ } as any);++ expect(mockSpawnHeteroSandbox).not.toHaveBeenCalled();+ expect(mockDispatchAgentRun).toHaveBeenCalledWith(+ expect.objectContaining({ cwd: '/Users/alice/work', deviceId: 'device-2' }),+ );+ });+it('should pass resolved Claude Code model and effort args to device dispatch', async () => {heteroAgentConfig.agencyConfig = {boundDeviceId: 'device-1',diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.tsindex d5dd579abab..a8f06fb07f9 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.topicWorkingDirectory.test.ts@@ -331,9 +331,11 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {}),);+ // An explicit request device outranks the topic's own machine.await service.execAgent({agentId: 'agent-1',appContext: { topicId: 'topic-1' },+ deviceId: DEVICE_ID,prompt: 'Hello',});@@ -343,6 +345,70 @@ describe('AiAgentService.execAgent - topic working directory binding', () => {);});+ it('runs a reused topic on the device it is bound to, not the agent default', async () => {+ // The topic ran on dev-2; the agent was switched to dev-1 afterwards. The+ // next turn must stay on dev-2, where the topic's work lives.+ mockQueryDeviceList.mockResolvedValue([+ { deviceId: DEVICE_ID, hostname: 'My Mac', online: true, platform: 'darwin' },+ { deviceId: 'dev-2', hostname: 'Other Mac', online: true, platform: 'darwin' },+ ]);+ mockTopicFindById.mockResolvedValue({ id: 'topic-1', metadata: { boundDeviceId: 'dev-2' } });+ mockGetAgentConfig.mockResolvedValue(+ createAgentConfig({+ boundDeviceId: DEVICE_ID,+ executionTarget: 'device',+ workingDirByDevice: { [DEVICE_ID]: { path: SOURCE_PATH }, 'dev-2': { path: '/repo/two' } },+ }),+ );++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ prompt: 'Hello',+ });++ expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', {+ workingDirectory: '/repo/two',+ workingDirectoryConfig: { path: '/repo/two' },+ });+ });++ it('stamps the run device on a topic that has a directory but no device yet', async () => {+ mockTopicFindById.mockResolvedValue({+ id: 'topic-1',+ metadata: {+ workingDirectory: SOURCE_PATH,+ workingDirectoryConfig: { path: SOURCE_PATH },+ },+ });+ mockGetAgentConfig.mockResolvedValue(+ createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),+ );++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ prompt: 'Hello',+ });++ expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', { boundDeviceId: DEVICE_ID });+ });++ it('pins the topic to the run device even when no directory resolves there', async () => {+ mockTopicFindById.mockResolvedValue({ id: 'topic-1', metadata: {} });+ mockGetAgentConfig.mockResolvedValue(+ createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),+ );++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ prompt: 'Hello',+ });++ expect(mockUpdateTopicMetadata).toHaveBeenCalledWith('topic-1', { boundDeviceId: DEVICE_ID });+ });+it('leaves the topic unbound when neither the agent nor the device has a directory', async () => {mockGetAgentConfig.mockResolvedValue(createAgentConfig({ boundDeviceId: DEVICE_ID, executionTarget: 'device' }),diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 4dfb633c289..de94fa39e2b 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -274,19 +274,30 @@ export class AiAgentService {* names one) — that is what lets another device skip it. A topic already* bound to a different device is left unpinned rather than given this* device's path.+ *+ * An unbound topic that already carries a cwd (the client's initial+ * metadata, or a pre-binding row) still gets the device stamped: the run+ * just used that cwd here, and the binding is what keeps later turns and the+ * device picker on this machine.*/private async bindTopicWorkingDirectory(params: BindTopicWorkingDirectoryParams): Promise<void> {const { config, currentDeviceId, currentWorkingDirectory, deviceId, topicId } = params;- if (currentWorkingDirectory || !config) return;+ if (!config) {+ // No directory resolved on this machine (no agent pick, no device+ // default), so the caller never read the topic either. The run still+ // happened here — pin an unbound topic to it all the same.+ if (deviceId) await this.stampTopicDevice(topicId, deviceId);+ return;+ }if (currentDeviceId && deviceId && currentDeviceId !== deviceId) return;- const path = getWorkingDirEffectivePath(config);- if (!path) return;+ const stampDevice = !!deviceId && !currentDeviceId;+ const path = currentWorkingDirectory ? undefined : getWorkingDirEffectivePath(config);+ if (!path && !stampDevice) return;try {await this.topicModel.updateMetadata(topicId, {- ...(deviceId && !currentDeviceId && { boundDeviceId: deviceId }),- workingDirectory: path,- workingDirectoryConfig: config,+ ...(stampDevice && { boundDeviceId: deviceId }),+ ...(path && { workingDirectory: path, workingDirectoryConfig: config }),});} catch (err) {// Metadata bookkeeping must never fail a run that is otherwise fine.@@ -294,6 +305,16 @@ export class AiAgentService {}}+ private async stampTopicDevice(topicId: string, deviceId: string): Promise<void> {+ try {+ const topic = await this.topicModel.findById(topicId);+ if (!topic || topic.metadata?.boundDeviceId) return;+ await this.topicModel.updateMetadata(topicId, { boundDeviceId: deviceId });+ } catch (err) {+ log('execAgent: stampTopicDevice failed (non-fatal): %O', err);+ }+ }+/*** Execute a single agent step against this service's runtime.*@@ -1092,7 +1113,7 @@ export class AiAgentService {parentOperationId,pinnedHeterogeneousTopicModel: turn.pinnedHeterogeneousTopicModel,requestTrigger: requestTriggerMetadata.trigger,- requestedDeviceId,+ requestedDeviceId: turn.requestedDeviceId,runAttachments,selfMessageIds,topicStartOwnerOperationId: params.topicStartOwnerOperationId,@@ -1210,7 +1231,7 @@ export class AiAgentService {operationId,parentMessageId,requestTrigger: requestTriggerMetadata.trigger,- requestedDeviceId,+ requestedDeviceId: turn.requestedDeviceId,resumeApproval,resumeApprovalPlugin,resumeApprovals,diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex 8b8e7334b8d..2c66d91c23c 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -368,6 +368,11 @@ export interface TurnSetupResult {/** Topic-pinned model + reasoning effort for a heterogeneous run (reused topics only). */pinnedHeterogeneousTopicModel?: HeterogeneousTopicPin;provider: string;+ /**+ * The request's device, or — when it named none — the device a reused topic+ * is bound to. Use this instead of the raw request value downstream.+ */+ requestedDeviceId?: string;requestTriggerMetadata: {agentDispatch?: { kind: 'callAgent'; visibility: 'internal' };steer?: true;@@ -435,10 +440,11 @@ 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`: a reused topic that already ran on a machine supplies the device+ // when the request names none (see the reuse branch below).+ let resolvedRequestedDeviceId = requestedDeviceId;+ let effectiveRequestedDeviceId = isFixedExecutionTargetSelection ? undefined : requestedDeviceId;+ let topicBoundDeviceId = isFixedDeviceTarget? agentConfig.agencyConfig?.boundDeviceId: isFixedExecutionTargetSelection? undefined@@ -614,6 +620,25 @@ export const setupTurn = async (};}+ // A conversation stays on the machine it already ran on: its cwd and CLI+ // session live there, so the agent-level target (the default for NEW+ // topics) must not move a later turn elsewhere. An explicit request device+ // (the picker's in-process preset, a task/sub-agent override) and a fixed+ // workspace target still win. `auto` opted into picking a fresh online+ // device every run, so an earlier pick never pins it.+ const topicPinnedDeviceId = canUseTopicPin ? existingTopic?.metadata?.boundDeviceId : undefined;+ if (+ !requestedDeviceId &&+ topicPinnedDeviceId &&+ !isFixedExecutionTargetSelection &&+ agentConfig.agencyConfig?.executionTarget !== 'auto'+ ) {+ resolvedRequestedDeviceId = topicPinnedDeviceId;+ effectiveRequestedDeviceId = topicPinnedDeviceId;+ topicBoundDeviceId = topicPinnedDeviceId;+ log('execAgent: routing topic %s to its bound device %s', topicId, topicPinnedDeviceId);+ }+// Re-assert the share restriction after topic overrides are applied.// Heterogeneous agents are not available for shared visitor runs.if (shareGate && isHeterogeneousAgentModelId(model)) {@@ -897,6 +922,7 @@ export const setupTurn = async (model,pinnedHeterogeneousTopicModel,provider,+ requestedDeviceId: resolvedRequestedDeviceId,requestTriggerMetadata,runAttachments,selfMessageIds,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex ae306e7664e..8ebf8607707 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -998,7 +998,11 @@"heteroAgent.executionTarget.sandbox": "Cloud Sandbox","heteroAgent.executionTarget.sandboxDesc": "Run in an ephemeral cloud sandbox","heteroAgent.executionTarget.sandboxUnsupported": "{{name}} currently runs only on a local or connected device",+ "heteroAgent.executionTarget.switchTopic.content": "This topic has been running on {{name}}, where its working directory and agent session are kept. After switching, its next turn starts a fresh session in the new environment. New topics will use this choice too.",+ "heteroAgent.executionTarget.switchTopic.ok": "Switch",+ "heteroAgent.executionTarget.switchTopic.title": "Move this topic to another environment?","heteroAgent.executionTarget.title": "Execution Environment",+ "heteroAgent.executionTarget.topicTag": "This topic","heteroAgent.executionTarget.unknownDevice": "Unknown device","heteroAgent.executionTarget.workspaceGroup": "Workspace Devices","heteroAgent.fullAccess.label": "Full access",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 3d98f18ea10..042981da60e 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -998,7 +998,11 @@"heteroAgent.executionTarget.sandbox": "云端沙箱","heteroAgent.executionTarget.sandboxDesc": "在临时云端沙箱中运行","heteroAgent.executionTarget.sandboxUnsupported": "{{name}} 目前仅支持在本地设备或已连接设备上运行",+ "heteroAgent.executionTarget.switchTopic.content": "本话题一直在「{{name}}」上运行,工作目录和会话都保存在那里。切换后,下一轮会在新环境中开启新会话;之后的新话题也会使用这个选择。",+ "heteroAgent.executionTarget.switchTopic.ok": "切换",+ "heteroAgent.executionTarget.switchTopic.title": "将本话题切换到其他执行环境?","heteroAgent.executionTarget.title": "执行环境",+ "heteroAgent.executionTarget.topicTag": "本话题","heteroAgent.executionTarget.unknownDevice": "未知设备","heteroAgent.executionTarget.workspaceGroup": "工作区设备","heteroAgent.fullAccess.label": "完全访问权限",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 7fba7b94a31..581ede99b74 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -689,6 +689,11 @@ export default {'heteroAgent.executionTarget.downloadDesktopDesc': 'Run agents with access to your computer','heteroAgent.executionTarget.downloadDesktopTitle': 'Get the desktop app','heteroAgent.executionTarget.title': 'Execution Environment',+ 'heteroAgent.executionTarget.topicTag': 'This topic',+ 'heteroAgent.executionTarget.switchTopic.content':+ 'This topic has been running on {{name}}, where its working directory and agent session are kept. After switching, its next turn starts a fresh session in the new environment. New topics will use this choice too.',+ 'heteroAgent.executionTarget.switchTopic.ok': 'Switch',+ 'heteroAgent.executionTarget.switchTopic.title': 'Move this topic to another environment?','heteroAgent.executionTarget.unknownDevice': 'Unknown device','hideForYou':"Direct message content is hidden. Please enable 'Show Direct Message Content' in settings to view.",diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsxindex 0a854380d2e..76cfba519b4 100644--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx@@ -4,7 +4,7 @@ import { isDesktop } from '@lobechat/const';import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';import type { DeviceExecutionTarget } from '@lobechat/types';import { Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';-import { Button, toast } from '@lobehub/ui/base-ui';+import { Button, confirmModal, toast } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';import {CheckIcon,@@ -32,6 +32,7 @@ import {} from '@/features/ExecutionTargetPicker';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import {+ getTopicBoundDeviceId,isHeterogeneousSandboxExecutionAvailable,isLocalSandboxEnabled,resolveExecutionTarget,@@ -41,9 +42,12 @@ import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';import { localFileService } from '@/services/electron/localFileService';import { useAgentStore } from '@/store/agent';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';import { useElectronStore } from '@/store/electron';import { formatLockedControlTooltip } from '../utils/lockedControlTooltip';+import { moveTopicToTarget } from './moveTopicToTarget';import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';const styles = createStaticStyles(({ css }) => ({@@ -324,11 +328,11 @@ interface OptionRowProps {icon: ReactNode;label: string;onClick: () => void;- tag?: ReactNode;+ tags?: ReactNode[];}const OptionRow = memo<OptionRowProps>(- ({ active, desc, disabled, extra, icon, label, onClick, tag }) => {+ ({ active, desc, disabled, extra, icon, label, onClick, tags }) => {return (<divclassName={cx(@@ -344,7 +348,11 @@ const OptionRow = memo<OptionRowProps>(<div className={styles.optionMeta}><Flexbox horizontal align={'center'} gap={6}><span className={styles.optionTitle}>{label}</span>- {tag ? <span className={styles.tag}>{tag}</span> : null}+ {tags?.map((tag, index) => (+ <span className={styles.tag} key={index}>+ {tag}+ </span>+ ))}</Flexbox>{desc ? <div className={styles.desc}>{desc}</div> : null}</div>@@ -513,28 +521,100 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {* default is written into the same setting the chip reads, so the answer to* "where is this running?" stays visible and changeable.*/- const ensureSandboxWorkingDirectory = useCallback(async () => {- if (configuredWorkingDirectory) return;-- const { path } = await localFileService.ensureSandboxWorkspace({ agentId });- // Leave it unset if the directory could not be created: pointing the fence- // at a path that does not exist would fail later and less clearly.- //- // `localTarget` because the sandbox pick is about to make `local` the- // target: the config still describes the previous one here, so without it a- // workspace member's first pick would file the path against the shared- // target (or nowhere) and the very next command would refuse again.- if (path) await commitWorkingDirectory({ path }, { localTarget: true });- }, [agentId, commitWorkingDirectory, configuredWorkingDirectory]);+ // `force`: the caller just cleared the directory, which this closure cannot+ // see yet.+ const ensureSandboxWorkingDirectory = useCallback(+ async (force = false) => {+ if (configuredWorkingDirectory && !force) return;++ const { path } = await localFileService.ensureSandboxWorkspace({ agentId });+ // Leave it unset if the directory could not be created: pointing the fence+ // at a path that does not exist would fail later and less clearly.+ //+ // `localTarget` because the sandbox pick is about to make `local` the+ // target: the config still describes the previous one here, so without it a+ // workspace member's first pick would file the path against the shared+ // target (or nowhere) and the very next command would refuse again.+ if (path) await commitWorkingDirectory({ path }, { localTarget: true });+ },+ [agentId, commitWorkingDirectory, configuredWorkingDirectory],+ );const selectExecutionTarget = useSelectExecutionTarget(agentId);++ // The machine the open topic already ran on. Its cwd and CLI session live+ // there, so the picker shows it (tagged) instead of the agent default, and+ // moving the topic elsewhere is an explicit, confirmed re-pin.+ const activeTopicId = useChatStore((s) => s.activeTopicId);+ const topicDeviceId = useChatStore((s) =>+ getTopicBoundDeviceId(topicSelectors.currentActiveTopic(s), agentId),+ );+ const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);+const handleSelect = useCallback(async (target: DeviceExecutionTarget, deviceId?: string, localSandbox?: boolean) => {setOpen(false);- if (localSandbox) await ensureSandboxWorkingDirectory();- await selectExecutionTarget(target, deviceId, { localSandbox });+ const apply = async () => {+ if (localSandbox) await ensureSandboxWorkingDirectory();+ await selectExecutionTarget(target, deviceId, { localSandbox });+ };++ const nextMachineId =+ target === 'device' ? deviceId : target === 'local' ? currentDeviceId : undefined;+ // `local` before this desktop's id resolved cannot say which machine it+ // is — leave the topic pin alone rather than unbinding it.+ const machineKnown = target !== 'local' || !!currentDeviceId;+ if (!activeTopicId || !topicDeviceId || !machineKnown || nextMachineId === topicDeviceId) {+ await apply();+ return;+ }++ const topicDevice = devices?.find((d) => d.deviceId === topicDeviceId);+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('heteroAgent.executionTarget.switchTopic.content', {+ name:+ topicDeviceId === currentDeviceId+ ? t('heteroAgent.executionTarget.local')+ : (topicDevice?.friendlyName ??+ topicDevice?.hostname ??+ t('heteroAgent.executionTarget.unknownDevice')),+ }),+ okText: t('heteroAgent.executionTarget.switchTopic.ok'),+ onOk: async () => {+ const result = await moveTopicToTarget({+ afterRepin: localSandbox ? () => ensureSandboxWorkingDirectory(true) : undefined,+ // The cwd and session are bare values that only hold on the old+ // machine — drop them with the pin so the next turn resolves fresh+ // ones where it now runs.+ repinTopic: () =>+ updateTopicMetadata(activeTopicId, {+ boundDeviceId: nextMachineId,+ heteroSessionBindingKey: undefined,+ heteroSessionBindingKeyByWorkingDirectory: undefined,+ heteroSessionId: undefined,+ heteroSessionIdByWorkingDirectory: undefined,+ workingDirectory: undefined,+ workingDirectoryConfig: undefined,+ }),+ saveTarget: () => selectExecutionTarget(target, deviceId, { localSandbox }),+ });+ // A refused/failed target save already toasted inside the hook.+ if (result === 'topic-not-saved') toast.error(t('saveAgentConfigFail', { ns: 'common' }));+ },+ title: t('heteroAgent.executionTarget.switchTopic.title'),+ });},- [ensureSandboxWorkingDirectory, selectExecutionTarget],+ [+ activeTopicId,+ currentDeviceId,+ devices,+ ensureSandboxWorkingDirectory,+ selectExecutionTarget,+ t,+ topicDeviceId,+ updateTopicMetadata,+ ],);// Setting up the backend raises an elevation prompt and creates a dedicated@@ -681,6 +761,22 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {: t('heteroAgent.executionTarget.workspaceGroup');}+ // Tag the row that runs this topic, so it reads as the conversation's own+ // machine rather than the agent default. A `fixed` target may point+ // elsewhere, in which case nothing is tagged.+ const effectiveMachineId =+ executionTarget === 'device'+ ? boundDeviceId+ : executionTarget === 'local'+ ? (currentDeviceId ?? boundDeviceId)+ : undefined;+ const topicTag =+ topicDeviceId && effectiveMachineId === topicDeviceId+ ? t('heteroAgent.executionTarget.topicTag')+ : undefined;+ const tagsFor = (active: boolean, tags: ReactNode[] = []) =>+ active && topicTag ? [...tags, topicTag] : tags;+const isActive = (target: DeviceExecutionTarget, deviceId?: string) => {if (target === 'device') return executionTarget === 'device' && boundDeviceId === deviceId;// The two local rows share one target and are told apart by the sandbox@@ -708,7 +804,6 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {icon={<ExecutionTargetIcon devicePlatform={d.platform} target={'device'} />}key={d.deviceId}label={d.friendlyName || d.hostname || d.deviceId}- tag={isCurrentMachine ? t('heteroAgent.executionTarget.gateway') : undefined}desc={<>{isCurrentMachine@@ -731,6 +826,10 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {)}</>}+ tags={tagsFor(+ isActive('device', d.deviceId),+ isCurrentMachine ? [t('heteroAgent.executionTarget.gateway')] : [],+ )}onClick={() => void handleSelect('device', d.deviceId)}/>);@@ -801,6 +900,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {icon={<ExecutionTargetIcon target={'local'} />}// 本机统一显示「本地设备」,不再带具体设备名称label={t('heteroAgent.executionTarget.local')}+ tags={tagsFor(isActive('local'))}onClick={() => void handleSelect('local', undefined, false)}/>) : null}@@ -816,6 +916,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {disabled={!canUseLocalSandbox}icon={<Icon icon={ShieldCheckIcon} size={14} />}label={t('heteroAgent.executionTarget.localSandbox')}+ tags={tagsFor(executionTarget === 'local' && localSandboxEnabled)}desc={canUseLocalSandbox? t(diff --git a/src/features/ChatInput/ControlBar/__tests__/moveTopicToTarget.test.ts b/src/features/ChatInput/ControlBar/__tests__/moveTopicToTarget.test.tsnew file mode 100644index 00000000000..865ff498e3c--- /dev/null+++ b/src/features/ChatInput/ControlBar/__tests__/moveTopicToTarget.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it, vi } from 'vitest';++import { moveTopicToTarget } from '../moveTopicToTarget';++describe('moveTopicToTarget', () => {+ it('keeps the topic untouched when the target is not saved', async () => {+ const repinTopic = vi.fn().mockResolvedValue(undefined);+ const afterRepin = vi.fn().mockResolvedValue(undefined);++ const result = await moveTopicToTarget({+ afterRepin,+ repinTopic,+ saveTarget: vi.fn().mockResolvedValue(false),+ });++ expect(result).toBe('target-not-saved');+ expect(repinTopic).not.toHaveBeenCalled();+ expect(afterRepin).not.toHaveBeenCalled();+ });++ it('saves the target before re-pinning the topic', async () => {+ const calls: string[] = [];++ const result = await moveTopicToTarget({+ afterRepin: async () => {+ calls.push('afterRepin');+ },+ repinTopic: async () => {+ calls.push('repinTopic');+ },+ saveTarget: async () => {+ calls.push('saveTarget');+ return true;+ },+ });++ expect(result).toBe('moved');+ expect(calls).toEqual(['saveTarget', 'repinTopic', 'afterRepin']);+ });++ it('reports a failed re-pin without running the follow-up', async () => {+ const afterRepin = vi.fn().mockResolvedValue(undefined);++ const result = await moveTopicToTarget({+ afterRepin,+ repinTopic: vi.fn().mockRejectedValue(new Error('network')),+ saveTarget: vi.fn().mockResolvedValue(true),+ });++ expect(result).toBe('topic-not-saved');+ expect(afterRepin).not.toHaveBeenCalled();+ });+});diff --git a/src/features/ChatInput/ControlBar/moveTopicToTarget.ts b/src/features/ChatInput/ControlBar/moveTopicToTarget.tsnew file mode 100644index 00000000000..7b156c8284f--- /dev/null+++ b/src/features/ChatInput/ControlBar/moveTopicToTarget.ts@@ -0,0 +1,34 @@+export type MoveTopicToTargetResult = 'moved' | 'target-not-saved' | 'topic-not-saved';++interface MoveTopicToTargetParams {+ /** Runs once the topic is re-pinned, e.g. giving a sandboxed run a directory. */+ afterRepin?: () => Promise<void>;+ /** Re-pin the topic and drop its old machine's directory and session. */+ repinTopic: () => Promise<void>;+ /** Persist the new execution target; resolves whether it was saved. */+ saveTarget: () => Promise<boolean>;+}++/**+ * Move a device-bound topic to another execution target.+ *+ * The target is saved first: re-pinning erases the topic's directory and CLI+ * session, so doing it before a save that is refused or fails would leave the+ * topic half-switched — stripped of its state while the target never changed.+ */+export const moveTopicToTarget = async ({+ afterRepin,+ repinTopic,+ saveTarget,+}: MoveTopicToTargetParams): Promise<MoveTopicToTargetResult> => {+ if (!(await saveTarget())) return 'target-not-saved';++ try {+ await repinTopic();+ } catch {+ return 'topic-not-saved';+ }++ await afterRepin?.();+ return 'moved';+};diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.tsindex ac8a9459c70..00efe02120a 100644--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts@@ -91,8 +91,10 @@ 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 } = useEffectiveAgencyConfig(+ agentId,+ { topicId: routeTopicId },+ );// 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/hooks/useSelectExecutionTarget.test.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.tsindex 65bc1bcf59b..99fe612af8f 100644--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts@@ -121,7 +121,7 @@ describe('useSelectExecutionTarget', () => {it('pins the given deviceId when switching to a specific device', async () => {const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));- await result.current('device', 'device-2');+ await expect(result.current('device', 'device-2')).resolves.toBe(true);expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id',@@ -315,7 +315,7 @@ describe('useSelectExecutionTarget', () => {.mockRejectedValue(new Error('save failed'));const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));- await expect(result.current('sandbox')).resolves.toBeUndefined();+ await expect(result.current('sandbox')).resolves.toBe(false);expect(toast.error).toHaveBeenCalledWith('saveAgentConfigFail');expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();@@ -327,7 +327,7 @@ describe('useSelectExecutionTarget', () => {.mockRejectedValue(new Error('save failed'));const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));- await expect(result.current('sandbox', undefined, { silent: true })).resolves.toBeUndefined();+ await expect(result.current('sandbox', undefined, { silent: true })).resolves.toBe(false);expect(toast.error).not.toHaveBeenCalled();});diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.tsindex a0e7b54a458..b924817178c 100644--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts@@ -74,6 +74,9 @@ export interface SelectExecutionTargetOptions {* 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.+ *+ * Resolves `true` only when the pick was persisted, so a caller with follow-up+ * writes (re-pinning a topic) can stop when the save was refused or failed.*/export const useSelectExecutionTarget = (agentId: string) => {const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));@@ -103,14 +106,14 @@ export const useSelectExecutionTarget = (agentId: string) => {target: DeviceExecutionTarget,deviceId?: string,options?: SelectExecutionTargetOptions,- ) => {- if (isAccessLoading) return;+ ): Promise<boolean> => {+ if (isAccessLoading) return false;// 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;+ return false;const boundDeviceId = agencyConfig?.boundDeviceId;let nextBoundDeviceId = target === 'device' ? deviceId : boundDeviceId;@@ -125,7 +128,7 @@ export const useSelectExecutionTarget = (agentId: string) => {}// Hetero agents must execute somewhere; without a resolvable local// device there is nothing to pin `local` to, so don't switch.- if (isHetero && !nextBoundDeviceId) return;+ if (isHetero && !nextBoundDeviceId) return false;}// Store the intent verbatim (`local` stays `local`), not a@@ -170,8 +173,9 @@ export const useSelectExecutionTarget = (agentId: string) => {await updateWorkspaceUserPreference({ agentDeviceOverrides: nextOverrides });} catch {if (!options?.silent) toast.error(t('saveAgentConfigFail', { ns: 'common' }));+ return false;}- return;+ return true;}const nextConfig = {@@ -198,7 +202,7 @@ export const useSelectExecutionTarget = (agentId: string) => {...(options?.silent ? { showErrorMessage: false } : {}),});} catch {- return;+ return false;}// A manager's earlier `local` pick lives in their own override and would@@ -231,8 +235,10 @@ export const useSelectExecutionTarget = (agentId: string) => {{ showErrorMessage: false },);if (!options?.silent) toast.error(t('saveAgentConfigFail', { ns: 'common' }));+ return false;}}+ return true;},[agentId,diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.tsindex 4bbf0b8efca..eb4a53a7701 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -261,6 +261,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},startOperation: mockStartOperation,associateMessageWithOperation: mockAssociateMessageWithOperation,completeOperation: mockCompleteOperation,@@ -322,6 +323,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},startOperation: mockStartOperation,associateMessageWithOperation: mockAssociateMessageWithOperation,completeOperation: mockCompleteOperation,@@ -360,6 +362,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},startOperation: mockStartOperation,associateMessageWithOperation: mockAssociateMessageWithOperation,completeOperation: mockCompleteOperation,@@ -400,6 +403,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},startOperation: mockStartOperation,associateMessageWithOperation: mockAssociateMessageWithOperation,completeOperation: mockCompleteOperation,@@ -448,6 +452,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},startOperation: mockStartOperation,associateMessageWithOperation: mockAssociateMessageWithOperation,completeOperation: mockCompleteOperation,@@ -494,6 +499,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},startOperation: mockStartOperation,associateMessageWithOperation: mockAssociateMessageWithOperation,completeOperation: mockCompleteOperation,@@ -545,6 +551,7 @@ describe('Generation Actions', () => {dbMessagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},deleteMessage: mockDeleteMessage,switchMessageBranch: mockSwitchMessageBranch,startOperation: mockStartOperation,@@ -728,6 +735,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,@@ -794,6 +802,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,@@ -865,6 +874,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},startOperation: mockStartOperation,associateMessageWithOperation: mockAssociateMessageWithOperation,@@ -910,6 +920,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,switchMessageBranch: mockSwitchMessageBranch,@@ -999,6 +1010,7 @@ describe('Generation Actions', () => {messagesMap: { [oldContextKey]: [oldUserMessage, oldAssistantMessage] },operations: {},operationsByMessage: {},+ topicDataMap: {},cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,completeOperation: mockCompleteOperation,@@ -1060,6 +1072,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,deleteMessage: vi.fn().mockResolvedValue(undefined),@@ -1115,6 +1128,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,@@ -1169,6 +1183,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,@@ -1228,6 +1243,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,@@ -1280,6 +1296,7 @@ describe('Generation Actions', () => {// has already flipped the interim regenerate op to 'cancelled'.operations: { 'test-op-id': { id: 'test-op-id', status: 'cancelled' } },operationsByMessage: {},+ topicDataMap: {},cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,@@ -1330,6 +1347,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: { 'test-op-id': { id: 'test-op-id', status: 'running' } },operationsByMessage: {},+ topicDataMap: {},dbMessages: [],cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,@@ -1378,6 +1396,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,@@ -1452,6 +1471,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},startOperation: mockStartOperation,associateMessageWithOperation: mockAssociateMessageWithOperation,@@ -1523,6 +1543,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},startOperation: mockStartOperation,associateMessageWithOperation: mockAssociateMessageWithOperation,@@ -1567,6 +1588,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},startOperation: mockStartOperation,associateMessageWithOperation: mockAssociateMessageWithOperation,@@ -1996,6 +2018,7 @@ describe('Generation Actions', () => {messagesMap: {},operations: {},operationsByMessage: {},+ topicDataMap: {},startOperation: mockStartOperation,associateMessageWithOperation: mockAssociateMessageWithOperation,completeOperation: mockCompleteOperation,diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex 18d84aed9c8..f8f02d839a8 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -21,7 +21,11 @@ import {getRuntimeCanManageAgent,} from '@/helpers/agentManagementAccess';import { resolveAgentWorkingDirectory } from '@/helpers/agentWorkingDirectory';-import { resolveWorkspaceScoped } from '@/helpers/executionTarget';+import {+ applyTopicDeviceBinding,+ getTopicBoundDeviceId,+ resolveWorkspaceScoped,+} from '@/helpers/executionTarget';import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';import { messageService } from '@/services/message';import { topicService } from '@/services/topic';@@ -124,7 +128,11 @@ export const ensureEffectiveAgencyAccess = async (agentId: string) => {});};-export const getEffectiveAgencyConfig = (agentId: string) => {+/**+ * `topic` keeps the run on the machine that conversation already ran on — see+ * `applyTopicDeviceBinding`. Omit it for agent-level decisions only.+ */+export const getEffectiveAgencyConfig = (agentId: string, topic?: ChatTopic | null) => {const agentState = getAgentStoreState();const sharedAgencyConfig = agentSelectors.getAgentConfigById(agentId)(agentState)?.agencyConfig;const agent = agentByIdSelectors.getAgentById(agentId)(agentState);@@ -147,15 +155,24 @@ export const getEffectiveAgencyConfig = (agentId: string) => {? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]: undefined;+ const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding(+ {+ agencyConfig: resolveAgentAgencyConfig(sharedAgencyConfig, deviceOverride, {+ canManage,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ }),+ workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),+ },+ getTopicBoundDeviceId(topic, agentId),+ getElectronStoreState().gatewayDeviceInfo?.deviceId,+ );+return {- agencyConfig: resolveAgentAgencyConfig(sharedAgencyConfig, deviceOverride, {- canManage,- visibility: agent?.visibility,- workspaceId: agent?.workspaceId,- }),+ agencyConfig,/** True workspace membership — stays true for the author, unlike `workspaceScoped`. */isWorkspaceAgent: !!agent?.workspaceId,- workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),+ workspaceScoped,};};@@ -189,7 +206,7 @@ export const resolveHeteroRunContext = (const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;const agentState = getAgentStoreState();const desktopContext = globalAgentContextManager.getContext();- const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(agentId);+ const { agencyConfig, workspaceScoped } = getEffectiveAgencyConfig(agentId, topic);const agentWorkingDirectory = resolveAgentWorkingDirectory({agencyConfig,currentDeviceId,@@ -468,6 +485,9 @@ const regenerateUserMessageFromSource = async (await ensureEffectiveAgencyAccess(context.agentId);const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(context.agentId,+ context.topicId+ ? topicSelectors.getTopicById(context.topicId)(useChatStore.getState())+ : undefined,);const heterogeneousProvider = agencyConfig?.heterogeneousProvider;const runtimeType = selectRuntimeType({@@ -839,6 +859,9 @@ export const generationSlice: StateCreator<await ensureEffectiveAgencyAccess(context.agentId);const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(context.agentId,+ context.topicId+ ? topicSelectors.getTopicById(context.topicId)(useChatStore.getState())+ : undefined,);const runtimeType = selectRuntimeType({boundDeviceId: agencyConfig?.boundDeviceId,@@ -930,6 +953,9 @@ export const generationSlice: StateCreator<await ensureEffectiveAgencyAccess(context.agentId);const { agencyConfig, isWorkspaceAgent, workspaceScoped } = getEffectiveAgencyConfig(context.agentId,+ context.topicId+ ? topicSelectors.getTopicById(context.topicId)(useChatStore.getState())+ : undefined,);const heterogeneousProvider = agencyConfig?.heterogeneousProvider;const runtimeType = selectRuntimeType({diff --git a/src/features/Conversation/useLocalPathReference.ts b/src/features/Conversation/useLocalPathReference.tsindex 7aa292d75a9..f43bd1ba844 100644--- a/src/features/Conversation/useLocalPathReference.ts+++ b/src/features/Conversation/useLocalPathReference.ts@@ -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 } = useEffectiveAgencyConfig(agentId, { topicId });const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);const executionTarget = resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: isDesktop,diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.tsindex 464dec159a3..7243a210a73 100644--- a/src/helpers/executionTarget.test.ts+++ b/src/helpers/executionTarget.test.ts@@ -3,10 +3,12 @@ import { RequestTrigger } from '@lobechat/types';import { describe, expect, it } from 'vitest';import {+ applyTopicDeviceBinding,canExecutionTargetReadLocalPaths,type ExecutionPlan,executionPlanToManifestExecutionEnv,executionTargetToRuntimeMode,+ getTopicBoundDeviceId,isDeviceLockedPlan,isHeterogeneousSandboxExecutionAvailable,isLocalSandboxEnabled,@@ -1332,3 +1334,106 @@ describe('canExecutionTargetReadLocalPaths', () => {expect(canExecutionTargetReadLocalPaths('none', config, 'device-1')).toBe(false);});});++describe('getTopicBoundDeviceId', () => {+ it('returns the machine an agent topic is pinned to', () => {+ expect(+ getTopicBoundDeviceId({ agentId: 'agt', metadata: { boundDeviceId: 'dev-a' } }, 'agt'),+ ).toBe('dev-a');+ });++ it('ignores another agent topic and a group topic owned by someone else', () => {+ expect(+ getTopicBoundDeviceId({ agentId: 'other', metadata: { boundDeviceId: 'dev-a' } }, 'agt'),+ ).toBeUndefined();+ expect(+ getTopicBoundDeviceId({ groupId: 'grp', metadata: { boundDeviceId: 'dev-a' } }, 'agt'),+ ).toBeUndefined();+ });++ it('returns nothing for an unbound topic', () => {+ expect(getTopicBoundDeviceId({ agentId: 'agt', metadata: {} }, 'agt')).toBeUndefined();+ expect(getTopicBoundDeviceId(undefined, 'agt')).toBeUndefined();+ });+});++describe('applyTopicDeviceBinding', () => {+ it('keeps a topic on its remote device after the agent default moved elsewhere', () => {+ const result = applyTopicDeviceBinding(+ {+ agencyConfig: cfg({ boundDeviceId: 'dev-b', executionTarget: 'device' }),+ workspaceScoped: false,+ },+ 'dev-a',+ 'this-desktop',+ );++ expect(result.agencyConfig).toMatchObject({+ boundDeviceId: 'dev-a',+ executionTarget: 'device',+ });+ });++ it('runs a topic pinned to this desktop in-process even when the agent default is the sandbox', () => {+ const result = applyTopicDeviceBinding(+ { agencyConfig: cfg({ executionTarget: 'sandbox' }), workspaceScoped: true },+ 'this-desktop',+ 'this-desktop',+ );++ expect(result).toEqual({+ agencyConfig: { boundDeviceId: 'this-desktop', executionTarget: 'local' },+ workspaceScoped: false,+ });+ });++ it('keeps the agent config when it already targets the topic machine', () => {+ const gateway = cfg({ boundDeviceId: 'this-desktop', executionTarget: 'device' });+ const local = cfg({ boundDeviceId: 'this-desktop', executionTarget: 'local' });++ expect(+ applyTopicDeviceBinding(+ { agencyConfig: gateway, workspaceScoped: false },+ 'this-desktop',+ 'this-desktop',+ ).agencyConfig,+ ).toBe(gateway);+ expect(+ applyTopicDeviceBinding(+ { agencyConfig: local, workspaceScoped: false },+ 'this-desktop',+ undefined,+ ).agencyConfig,+ ).toBe(local);+ });++ it('never overrides a fixed workspace target', () => {+ const fixed = cfg({+ boundDeviceId: 'dev-b',+ executionTarget: 'device',+ executionTargetSelectionPolicy: 'fixed',+ });++ expect(+ applyTopicDeviceBinding({ agencyConfig: fixed, workspaceScoped: true }, 'dev-a', undefined),+ ).toEqual({ agencyConfig: fixed, workspaceScoped: true });+ });++ it('leaves an auto agent to pick a fresh device', () => {+ const auto = cfg({ executionTarget: 'auto' });++ expect(+ applyTopicDeviceBinding({ agencyConfig: auto, workspaceScoped: false }, 'dev-a', undefined)+ .agencyConfig,+ ).toBe(auto);+ });++ it('leaves an unbound topic on the agent default', () => {+ const agent = cfg({ executionTarget: 'sandbox' });++ expect(+ applyTopicDeviceBinding({ agencyConfig: agent, workspaceScoped: false }, undefined, 'x')+ .agencyConfig,+ ).toBe(agent);+ });+});diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.tsindex 8392fdd5927..26ae9596dbe 100644--- a/src/helpers/executionTarget.ts+++ b/src/helpers/executionTarget.ts@@ -267,6 +267,84 @@ export const canExecutionTargetReadLocalPaths = (target === 'local' ||(target === 'device' && !!currentDeviceId && agencyConfig?.boundDeviceId === currentDeviceId);+interface TopicDeviceBindingSource {+ agentId?: string | null;+ groupId?: string | null;+ metadata?: { boundDeviceId?: string } | null;+}++/**+ * The machine a conversation is pinned to, as seen by `agentId`.+ *+ * A group topic's binding belongs to its owning agent; member agents keep+ * their own target. Mirrors the server's `canUseTopicPin` rule in turnSetup.+ */+export const getTopicBoundDeviceId = (+ topic: TopicDeviceBindingSource | null | undefined,+ agentId: string | undefined,+): string | undefined => {+ const deviceId = topic?.metadata?.boundDeviceId;+ if (!topic || !deviceId || !agentId) return;+ if (topic.agentId ? topic.agentId !== agentId : !!topic.groupId) return;+ return deviceId;+};++export interface TopicDeviceBindingResult {+ agencyConfig: LobeAgentAgencyConfig | undefined;+ workspaceScoped: boolean;+}++/**+ * Keep a conversation on the machine it already ran on.+ *+ * The agent-level target is only the default for NEW conversations: a topic+ * that ran on device A holds A's working directory and CLI session, so a later+ * turn sent after the agent was switched to device B must still go to A —+ * otherwise the topic's cwd is skipped on B and resume silently starts fresh.+ *+ * The agent config is kept as-is when it already targets the topic's machine+ * (preserving the user's `local` vs gateway transport choice). Otherwise the+ * topic's machine becomes `local` when it is this desktop and `device`+ * elsewhere. A `fixed` workspace policy is author-controlled and always wins,+ * and `auto` opted into a fresh device pick every run. Mirrors the server+ * default in turnSetup.+ *+ * The binding is this member's own run history, so it lifts `workspaceScoped`.+ */+export const applyTopicDeviceBinding = (+ {+ agencyConfig,+ workspaceScoped,+ }: { agencyConfig: LobeAgentAgencyConfig | undefined; workspaceScoped: boolean },+ topicDeviceId: string | undefined,+ currentDeviceId: string | undefined,+): TopicDeviceBindingResult => {+ const unchanged = { agencyConfig, workspaceScoped };+ const target = agencyConfig?.executionTarget;+ if (+ !topicDeviceId ||+ target === 'auto' ||+ agencyConfig?.executionTargetSelectionPolicy === 'fixed'+ )+ return unchanged;++ const alreadyOnTopicMachine =+ (target === 'device' && agencyConfig?.boundDeviceId === topicDeviceId) ||+ (target === 'local' &&+ (currentDeviceId ?? agencyConfig?.boundDeviceId) === topicDeviceId &&+ !workspaceScoped);+ if (alreadyOnTopicMachine) return unchanged;++ return {+ agencyConfig: {+ ...agencyConfig,+ boundDeviceId: topicDeviceId,+ executionTarget: topicDeviceId === currentDeviceId ? 'local' : 'device',+ },+ workspaceScoped: false,+ };+};+/*** The effective `runtimeMode` (server tool gate) from the unified execution* target.diff --git a/src/hooks/useEffectiveAgencyConfig.ts b/src/hooks/useEffectiveAgencyConfig.tsindex bf503a08f87..9cb75e7931b 100644--- a/src/hooks/useEffectiveAgencyConfig.ts+++ b/src/hooks/useEffectiveAgencyConfig.ts@@ -2,13 +2,24 @@ import type { LobeAgentAgencyConfig } from '@lobechat/types';import { resolveAgentAgencyConfig } from '@lobechat/types';import { useAgentManagementAccess } from '@/features/ResourcePermission/useAgentManagementAccess';-import { resolveWorkspaceScoped } from '@/helpers/executionTarget';+import {+ applyTopicDeviceBinding,+ getTopicBoundDeviceId,+ resolveWorkspaceScoped,+} from '@/helpers/executionTarget';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';+import { useElectronStore } from '@/store/electron';import { useUserStore } from '@/store/user';export interface UseEffectiveAgencyConfigResult {- /** Shared `agents.agencyConfig` merged with the caller's per-agent override. */+ /**+ * Shared `agents.agencyConfig` merged with the caller's per-agent override,+ * then pinned to the topic's machine when that conversation already ran on+ * one (see `applyTopicDeviceBinding`).+ */agencyConfig: LobeAgentAgencyConfig | undefined;/** Whether the execution target is ready to be shown as an effective runtime summary. */canDisplayExecutionTarget: boolean;@@ -30,6 +41,15 @@ export interface UseEffectiveAgencyConfigResult {workspaceScoped: boolean;}+export interface UseEffectiveAgencyConfigOptions {+ /**+ * The conversation whose machine binding applies. Defaults to the active+ * topic; pass `null` for agent-level surfaces (e.g. the profile editor) that+ * must show the default for new conversations.+ */+ topicId?: string | null;+}+/*** The agent's EFFECTIVE `agencyConfig` for the current caller.*@@ -50,7 +70,10 @@ export interface UseEffectiveAgencyConfigResult {* Self-populates the workspace preference cache (SWR dedupes across callers;* personal mode short-circuits without a network call).*/-export const useEffectiveAgencyConfig = (agentId?: string): UseEffectiveAgencyConfigResult => {+export const useEffectiveAgencyConfig = (+ agentId?: string,+ { topicId }: UseEffectiveAgencyConfigOptions = {},+): UseEffectiveAgencyConfigResult => {const sharedAgencyConfig = useAgentStore((s) =>agentId ? agentByIdSelectors.getAgencyConfigById(agentId)(s) : undefined,);@@ -75,11 +98,28 @@ export const useEffectiveAgencyConfig = (agentId?: string): UseEffectiveAgencyCoconst storePreference = useUserStore((s) => s.workspaceUserPreference);const preference = fetchedPreference === undefined ? storePreference : (fetchedPreference ?? {});const override = agentId ? preference.agentDeviceOverrides?.[agentId] : undefined;- const agencyConfig = resolveAgentAgencyConfig(sharedAgencyConfig, override, {+ const agentAgencyConfig = resolveAgentAgencyConfig(sharedAgencyConfig, override, {canManage: canManageAgent,visibility: agent?.visibility,workspaceId: agent?.workspaceId,});+ const activeTopicId = useChatStore((s) => s.activeTopicId);+ const bindingTopicId = topicId === undefined ? activeTopicId : topicId;+ const topicDeviceId = useChatStore((s) =>+ getTopicBoundDeviceId(+ bindingTopicId ? topicSelectors.getTopicById(bindingTopicId)(s) : undefined,+ agentId,+ ),+ );+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);+ const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding(+ {+ agencyConfig: agentAgencyConfig,+ workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, override),+ },+ topicDeviceId,+ currentDeviceId,+ );// Managers and private-agent owners also keep their `local` pick in the// per-user override, so any workspace agent must wait for the preference// fetch — not just the member-selection case.@@ -91,6 +131,6 @@ export const useEffectiveAgencyConfig = (agentId?: string): UseEffectiveAgencyCocanSelectExecutionTarget:!!agentId && !isPreferenceLoading && agencyConfig?.executionTargetSelectionPolicy !== 'fixed',isPreferenceLoading,- workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, override),+ workspaceScoped,};};diff --git a/src/hooks/useEffectiveWorkingDirectory.ts b/src/hooks/useEffectiveWorkingDirectory.tsindex f3bf27e932b..fb6d8a7f2ac 100644--- a/src/hooks/useEffectiveWorkingDirectory.ts+++ b/src/hooks/useEffectiveWorkingDirectory.ts@@ -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 } = useEffectiveAgencyConfig(agentId, { topicId });const legacyAgentWorkingDirectory = useAgentStore((s) =>agentId ? s.localAgentWorkingDirectoryMap[agentId] : undefined,);diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsxindex e197554e8ad..a5784bc206b 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx@@ -80,8 +80,10 @@ const ProfileEditor = memo(() => {const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);const heterogeneousProvider = config?.agencyConfig?.heterogeneousProvider;- const { agencyConfig: effectiveAgencyConfig, workspaceScoped } =- useEffectiveAgencyConfig(agentId);+ const { agencyConfig: effectiveAgencyConfig, workspaceScoped } = useEffectiveAgencyConfig(+ agentId,+ { topicId: null },+ );const updateHeterogeneousCommand = async (command: string) => {if (!canEdit) return;diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 0eb33d8f92f..50f3cd9cf7b 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -2216,8 +2216,10 @@ describe('ConversationLifecycle actions', () => {// `workingDirectory` is the EFFECTIVE path (the checked-out worktree the// run executes in); the config keeps the SOURCE repo, which is what- // By-Project groups on.+ // By-Project groups on. The machine is recorded with it, so the next+ // turn stays there after the agent default changes.const expectedMetadata = {+ boundDeviceId: deviceId,workingDirectory: worktreePath,workingDirectoryConfig: {git: { activeWorktree: worktreePath },@@ -2284,6 +2286,7 @@ describe('ConversationLifecycle actions', () => {expect.objectContaining({optimisticTopic: expect.objectContaining({metadata: {+ boundDeviceId: deviceId,workingDirectory: '/repo/default',workingDirectoryConfig: { path: '/repo/default' },},@@ -2337,6 +2340,7 @@ describe('ConversationLifecycle actions', () => {expect.objectContaining({newTopic: expect.objectContaining({metadata: {+ boundDeviceId: deviceId,workingDirectory: '/repo/lobehub',workingDirectoryConfig: { path: '/repo/lobehub' },},@@ -2346,6 +2350,51 @@ describe('ConversationLifecycle actions', () => {);});+ // A native agent with no directory configured is a valid setup, but the+ // topic still has to remember its machine — the client runtime creates+ // it, so no server turn would stamp the device later.+ it('should pin a client-runtime new topic to its device even without a directory', async () => {+ mockConstEnv.isDesktop = true;+ const deviceId = 'device-1';+ setupMockSelectors({+ agentConfig: {+ agencyConfig: { boundDeviceId: deviceId, executionTarget: 'local' },+ },+ });++ const sendMessageInServerSpy = vi+ .spyOn(aiChatService, 'sendMessageInServer')+ .mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ topicId: TEST_IDS.NEW_TOPIC_ID,+ topics: [],+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ const { result } = renderHook(() => useChatStore());+ act(() => {+ useChatStore.setState({ isGatewayModeEnabled: () => false });+ });++ await act(async () => {+ await result.current.sendMessage({+ context: { agentId: TEST_IDS.SESSION_ID, threadId: null, topicId: null },+ message: 'No directory here',+ });+ });++ expect(sendMessageInServerSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ newTopic: expect.objectContaining({ metadata: { boundDeviceId: deviceId } }),+ }),+ expect.any(AbortController),+ );+ });+it('should leave a plain-chat agent topic unbound', async () => {mockConstEnv.isDesktop = true;const deviceId = 'device-1';@@ -2484,6 +2533,7 @@ describe('ConversationLifecycle actions', () => {expect.objectContaining({newTopic: expect.objectContaining({metadata: {+ boundDeviceId: HETERO_DEVICE_ID,workingDirectory: '/repo/device-default',workingDirectoryConfig: { path: '/repo/device-default' },},@@ -2493,6 +2543,60 @@ describe('ConversationLifecycle actions', () => {);});+ // The topic ran on another machine, where its cwd and CLI session live.+ // An agent default of `local` must not pull its next turn onto this+ // desktop — the run goes through the gateway to the topic's machine.+ it('keeps a topic pinned to another machine off the in-process runtime', async () => {+ setupHeteroRun();+ const agentId = TEST_IDS.SESSION_ID;+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ operationId: 'gateway-op-remote-topic',+ topicId: 'remote-topic',+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ });+ act(() => {+ useChatStore.setState({+ executeGatewayAgent: executeGatewayAgentSpy,+ isGatewayModeEnabled: () => true,+ topicDataMap: {+ [topicMapKey({ agentId })]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [+ {+ agentId,+ createdAt: 0,+ id: 'remote-topic',+ metadata: {+ boundDeviceId: 'remote-device',+ workingDirectory: '/remote/repo',+ },+ title: 'Remote work',+ updatedAt: 0,+ } as any,+ ],+ pageSize: 20,+ total: 1,+ },+ },+ });+ });++ const { result } = renderHook(() => useChatStore());+ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, threadId: null, topicId: 'remote-topic' },+ message: 'Continue there',+ });+ });++ expect(executeHeterogeneousAgentMock).not.toHaveBeenCalled();+ expect(executeGatewayAgentSpy).toHaveBeenCalled();+ });+it('keeps the agent per-device pick above the device defaultCwd', async () => {setupHeteroRun({workingDirByDevice: { [HETERO_DEVICE_ID]: { path: '/repo/agent-pick' } },diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 57d6dc0737f..c5ae864035c 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -23,6 +23,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { useAiInfraStore } from '@/store/aiInfra';import { useChatStore } from '@/store/chat/store';+import { useElectronStore } from '@/store/electron';import { useUserStore } from '@/store/user';import { createGatewayEventHandler } from '../transports/gateway/gatewayEventHandler';@@ -2870,6 +2871,33 @@ describe('heterogeneousAgentExecutor DB persistence', () => {});});+ // The session now lives on this machine, so the topic is pinned here —+ // otherwise a legacy unbound topic follows whatever the agent default+ // becomes and its next turn cannot resume.+ it('pins the topic to this machine when it persists the session id', async () => {+ useElectronStore.setState({ gatewayDeviceInfo: { deviceId: 'this-desktop' } as any });+ const store = createMockStore({+ topicDataMap: { 'agent-1__main': { items: [{ id: 'topic-1', metadata: {} }] } },+ });+ store.updateTopicMetadata = vi.fn(async () => {});+ const get = vi.fn(() => store);+ mockSendPrompt.mockImplementation(() => new Promise<void>(() => {}));++ void executeHeterogeneousAgent(get, { ...defaultParams, workingDirectory: '/repo' });+ await flush();+ ipc.emitRawLine('ipc-sess-1', ccInit('cc-session-here'));+ await flush();++ expect(store.updateTopicMetadata).toHaveBeenCalledWith(+ 'topic-1',+ expect.objectContaining({+ boundDeviceId: 'this-desktop',+ heteroSessionId: 'cc-session-here',+ }),+ );+ useElectronStore.setState({ gatewayDeviceInfo: undefined });+ });+it('persists a newly reported session id even when sendPrompt exits non-zero', async () => {let topicMeta: ChatTopicMetadata = {};const store = createMockStore({diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.tsindex 4462d3e14be..0fbdccf4749 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -16,7 +16,11 @@ import {ensureAgentManagementAccess,getRuntimeCanManageAgent,} from '@/helpers/agentManagementAccess';-import { resolveWorkspaceScoped } from '@/helpers/executionTarget';+import {+ applyTopicDeviceBinding,+ getTopicBoundDeviceId,+ resolveWorkspaceScoped,+} from '@/helpers/executionTarget';import { lambdaClient } from '@/libs/trpc/client';import {type AgentInterventionSourceAction,@@ -25,7 +29,7 @@ import {} from '@/services/aiAgent';import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';-import { displayMessageSelectors } from '@/store/chat/selectors';+import { displayMessageSelectors, topicSelectors } from '@/store/chat/selectors';import {type AgentRuntimeType,selectRuntimeType,@@ -37,6 +41,7 @@ import type { Operation } from '@/store/chat/slices/operation/types';import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';import { type ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { getElectronStoreState } from '@/store/electron';import { type StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -252,11 +257,23 @@ export class ConversationControlActionImpl {const deviceOverride = agent?.workspaceId? useUserStore.getState().workspaceUserPreference.agentDeviceOverrides?.[agentId]: undefined;- const agencyConfig = resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {- canManage,- visibility: agent?.visibility,- workspaceId: agent?.workspaceId,- });+ // Same topic machine binding as sendMessage, so the resume takes the path+ // the paused run was dispatched on.+ const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding(+ {+ agencyConfig: resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {+ canManage,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ }),+ workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),+ },+ getTopicBoundDeviceId(+ context.topicId ? topicSelectors.getTopicById(context.topicId)(this.#get()) : undefined,+ agentId,+ ),+ getElectronStoreState().gatewayDeviceInfo?.deviceId,+ );const isGatewayMode = this.#get().isGatewayModeEnabled(agentId);const heterogeneousProvider =agencyConfig?.heterogeneousProvider ??@@ -271,7 +288,7 @@ export class ConversationControlActionImpl {heterogeneousProvider,isGatewayMode,isWorkspaceAgent: !!agent?.workspaceId,- workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),+ workspaceScoped,}) === 'gateway');};diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 77c12654a88..588a77ae043 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -39,6 +39,8 @@ import {resolveTargetDeviceId,} from '@/helpers/agentWorkingDirectory';import {+ applyTopicDeviceBinding,+ getTopicBoundDeviceId,resolveExecutionTarget,resolveToolMode,resolveWorkspaceScoped,@@ -459,15 +461,25 @@ export class ConversationLifecycleActionImpl {const deviceOverride = agent?.workspaceId? getUserStoreState().workspaceUserPreference.agentDeviceOverrides?.[agentId]: undefined;- const workspaceScoped = resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride);// Runtime selection must use the same per-user device override as the// switcher. A workspace-local pick is intentionally private to this member- // and is therefore safe to execute in-process on their desktop.- const agencyConfig = resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {- canManage,- visibility: agent?.visibility,- workspaceId: agent?.workspaceId,- });+ // and is therefore safe to execute in-process on their desktop. An existing+ // conversation then stays on the machine it already ran on.+ const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding(+ {+ agencyConfig: resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {+ canManage,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ }),+ workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),+ },+ getTopicBoundDeviceId(+ context.topicId ? topicSelectors.getTopicById(context.topicId)(this.#get()) : undefined,+ agentId,+ ),+ getElectronStoreState().gatewayDeviceInfo?.deviceId,+ );const isGatewayMode = this.#get().isGatewayModeEnabled(agentId);// Legacy agents may only carry `model: '<cli-type>'`. Keep gateway routing// unchanged when it is available. Recover the provider when gateway mode is@@ -1211,15 +1223,30 @@ export class ConversationLifecycleActionImpl {const resolveWorkingDirPath = isLocalCliHetero? getWorkingDirSourcePath: getWorkingDirEffectivePath;+ // A topic's cwd is a bare path that only holds on the machine it was pinned+ // on — never hand another machine's path to this run (mirrors the server's+ // `topicPinFitsDevice`).+ const topicDeviceId = existingTopic?.metadata?.boundDeviceId;+ const topicCwdMetadata =+ topicDeviceId && runCwdDeviceId && topicDeviceId !== runCwdDeviceId+ ? undefined+ : existingTopic?.metadata;const workingDirectory =- resolveWorkingDirPath(existingTopic?.metadata?.workingDirectoryConfig) ??- existingTopic?.metadata?.workingDirectory ??+ resolveWorkingDirPath(topicCwdMetadata?.workingDirectoryConfig) ??+ topicCwdMetadata?.workingDirectory ??agentWorkingDirectory;const workingDirectoryConfig =- existingTopic?.metadata?.workingDirectoryConfig ??- (existingTopic?.metadata?.workingDirectory- ? { path: existingTopic.metadata.workingDirectory }+ topicCwdMetadata?.workingDirectoryConfig ??+ (topicCwdMetadata?.workingDirectory+ ? { path: topicCwdMetadata.workingDirectory }: agentWorkingDirectoryConfig);+ // Record which machine a new conversation runs on, so its next turn — and+ // the device picker — stay on it after the agent default changes. `auto`+ // has not picked a machine yet; the server stamps the one it routes to.+ const newTopicDeviceId =+ runEffectiveTarget === 'local' || runEffectiveTarget === 'device'+ ? runCwdDeviceId+ : undefined;const pendingTopicRepos =runtimeType === 'gateway' && willCreateNewTopic && operationContext.agentId? getPendingTopicRepos(operationContext.agentId)@@ -1238,10 +1265,16 @@ export class ConversationLifecycleActionImpl {}: workingDirectory? {+ ...(newTopicDeviceId ? { boundDeviceId: newTopicDeviceId } : {}),workingDirectory,...(workingDirectoryConfig ? { workingDirectoryConfig } : {}),}- : undefined;+ : // No directory is a valid state for a native agent, but the machine+ // still has to be recorded: the client runtime creates this topic+ // itself, so no server turn would stamp it afterwards.+ newTopicDeviceId+ ? { boundDeviceId: newTopicDeviceId }+ : undefined;/** First-send persistence bypasses turnSetup, so both runtime paths must carry the effort snapshot. */const optimisticTopicMetadata = newTopicReasoningSnapshot? { ...workingDirectoryMetadata, ...newTopicReasoningSnapshot }diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 3628651c876..f50e3a1a418 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -13,6 +13,7 @@ import {} from '@lobechat/agent-gateway-client';import { isRemoteHeterogeneousType } from '@lobechat/heterogeneous-agents';import type {+ ChatTopic,ChatTopicMetadata,ChatTopicStatus,ConversationContext,@@ -27,7 +28,12 @@ import {ensureAgentManagementAccess,getRuntimeCanManageAgent,} from '@/helpers/agentManagementAccess';-import { resolveExecutionTarget, resolveWorkspaceScoped } from '@/helpers/executionTarget';+import {+ applyTopicDeviceBinding,+ getTopicBoundDeviceId,+ resolveExecutionTarget,+ resolveWorkspaceScoped,+} from '@/helpers/executionTarget';import { trackProductUsageEvent } from '@/libs/analytics/productUsageEvent';import {aiAgentService,@@ -45,6 +51,7 @@ import { topicSelectors } from '@/store/chat/selectors';import type { ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { topicMapKey } from '@/store/chat/utils/topicMapKey';+import { getElectronStoreState } from '@/store/electron';import { getFileStoreState } from '@/store/file/store';import { getServerConfigStoreState } from '@/store/serverConfig';import type { StoreSetter } from '@/store/types';@@ -136,6 +143,7 @@ const interruptGatewayTaskOrThrow = async (*/const resolveDesktopDeviceHints = async (agentId?: string,+ topic?: ChatTopic,): Promise<{ deviceId?: string; localDeviceId?: string }> => {if (!isDesktop || !agentId) return {};@@ -175,20 +183,29 @@ const resolveDesktopDeviceHints = async (const deviceOverride = agent?.workspaceId? userState.workspaceUserPreference.agentDeviceOverrides?.[agentId]: undefined;- const agencyConfig = resolveAgentAgencyConfig(- agentByIdSelectors.getAgencyConfigById(agentId)(agentState),- deviceOverride,+ // A conversation pinned to another machine must not be preset to this one —+ // the server then routes it by the topic's own binding.+ const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding({- canManage,- visibility: agent?.visibility,- workspaceId: agent?.workspaceId,+ agencyConfig: resolveAgentAgencyConfig(+ agentByIdSelectors.getAgencyConfigById(agentId)(agentState),+ deviceOverride,+ {+ canManage,+ visibility: agent?.visibility,+ workspaceId: agent?.workspaceId,+ },+ ),+ workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),},+ getTopicBoundDeviceId(topic, agentId),+ getElectronStoreState().gatewayDeviceInfo?.deviceId,);const isPlatformTask = isRemoteHeterogeneousType(agencyConfig?.heterogeneousProvider?.type ?? '');const executionTarget = resolveExecutionTarget(agencyConfig, {clientExecutionAvailable: true,isHetero: !!agencyConfig?.heterogeneousProvider,- workspaceScoped: resolveWorkspaceScoped(usesWorkspaceMemberSelection, deviceOverride),+ workspaceScoped,});// Platform hints are capability claims, not routing overrides. Always send// this desktop best-effort and let the server's authoritative execution plan@@ -925,7 +942,12 @@ export class GatewayActionImpl {? this.#get().getOperationAbortSignal(parentOperationId): undefined;- const desktopDeviceHints = await resolveDesktopDeviceHints(executionContext.agentId);+ const desktopDeviceHints = await resolveDesktopDeviceHints(+ executionContext.agentId,+ executionContext.topicId+ ? topicSelectors.getTopicById(executionContext.topicId)(this.#get())+ : undefined,+ );const userInterventionConfig = {approvalMode: toolInterventionSelectors.approvalMode(useUserStore.getState()),allowList: toolInterventionSelectors.allowList(useUserStore.getState()),diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 962d1cd4aa5..83bf0a20efc 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -81,6 +81,7 @@ import {import { type ChatStore, useChatStore } from '@/store/chat/store';import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { getElectronStoreState } from '@/store/electron';import { getUserStoreState, useUserStore } from '@/store/user';import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';@@ -913,7 +914,11 @@ export const executeHeterogeneousAgent = async (.catch(() => {}).then(async () => {const topicMetadata = getTopicMetadataById(get(), topicId);+ // The session and its cwd now live on THIS machine, so the topic is+ // pinned here — its next turn and the device picker follow it.+ const runDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;await updateTopicMetadata(topicId, {+ ...(runDeviceId ? { boundDeviceId: runDeviceId } : {}),heteroSessionBindingKey: activeSessionBindingKey,heteroSessionBindingKeyByWorkingDirectory: setHeteroSessionBindingKeyForWorkingDirectory(topicMetadata,