π€― 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(terminal): open the chat terminal on the topic's device (#21223)
Lobehub Codere39477e4e3ad
diff --git a/src/features/ChatTerminal/Content.tsx b/src/features/ChatTerminal/Content.tsxindex 02516513414..7db19875213 100644--- a/src/features/ChatTerminal/Content.tsx+++ b/src/features/ChatTerminal/Content.tsx@@ -22,21 +22,17 @@ import {SquareTerminalIcon,XIcon,} from 'lucide-react';-import { memo, useEffect, useMemo, useRef } from 'react';+import { memo, useEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';-import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';-import { topicSelectors } from '@/store/chat/selectors';-import { canHostTerminal, deviceSelectors, useDeviceStore } from '@/store/device';-import { useElectronStore } from '@/store/electron';import { useGlobalStore } from '@/store/global';import SplitView from './SplitView';import type { TerminalTab } from './store';import { useChatTerminalStore } from './store';import { buildTargetOptions, LOCAL_TARGET } from './targetOptions';+import { useTerminalTarget } from './useTerminalTarget';const EMPTY_TABS: TerminalTab[] = [];@@ -97,18 +93,10 @@ const Content = memo(() => {const topicId = useChatStore((s) => s.activeTopicId);const agentId = useChatStore((s) => s.activeAgentId);- const topicWorkingDirectory = useChatStore(topicSelectors.currentTopicWorkingDirectory);- const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);- const agentWorkingDirectory = useAgentStore((s) =>- agentId- ? agentByIdSelectors.getAgentWorkingDirectoryById(agentId, currentDeviceId)(s)- : undefined,- );const toggleTerminalPanel = useGlobalStore((s) => s.toggleTerminalPanel);// Tabs are bound to the topic: sessions created here only show for this topic.const topicKey = topicId || (agentId ? `agent:${agentId}` : 'global');- const cwd = topicWorkingDirectory || agentWorkingDirectory || undefined;const tabs = useChatTerminalStore((s) => s.tabsByTopic[topicKey]) ?? EMPTY_TABS;const activeTabId = useChatTerminalStore((s) => s.activeTabIds[topicKey]);@@ -122,35 +110,22 @@ const Content = memo(() => {const closePane = useChatTerminalStore((s) => s.closePane);const setActivePane = useChatTerminalStore((s) => s.setActivePane);const setPaneFlex = useChatTerminalStore((s) => s.setPaneFlex);- const targetDeviceId = useChatTerminalStore((s) => s.deviceByTopic[topicKey]);- const setTerminalDevice = useChatTerminalStore((s) => s.setTerminalDevice);- const devices = useDeviceStore(deviceSelectors.deviceList);- // Only devices that can actually open a shell. An offline row, or one whose- // live connections are all desktop ones, answers a terminal RPC with a- // refusal β offering it would fail the session the moment it is claimed.- const targets = useMemo(() => devices.filter(canHostTerminal), [devices]);- // Desktop can always run a shell here; the web build needs a device.- const canSpawn = isDesktop || !!targetDeviceId;+ const { canSpawn, cwd, selectTarget, targetDeviceId, targets } = useTerminalTarget(+ topicKey,+ agentId || undefined,+ );const activeTab = tabs.find((tab) => tab.id === activeTabId) ?? tabs.at(-1);const prevTabCountRef = useRef(0);- // The web build has no local shell, so a topic must name a device before the- // first terminal can open. Claim the first usable one until the user picks- // another.- useEffect(() => {- if (isDesktop || targetDeviceId || targets.length === 0) return;- setTerminalDevice(topicKey, targets[0].deviceId);- }, [targets, setTerminalDevice, targetDeviceId, topicKey]);-// Open a first shell automatically when this topic has none yet and we know// where it would run. Runs on open / topic switch / target arrival only β NOT// on tab-count changes, so closing the last tab doesn't respawn a shell.useEffect(() => {prevTabCountRef.current = tabs.length;- if (tabs.length === 0 && canSpawn) void createTab(topicKey, cwd);+ if (tabs.length === 0 && canSpawn) void createTab(topicKey, cwd, targetDeviceId);// eslint-disable-next-line react-hooks/exhaustive-deps}, [topicKey, canSpawn]);@@ -177,15 +152,6 @@ const Content = memo(() => {},];- /**- * Point the topic at another machine. Existing shells keep running where they- * started, so open one β otherwise picking a device looks like it did nothing.- */- const selectTarget = (next: string) => {- setTerminalDevice(topicKey, next === LOCAL_TARGET ? undefined : next);- void createTab(topicKey, cwd);- };-const targetOptions = buildTargetOptions(targets,isDesktop ? t('terminalPanel.targetLocal') : undefined,@@ -228,7 +194,7 @@ const Content = memo(() => {loading={creating}size={'small'}title={t('terminalPanel.newTab')}- onClick={() => createTab(topicKey, cwd)}+ onClick={() => createTab(topicKey, cwd, targetDeviceId)}/><Flexbox flex={1} /><Select@@ -244,7 +210,7 @@ const Content = memo(() => {icon={SquareSplitHorizontalIcon}size={'small'}title={t('terminalPanel.split')}- onClick={() => activeTab && splitPane(topicKey, activeTab.id, cwd)}+ onClick={() => activeTab && splitPane(topicKey, activeTab.id, cwd, targetDeviceId)}/><ActionIconicon={XIcon}@@ -265,7 +231,7 @@ const Content = memo(() => {) : createError ? (<Flexbox align={'center'} flex={1} gap={8} height={'100%'} justify={'center'}><Text type={'secondary'}>{t('terminalPanel.createFailed')}</Text>- <Button size={'small'} onClick={() => createTab(topicKey, cwd)}>+ <Button onClick={() => createTab(topicKey, cwd, targetDeviceId)}>{t('retry', { ns: 'common' })}</Button></Flexbox>diff --git a/src/features/ChatTerminal/store.test.ts b/src/features/ChatTerminal/store.test.tsindex 45bf5489840..64e70b7df8c 100644--- a/src/features/ChatTerminal/store.test.ts+++ b/src/features/ChatTerminal/store.test.ts@@ -3,8 +3,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { useChatTerminalStore } from './store';import { xtermManager } from './xtermManager';-const { createSession, exitListeners, navListeners } = vi.hoisted(() => ({+const { createSession, exitListeners, navListeners, openDeviceSession } = vi.hoisted(() => ({createSession: vi.fn(),+ openDeviceSession: vi.fn(),exitListeners: [] as ((sessionId: string, exitCode: number) => void)[],navListeners: [] as ((sessionId: string, direction: -1 | 1) => void)[],}));@@ -13,6 +14,10 @@ vi.mock('@/services/electron/terminal', () => ({electronTerminalService: { createSession },}));+vi.mock('./deviceTerminal', () => ({+ DeviceTerminalSession: { open: openDeviceSession },+}));+vi.mock('./xtermManager', () => ({xtermManager: {close: vi.fn(),@@ -88,6 +93,28 @@ describe('closeOtherTabs', () => {});});+describe('createTab', () => {+ const info = { cwd: '/repo', id: 'n', pid: 1, shell: '/bin/zsh' };++ it('opens the shell on the given device', async () => {+ openDeviceSession.mockResolvedValue({ info });++ await useChatTerminalStore.getState().createTab('topic', '/repo', 'dev_sg');++ expect(openDeviceSession).toHaveBeenCalledWith('dev_sg', { cols: 80, cwd: '/repo', rows: 24 });+ expect(createSession).not.toHaveBeenCalled();+ });++ it('opens a local shell without a device', async () => {+ createSession.mockResolvedValue(info);++ await useChatTerminalStore.getState().createTab('topic', '/repo');++ expect(createSession).toHaveBeenCalledWith({ cols: 80, cwd: '/repo', rows: 24 });+ expect(openDeviceSession).not.toHaveBeenCalled();+ });+});+describe('closeTab', () => {it('kills every pane in the tab', () => {useChatTerminalStore.setState({ tabsByTopic: { topic: [tab('a', ['a', 'a2'])] } });diff --git a/src/features/ChatTerminal/store.ts b/src/features/ChatTerminal/store.tsindex ba0acf2a286..14f95fee52f 100644--- a/src/features/ChatTerminal/store.ts+++ b/src/features/ChatTerminal/store.ts@@ -39,11 +39,12 @@ interface ChatTerminalState {/** Per topic key, so a create in-flight for one topic doesn't block another */creatingByTopic: Record<string, boolean>;/**- * Device a topic's NEW terminals run on. Absent means this machine: the- * Electron main process on desktop, or no target at all on the web. Sessions- * already opened keep running where they started.+ * Device the user picked for a topic's NEW terminals; `deviceId: undefined`+ * means this machine. Absent means no pick, so the panel follows the device+ * the conversation runs on (see `resolveTerminalDevice`). Sessions already+ * opened keep running where they started.*/- deviceByTopic: Record<string, string | undefined>;+ devicePickByTopic: Record<string, { deviceId?: string } | undefined>;/** Terminal tabs per topic key β sessions created in a topic only show in that topic */tabsByTopic: Record<string, TerminalTab[]>;}@@ -52,13 +53,14 @@ interface ChatTerminalActions {closeOtherTabs: (topicKey: string, tabId: string) => void;closePane: (topicKey: string, paneId: string) => void;closeTab: (topicKey: string, tabId: string) => void;- createTab: (topicKey: string, cwd?: string) => Promise<void>;+ /** `deviceId` is where the shell runs; omitted means this machine. */+ createTab: (topicKey: string, cwd?: string, deviceId?: string) => Promise<void>;setActivePane: (topicKey: string, tabId: string, paneId: string) => void;setActiveTab: (topicKey: string, tabId: string) => void;setPaneFlex: (topicKey: string, tabId: string, flex: number[]) => void;/** Point a topic's next terminal at a device; `undefined` means this machine. */setTerminalDevice: (topicKey: string, deviceId?: string) => void;- splitPane: (topicKey: string, tabId: string, cwd?: string) => Promise<void>;+ splitPane: (topicKey: string, tabId: string, cwd?: string, deviceId?: string) => Promise<void>;}const tabTitle = (cwd: string, shell: string) => {@@ -96,14 +98,13 @@ export const useChatTerminalStore = create<ChatTerminalActions & ChatTerminalSta) => {// Shared by createTab and splitPane: both spawn a PTY and both are gated by// the same per-topic in-flight flag so a double click can't fork two shells.- const spawnSession = async (topicKey: string, cwd?: string) => {+ const spawnSession = async (topicKey: string, cwd?: string, deviceId?: string) => {if (get().creatingByTopic[topicKey]) return;set((s) => ({createErrors: { ...s.createErrors, [topicKey]: undefined },creatingByTopic: { ...s.creatingByTopic, [topicKey]: true },}));try {- const deviceId = get().deviceByTopic[topicKey];// A device session owns its own polling transport, which also registers// the sink routing this terminal's input back to that device. Without a// target the shell is local, and only the desktop app has one.@@ -190,8 +191,8 @@ export const useChatTerminalStore = create<ChatTerminalActions & ChatTerminalStacreateErrors: {},- createTab: async (topicKey, cwd) => {- const info = await spawnSession(topicKey, cwd);+ createTab: async (topicKey, cwd, deviceId) => {+ const info = await spawnSession(topicKey, cwd, deviceId);if (!info) return;const { activeTabIds, tabsByTopic } = get();set({@@ -213,7 +214,7 @@ export const useChatTerminalStore = create<ChatTerminalActions & ChatTerminalStacreatingByTopic: {},- deviceByTopic: {},+ devicePickByTopic: {},setActivePane: (topicKey, tabId, paneId) => {updateTab(topicKey, tabId, (tab) =>@@ -236,11 +237,11 @@ export const useChatTerminalStore = create<ChatTerminalActions & ChatTerminalSta},setTerminalDevice: (topicKey, deviceId) => {- set((s) => ({ deviceByTopic: { ...s.deviceByTopic, [topicKey]: deviceId } }));+ set((s) => ({ devicePickByTopic: { ...s.devicePickByTopic, [topicKey]: { deviceId } } }));},- splitPane: async (topicKey, tabId, cwd) => {- const info = await spawnSession(topicKey, cwd);+ splitPane: async (topicKey, tabId, cwd, deviceId) => {+ const info = await spawnSession(topicKey, cwd, deviceId);if (!info) return;updateTab(topicKey, tabId, (tab) => {const found = tab.panes.findIndex((pane) => pane.id === tab.activePaneId);diff --git a/src/features/ChatTerminal/targetOptions.test.ts b/src/features/ChatTerminal/targetOptions.test.tsindex 434b4005a79..227d748f2eb 100644--- a/src/features/ChatTerminal/targetOptions.test.ts+++ b/src/features/ChatTerminal/targetOptions.test.ts@@ -1,7 +1,12 @@import type { DeviceListItem } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { buildTargetOptions, LOCAL_TARGET } from './targetOptions';+import {+ buildTargetOptions,+ LOCAL_TARGET,+ resolveTerminalCwd,+ resolveTerminalDevice,+} from './targetOptions';const device = (patch: Partial<DeviceListItem>) =>({ deviceId: 'dev_1', ...patch }) as DeviceListItem;@@ -28,3 +33,98 @@ describe('buildTargetOptions', () => {expect(options.map((option) => option.label)).toEqual(['Laptop', 'host-b', 'c']);});});++describe('resolveTerminalDevice', () => {+ const sg = device({ deviceId: 'dev_sg' });+ const jp = device({ deviceId: 'dev_jp' });+ const base = { listSettled: true, localAvailable: true, targets: [jp, sg] };++ it("follows the topic's device instead of this machine", () => {+ expect(resolveTerminalDevice({ ...base, topicDeviceId: 'dev_sg' })).toEqual({+ deviceId: 'dev_sg',+ ready: true,+ });+ });++ it("follows the topic's device on the web instead of the first device", () => {+ expect(+ resolveTerminalDevice({ ...base, localAvailable: false, topicDeviceId: 'dev_sg' }),+ ).toEqual({ deviceId: 'dev_sg', ready: true });+ });++ it("lets an explicit pick override the topic's device, including this machine", () => {+ expect(+ resolveTerminalDevice({ ...base, pick: { deviceId: 'dev_jp' }, topicDeviceId: 'dev_sg' }),+ ).toEqual({ deviceId: 'dev_jp', ready: true });+ expect(resolveTerminalDevice({ ...base, pick: {}, topicDeviceId: 'dev_sg' })).toEqual({+ deviceId: undefined,+ ready: true,+ });+ });++ it("waits for the device list before falling back from the topic's device", () => {+ expect(+ resolveTerminalDevice({ ...base, listSettled: false, targets: [], topicDeviceId: 'dev_sg' }),+ ).toEqual({ ready: false });+ });++ it('waits while the execution config may still change, unless the user picked', () => {+ expect(resolveTerminalDevice({ ...base, configLoading: true })).toEqual({ ready: false });+ expect(+ resolveTerminalDevice({ ...base, configLoading: true, pick: { deviceId: 'dev_jp' } }),+ ).toEqual({ deviceId: 'dev_jp', ready: true });+ });++ it("falls back when the topic's device cannot host a shell", () => {+ expect(resolveTerminalDevice({ ...base, targets: [jp], topicDeviceId: 'dev_sg' })).toEqual({+ ready: true,+ });+ expect(+ resolveTerminalDevice({+ ...base,+ localAvailable: false,+ targets: [jp],+ topicDeviceId: 'dev_sg',+ }),+ ).toEqual({ deviceId: 'dev_jp', ready: true });+ });++ it('cannot spawn on the web without any device', () => {+ expect(resolveTerminalDevice({ ...base, localAvailable: false, targets: [] })).toEqual({+ deviceId: undefined,+ ready: false,+ });+ });+});++describe('resolveTerminalCwd', () => {+ it("starts in the conversation's directory on the machine it lives on", () => {+ expect(+ resolveTerminalCwd({+ deviceDefaultCwd: '/home/b',+ terminalDeviceId: 'dev_b',+ workingDirectory: '/repo',+ workingDirectoryDeviceId: 'dev_b',+ }),+ ).toBe('/repo');+ });++ it("uses the device's own default when the shell opens on another machine", () => {+ expect(+ resolveTerminalCwd({+ deviceDefaultCwd: '/home/a',+ terminalDeviceId: 'dev_a',+ workingDirectory: '/repo-on-b',+ workingDirectoryDeviceId: 'dev_b',+ }),+ ).toBe('/home/a');+ expect(+ resolveTerminalCwd({+ deviceDefaultCwd: null,+ terminalDeviceId: undefined,+ workingDirectory: '/repo-on-b',+ workingDirectoryDeviceId: 'dev_b',+ }),+ ).toBeUndefined();+ });+});diff --git a/src/features/ChatTerminal/targetOptions.ts b/src/features/ChatTerminal/targetOptions.tsindex 9018e9da13b..ab70eab7045 100644--- a/src/features/ChatTerminal/targetOptions.ts+++ b/src/features/ChatTerminal/targetOptions.ts@@ -22,3 +22,85 @@ export const buildTargetOptions = (value: device.deviceId,})),];++interface ResolveTerminalDeviceParams {+ /**+ * The topic's execution config may still change (e.g. a workspace member's+ * own device override is in flight), so `topicDeviceId` is not final yet.+ */+ configLoading?: boolean;+ /**+ * The server has answered the device list (or failed to). A persisted copy+ * does not count: its rows have unknown presence and read as offline, so+ * `targets` would be empty-for-now rather than the real answer.+ */+ listSettled: boolean;+ /** Whether this build has a shell of its own (the desktop app) */+ localAvailable: boolean;+ /** The user's pick in the terminal picker; `undefined` inside it means this machine */+ pick?: { deviceId?: string };+ /** Devices that can host a terminal right now */+ targets: DeviceListItem[];+ /** Remote device the conversation runs on, if any */+ topicDeviceId?: string;+}++interface ResolvedTerminalDevice {+ /** Where the next shell runs; `undefined` is this machine */+ deviceId?: string;+ /** Whether that answer is final β false while the topic's device may still show up */+ ready: boolean;+}++/**+ * Where a topic's next terminal opens. An explicit pick wins; otherwise the+ * terminal follows the device the conversation runs on, so the shell lands on+ * the same machine as the agent. A topic device that cannot host a shell+ * (offline, desktop-only connection) falls back to this machine, or on the web+ * to the first usable device.+ */+export const resolveTerminalDevice = ({+ configLoading,+ listSettled,+ localAvailable,+ pick,+ targets,+ topicDeviceId,+}: ResolveTerminalDeviceParams): ResolvedTerminalDevice => {+ if (pick) return { deviceId: pick.deviceId, ready: true };+ // A shell already opened stays where it started, so don't open the first one+ // on a device the conversation is about to stop pointing at.+ if (configLoading) return { ready: false };+ if (topicDeviceId && targets.some((device) => device.deviceId === topicDeviceId))+ return { deviceId: topicDeviceId, ready: true };+ // Hold off until the list arrives: spawning now would open the shell on the+ // fallback and leave it there once the topic's device turns up.+ if (topicDeviceId && !listSettled) return { ready: false };+ if (localAvailable) return { ready: true };+ const fallback = targets[0]?.deviceId;+ return { deviceId: fallback, ready: !!fallback };+};++interface ResolveTerminalCwdParams {+ /** A device's own default directory, for the machine the shell opens on */+ deviceDefaultCwd?: string | null;+ /** Machine the shell opens on; `undefined` is this machine without a gateway id */+ terminalDeviceId?: string;+ /** The conversation's working directory, resolved for `workingDirectoryDeviceId` */+ workingDirectory?: string;+ /** Machine the conversation's working directory lives on */+ workingDirectoryDeviceId?: string;+}++/**+ * The directory a new shell starts in. The conversation's directory only+ * exists on the machine the agent runs on; a shell opened anywhere else starts+ * in that device's own default rather than a path that may not exist there.+ */+export const resolveTerminalCwd = ({+ deviceDefaultCwd,+ terminalDeviceId,+ workingDirectory,+ workingDirectoryDeviceId,+}: ResolveTerminalCwdParams): string | undefined =>+ terminalDeviceId === workingDirectoryDeviceId ? workingDirectory : deviceDefaultCwd || undefined;diff --git a/src/features/ChatTerminal/useTerminalTarget.test.ts b/src/features/ChatTerminal/useTerminalTarget.test.tsnew file mode 100644index 00000000000..1e1a2007f7f--- /dev/null+++ b/src/features/ChatTerminal/useTerminalTarget.test.ts@@ -0,0 +1,102 @@+import type { DeviceListItem } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { create } from 'zustand';++import { useChatTerminalStore } from './store';+import { LOCAL_TARGET } from './targetOptions';+import { useTerminalTarget } from './useTerminalTarget';++const device = (deviceId: string, defaultCwd: string) =>+ ({ defaultCwd, deviceId, online: true }) as DeviceListItem;++const { deviceStore, env } = vi.hoisted(() => ({+ deviceStore: { current: undefined as any },+ env: { currentDeviceId: undefined as string | undefined, isDesktop: false },+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ get isDesktop() {+ return env.isDesktop;+ },+}));++// The topic runs on dev_b, in a directory that only exists there.+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => ({+ agencyConfig: { boundDeviceId: 'dev_b', executionTarget: 'device' },+ isPreferenceLoading: false,+ workspaceScoped: false,+ }),+}));+vi.mock('@/hooks/useEffectiveWorkingDirectory', () => ({+ useEffectiveWorkingDirectory: () => '/repo-on-b',+}));+vi.mock('@/helpers/gatewayMode', () => ({ useIsGatewayModeEnabled: () => true }));++vi.mock('@/store/electron', () => ({+ useElectronStore: (selector: (s: unknown) => unknown) =>+ selector({ gatewayDeviceInfo: { deviceId: env.currentDeviceId } }),+}));+vi.mock('@/store/device', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useDeviceStore: Object.assign(+ (selector: (s: unknown) => unknown) => deviceStore.current(selector),+ { getState: () => deviceStore.current.getState() },+ ),+}));++const createTab = vi.fn(async () => {});++beforeEach(() => {+ env.currentDeviceId = undefined;+ env.isDesktop = false;+ deviceStore.current = create(() => ({+ deviceListMap: { all: [device('dev_a', '/home/a'), device('dev_b', '/home/b')] },+ deviceListReplica: { entries: { all: { source: 'server' } } },+ useFetchDevices: () => ({ error: undefined }),+ }));+ useChatTerminalStore.setState({ createTab, devicePickByTopic: {} });+ createTab.mockClear();+});++describe('useTerminalTarget', () => {+ it("defaults to the topic's device, in the conversation's directory", () => {+ const { result } = renderHook(() => useTerminalTarget('tpc_1', 'agt_1'));++ expect(result.current).toMatchObject({+ canSpawn: true,+ cwd: '/repo-on-b',+ targetDeviceId: 'dev_b',+ });+ });++ it("opens the switched-to device's shell in that device's directory, not the old target's", () => {+ const { result } = renderHook(() => useTerminalTarget('tpc_1', 'agt_1'));++ act(() => result.current.selectTarget('dev_a'));++ expect(createTab).toHaveBeenCalledWith('tpc_1', '/home/a', 'dev_a');+ expect(result.current).toMatchObject({ cwd: '/home/a', targetDeviceId: 'dev_a' });+ });++ it("goes back to the conversation's directory when switching back to its device", () => {+ useChatTerminalStore.setState({ devicePickByTopic: { tpc_1: { deviceId: 'dev_a' } } });+ const { result } = renderHook(() => useTerminalTarget('tpc_1', 'agt_1'));++ act(() => result.current.selectTarget('dev_b'));++ expect(createTab).toHaveBeenCalledWith('tpc_1', '/repo-on-b', 'dev_b');+ });++ it('does not carry the remote directory over when switching to this computer', () => {+ env.isDesktop = true;+ env.currentDeviceId = 'dev_local';+ const { result } = renderHook(() => useTerminalTarget('tpc_1', 'agt_1'));++ act(() => result.current.selectTarget(LOCAL_TARGET));++ expect(createTab).toHaveBeenCalledWith('tpc_1', undefined, undefined);+ });+});diff --git a/src/features/ChatTerminal/useTerminalTarget.ts b/src/features/ChatTerminal/useTerminalTarget.tsnew file mode 100644index 00000000000..51ec3d99701--- /dev/null+++ b/src/features/ChatTerminal/useTerminalTarget.ts@@ -0,0 +1,106 @@+import { isDesktop } from '@lobechat/const';+import type { DeviceListItem } from '@lobechat/types';+import { useMemo } from 'react';++import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';+import { resolveExecutionTarget } from '@/helpers/executionTarget';+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';+import { canHostTerminal, deviceSelectors, useDeviceStore } from '@/store/device';+import { useElectronStore } from '@/store/electron';++import { useChatTerminalStore } from './store';+import { LOCAL_TARGET, resolveTerminalCwd, resolveTerminalDevice } from './targetOptions';++interface TerminalTarget {+ /** Whether the next shell's target is final, so the first one may open */+ canSpawn: boolean;+ /** Directory a shell opened on the current target starts in */+ cwd?: string;+ /** Point the topic at another target (`LOCAL_TARGET` for this machine) and open a shell there */+ selectTarget: (next: string) => void;+ /** Where the next shell runs; `undefined` is this machine */+ targetDeviceId?: string;+ /** Devices that can host a terminal right now */+ targets: DeviceListItem[];+}++/**+ * Where a topic's terminals open and which directory they start in.+ *+ * The default follows the device the conversation runs on β the same+ * resolution the chat input's device picker shows β so the shell lands next to+ * the agent's files. A pick in the terminal's own picker overrides it.+ */+export const useTerminalTarget = (topicKey: string, agentId?: string): TerminalTarget => {+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);+ const createTab = useChatTerminalStore((s) => s.createTab);+ const devicePick = useChatTerminalStore((s) => s.devicePickByTopic[topicKey]);+ const setTerminalDevice = useChatTerminalStore((s) => s.setTerminalDevice);++ const { agencyConfig, isPreferenceLoading, workspaceScoped } = useEffectiveAgencyConfig(agentId);+ const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);+ const executionTarget = resolveExecutionTarget(agencyConfig, {+ clientExecutionAvailable: isDesktop,+ deviceRoutingAvailable,+ isHetero: !!agencyConfig?.heterogeneousProvider?.type,+ workspaceScoped,+ });+ const boundDeviceId = executionTarget === 'device' ? agencyConfig?.boundDeviceId : undefined;+ // Bound to this very desktop: its own PTY is the same machine, minus a gateway hop.+ const topicDeviceId = isDesktop && boundDeviceId === currentDeviceId ? undefined : boundDeviceId;++ // The panel shell only fetches the list on the web; desktop needs it here to+ // follow a topic bound to a remote device.+ const { error: deviceListError } = useDeviceStore((s) => s.useFetchDevices)(true);+ const devices = useDeviceStore(deviceSelectors.deviceList);+ const deviceListConfirmed = useDeviceStore(deviceSelectors.isDeviceListConfirmed);+ // Only devices that can actually open a shell. An offline row, or one whose+ // live connections are all desktop ones, answers a terminal RPC with a+ // refusal β offering it would fail the session the moment it is claimed.+ const targets = useMemo(() => devices.filter(canHostTerminal), [devices]);+ const { deviceId: targetDeviceId, ready: canSpawn } = resolveTerminalDevice({+ configLoading: isPreferenceLoading,+ listSettled: deviceListConfirmed || !!deviceListError,+ localAvailable: isDesktop,+ pick: devicePick,+ targets,+ topicDeviceId,+ });++ const effectiveWorkingDirectory = useEffectiveWorkingDirectory(agentId);+ const workingDirectoryDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {+ workspaceScoped,+ });+ // Subscribed so `cwd` follows edits to the target's default directory.+ const targetDefaultCwd = useDeviceStore(deviceSelectors.getDeviceDefaultCwd(targetDeviceId));+ const cwdFor = (deviceId: string | undefined, deviceDefaultCwd?: string | null) =>+ resolveTerminalCwd({+ deviceDefaultCwd,+ terminalDeviceId: deviceId ?? currentDeviceId,+ workingDirectory: effectiveWorkingDirectory,+ workingDirectoryDeviceId,+ });++ /**+ * Existing shells keep running where they started, so open one on the new+ * target β otherwise picking a device looks like it did nothing.+ */+ const selectTarget = (next: string) => {+ const deviceId = next === LOCAL_TARGET ? undefined : next;+ setTerminalDevice(topicKey, deviceId);+ // `cwd` belongs to the previous target until the next render, so resolve+ // the directory for the device being switched to.+ const nextDefaultCwd = deviceSelectors.getDeviceDefaultCwd(deviceId)(useDeviceStore.getState());+ void createTab(topicKey, cwdFor(deviceId, nextDefaultCwd), deviceId);+ };++ return {+ canSpawn,+ cwd: cwdFor(targetDeviceId, targetDefaultCwd),+ selectTarget,+ targetDeviceId,+ targets,+ };+};