Skip to content

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

πŸ› fix(chat-input): scope control bar topic reads and writes to the composer's own topic (#20935)

Mochaac18957b28f5
diff --git a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
index 5d9b5f63756..0e730fc2fb9 100644
--- a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx
@@ -236,6 +236,8 @@ interface BranchSwitcherProps {
placement?: 'topLeft' | 'bottomLeft' | 'bottomRight';
/** The repo the conversation is anchored to (worktrees hang off it). */
sourcePath: string;
+ /** The conversation the switch is recorded on; omitted, the global active topic. */
+ topicId?: string | null;
/** Used to route a checkout into the worktree that already holds the branch. */
worktrees: DeviceGitWorktreeListItem[];
}
@@ -254,6 +256,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
onOptimisticCheckout,
placement = 'topLeft',
sourcePath,
+ topicId,
worktrees,
children,
}) => {
@@ -262,7 +265,7 @@ const BranchSwitcher = memo<BranchSwitcherProps>(
const [search, setSearch] = useState('');
const [busyBranch, setBusyBranch] = useState<string | null>(null);
const currentRowRef = useRef<HTMLDivElement>(null);
- const switchWorktree = useSwitchWorktree({ agentId, isGithub, sourcePath });
+ const switchWorktree = useSwitchWorktree({ agentId, isGithub, sourcePath, topicId });
const {
data: branches = [],
diff --git a/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx b/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx
index a659d2c3840..4ac594b6d9d 100644
--- a/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/CloudRepoSwitcher.tsx
@@ -10,9 +10,8 @@ import { useTranslation } from 'react-i18next';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
-import { useChatStore } from '@/store/chat';
-import { getPendingTopicRepos, setPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
-import { topicSelectors } from '@/store/chat/selectors';
+
+import { useTopicRepoSelection } from './useTopicRepoSelection';
const styles = createStaticStyles(({ css }) => ({
button: css`
@@ -109,8 +108,6 @@ const CloudRepoSwitcher = memo<CloudRepoSwitcherProps>(({ agentId }) => {
const { t } = useTranslation('chat');
const [open, setOpen] = useState(false);
const { allowed: canCreateContent, reason } = usePermission('create_content');
- // Incremented to trigger re-renders when the module-singleton pending selection changes.
- const [, forceUpdate] = useState(0);
// Available repos configured on the agent
const availableRepos: string[] = useAgentStore((s) => {
@@ -122,60 +119,7 @@ const CloudRepoSwitcher = memo<CloudRepoSwitcherProps>(({ agentId }) => {
}
});
- // Repos persisted to the current topic (empty when no topic or none set)
- const topicRepos: string[] = useChatStore((s) => {
- const meta = topicSelectors.currentTopicMetadata(s);
- return meta?.repos ?? [];
- });
-
- const activeTopicId = useChatStore((s) => s.activeTopicId);
- const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);
-
- const currentWorkingDirectory = useChatStore(
- (s) => topicSelectors.currentTopicMetadata(s)?.workingDirectory,
- );
-
- const toggleRepo = useCallback(
- async (repo: string) => {
- if (!canCreateContent) return;
-
- if (!activeTopicId) {
- // No topic yet β€” buffer in the module singleton keyed by agentId.
- // gateway.ts will read and consume this when the first message creates a topic.
- const prev = getPendingTopicRepos(agentId);
- const isSelected = prev.includes(repo);
- const next = isSelected ? prev.filter((r) => r !== repo) : [...prev, repo];
- setPendingTopicRepos(agentId, next);
- forceUpdate((v) => v + 1);
- return;
- }
-
- const isSelected = topicRepos.includes(repo);
- const nextRepos = isSelected ? topicRepos.filter((r) => r !== repo) : [...topicRepos, repo];
-
- // Only set workingDirectory when it hasn't been assigned yet (first selection).
- // Once set, it stays fixed so the topic keeps its sidebar grouping.
- const patch: {
- repos: string[];
- workingDirectory?: string;
- workingDirectoryConfig?: { path: string; repoType: 'github' };
- } = { repos: nextRepos };
- if (!currentWorkingDirectory && nextRepos.length > 0) {
- patch.workingDirectory = nextRepos[0];
- patch.workingDirectoryConfig = { path: nextRepos[0], repoType: 'github' };
- }
-
- await updateTopicMetadata(activeTopicId, patch);
- },
- [
- agentId,
- activeTopicId,
- canCreateContent,
- currentWorkingDirectory,
- topicRepos,
- updateTopicMetadata,
- ],
- );
+ const { displayRepos, toggleRepo } = useTopicRepoSelection(agentId, canCreateContent);
const handleOpenChange = useCallback(
(nextOpen: boolean) => {
@@ -188,10 +132,6 @@ const CloudRepoSwitcher = memo<CloudRepoSwitcherProps>(({ agentId }) => {
if (availableRepos.length === 0) return null;
- // When a topic exists, show its persisted repos.
- // When no topic exists yet, show the pending selection from the module singleton.
- const displayRepos = activeTopicId ? topicRepos : getPendingTopicRepos(agentId);
-
// Button label
const buttonLabel =
displayRepos.length === 0
diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsx
index 45d0aaf5e29..a4e1781d76c 100644
--- a/src/features/ChatInput/ControlBar/GitStatus.tsx
+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx
@@ -123,10 +123,12 @@ interface GitStatusProps {
isGithub: boolean;
path: string;
sourcePath?: string;
+ /** The conversation the switch is recorded on; omitted, the global active topic. */
+ topicId?: string | null;
}
const GitStatus = memo<GitStatusProps>(
- ({ agentId, path, sourcePath, isGithub, deviceId, fallbackGit }) => {
+ ({ agentId, path, sourcePath, isGithub, deviceId, fallbackGit, topicId }) => {
const { t } = useTranslation('device');
// Transport (Electron IPC vs device RPC) is decided inside the service; the
// component just reads, identically for local and remote.
@@ -313,6 +315,7 @@ const GitStatus = memo<GitStatusProps>(
isGithub={isGithub}
path={path}
sourcePath={sourcePath}
+ topicId={topicId}
/>
);
}
@@ -363,6 +366,7 @@ const GitStatus = memo<GitStatusProps>(
isGithub={isGithub}
path={path}
sourcePath={sourcePath ?? path}
+ topicId={topicId}
worktrees={worktrees}
onWorktreesChange={mutateWorktrees}
/>
@@ -381,6 +385,7 @@ const GitStatus = memo<GitStatusProps>(
open={switcherOpen}
path={path}
sourcePath={sourcePath ?? path}
+ topicId={topicId}
worktrees={worktrees}
onExternalRefresh={refreshAfterSync}
onOpenChange={setSwitcherOpen}
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
index d761dcd040e..9b0c6232900 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
@@ -3,18 +3,16 @@
*/
import type * as LobechatConstModule from '@lobechat/const';
import type * as ElectronClientIpcModule from '@lobechat/electron-client-ipc';
-import type { KimiCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
-import type { HeterogeneousProviderConfig } from '@lobechat/types';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { openQuotaCalendarModal } from '@/features/AgentQuotaCalendar';
-import HeteroControlBar from '..';
import ClaudeCodeQuotaMenu from './ClaudeCodeQuotaMenu';
import CodexQuotaMenu from './CodexQuotaMenu';
import KimiCodeQuotaMenu from './KimiCodeQuotaMenu';
+import { codexSnapshot, kimiCodeSnapshot } from './testUtils';
const mockService = vi.hoisted(() => ({
consumeCodexRateLimitResetCredit: vi.fn(),
@@ -23,18 +21,6 @@ const mockService = vi.hoisted(() => ({
getKimiCodeQuota: vi.fn(),
}));
-const effectiveAgencyConfig = vi.hoisted(() => ({
- current: {
- boundDeviceId: 'personal-device' as string | undefined,
- executionTarget: 'local' as 'local' | 'device',
- heterogeneousProvider: {
- command: 'codex',
- type: 'codex',
- } as HeterogeneousProviderConfig,
- },
- workspaceScoped: false,
-}));
-
vi.mock('@lobechat/const', async (importOriginal) => ({
...(await importOriginal<typeof LobechatConstModule>()),
isDesktop: true,
@@ -45,53 +31,12 @@ vi.mock('@lobechat/electron-client-ipc', async (importOriginal) => ({
useWatchBroadcast: vi.fn(),
}));
-vi.mock('@/business/client/features/ChatInputCredits', () => ({
- default: () => <div data-testid="api-credits" />,
-}));
-
-vi.mock('@/features/ChatInput/ControlBar/WorkspaceControls', () => ({
- default: () => <div data-testid="workspace-controls" />,
-}));
-
-vi.mock('@/features/ChatInput/ControlBar/HeteroDeviceSwitcher', () => ({
- default: () => <div data-testid="hetero-device-switcher" />,
-}));
-
vi.mock('@/features/AgentQuotaCalendar', () => ({
openQuotaCalendarModal: vi.fn(),
}));
vi.mock('@/features/ChatInput/hooks/useAgentId', () => ({ useAgentId: () => 'agent-1' }));
-// Resource-access gating is out of scope for quota tests β€” keep it permissive
-// so HeteroControlBar renders its full quota UI without the ChatInput store.
-vi.mock('@/features/ChatInput/hooks/useChatInputResourceAccess', () => ({
- useChatInputResourceAccess: () => ({
- canConfigureResource: true,
- canSendMessage: true,
- canUseResource: true,
- isAccessLoading: false,
- }),
-}));
-
-vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
- useEffectiveAgencyConfig: () => ({
- agencyConfig: effectiveAgencyConfig.current,
- workspaceScoped: effectiveAgencyConfig.workspaceScoped,
- }),
-}));
-
-vi.mock('@/store/agent', () => ({
- useAgentStore: (selector: (state: Record<string, unknown>) => unknown) => selector({}),
-}));
-
-vi.mock('@/store/agent/selectors', () => ({
- agentByIdSelectors: {
- isAgentConfigLoadingById: () => () => false,
- isWorkspaceAgentById: () => () => true,
- },
-}));
-
const { confirmModalMock, toastErrorMock, toastSuccessMock } = vi.hoisted(() => ({
confirmModalMock: vi.fn(),
toastErrorMock: vi.fn(),
@@ -273,41 +218,7 @@ const waitForQuotaIdle = async () => {
});
};
-const codexSnapshot = (
- overrides: Partial<ElectronClientIpcModule.CodexQuotaSnapshot> = {},
-): ElectronClientIpcModule.CodexQuotaSnapshot => ({
- error: null,
- provider: 'codex',
- rateLimitResetCredits: null,
- session: null,
- status: 'ok',
- updatedAt: Date.now(),
- weekly: null,
- ...overrides,
-});
-
-const kimiCodeSnapshot = (
- overrides: Partial<KimiCodeQuotaSnapshot> = {},
-): KimiCodeQuotaSnapshot => ({
- error: null,
- extraUsage: null,
- monthly: null,
- monthlyCode: null,
- provider: 'kimi-code',
- session: null,
- status: 'ok',
- updatedAt: Date.now(),
- weekly: null,
- ...overrides,
-});
-
beforeEach(() => {
- effectiveAgencyConfig.current = {
- boundDeviceId: 'personal-device',
- executionTarget: 'local',
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- };
- effectiveAgencyConfig.workspaceScoped = false;
confirmModalMock.mockReset();
mockService.consumeCodexRateLimitResetCredit.mockReset();
mockService.getClaudeCodeQuota.mockReset();
@@ -328,138 +239,6 @@ beforeEach(() => {
vi.mocked(openQuotaCalendarModal).mockClear();
});
-describe('HeteroControlBar', () => {
- it('shows local Codex quota for a workspace member local-device override', async () => {
- mockService.getCodexQuota.mockResolvedValue(
- codexSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
- );
-
- render(<HeteroControlBar />);
-
- expect(
- await screen.findByRole('button', { name: 'heteroAgent.codexQuota.tooltip' }),
- ).toBeTruthy();
- expect(screen.queryByTestId('api-credits')).toBeNull();
- expect(mockService.getCodexQuota).toHaveBeenCalledWith({ command: 'codex', env: undefined });
- });
-
- it('shows Codex quota sampled by a bound remote device', async () => {
- effectiveAgencyConfig.current = {
- boundDeviceId: 'remote-device',
- executionTarget: 'device',
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- };
- mockLambdaCodexQuota.mockResolvedValue(
- codexSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
- );
-
- render(<HeteroControlBar />);
-
- expect(
- await screen.findByRole('button', { name: 'heteroAgent.codexQuota.tooltip' }),
- ).toBeTruthy();
- expect(mockLambdaCodexQuota).toHaveBeenCalledWith({
- command: 'codex',
- deviceId: 'remote-device',
- env: undefined,
- });
- expect(mockService.getCodexQuota).not.toHaveBeenCalled();
- });
-
- it('shows remote quota for a workspace shared-device fallback', async () => {
- effectiveAgencyConfig.current = {
- boundDeviceId: 'workspace-device',
- executionTarget: 'local',
- heterogeneousProvider: { command: 'codex', type: 'codex' },
- };
- effectiveAgencyConfig.workspaceScoped = true;
- mockLambdaCodexQuota.mockResolvedValue(
- codexSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
- );
-
- render(<HeteroControlBar />);
-
- expect(
- await screen.findByRole('button', { name: 'heteroAgent.codexQuota.tooltip' }),
- ).toBeTruthy();
- expect(mockLambdaCodexQuota).toHaveBeenCalledWith({
- command: 'codex',
- deviceId: 'workspace-device',
- env: undefined,
- });
- expect(mockService.getCodexQuota).not.toHaveBeenCalled();
- });
-
- it('shows platform credits instead of Codex quota in API mode', () => {
- effectiveAgencyConfig.current = {
- boundDeviceId: 'personal-device',
- executionTarget: 'local',
- heterogeneousProvider: { authMode: 'api', command: 'codex', type: 'codex' },
- };
-
- render(<HeteroControlBar />);
-
- expect(screen.getByTestId('api-credits')).toBeTruthy();
- expect(screen.queryByRole('button', { name: 'heteroAgent.codexQuota.tooltip' })).toBeNull();
- expect(mockService.getCodexQuota).not.toHaveBeenCalled();
- });
-
- it('shows platform credits instead of Claude Code quota in API mode', () => {
- effectiveAgencyConfig.current = {
- boundDeviceId: 'personal-device',
- executionTarget: 'local',
- heterogeneousProvider: { authMode: 'api', type: 'claude-code' },
- };
-
- render(<HeteroControlBar />);
-
- expect(screen.getByTestId('api-credits')).toBeTruthy();
- expect(screen.queryByRole('button', { name: 'heteroAgent.claudeQuota.tooltip' })).toBeNull();
- expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
- });
-
- it('shows local Kimi Code quota for a local execution target', async () => {
- effectiveAgencyConfig.current = {
- boundDeviceId: 'personal-device',
- executionTarget: 'local',
- heterogeneousProvider: { command: 'kimi', type: 'kimi-code' },
- };
- mockService.getKimiCodeQuota.mockResolvedValue(
- kimiCodeSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
- );
-
- render(<HeteroControlBar />);
-
- expect(
- await screen.findByRole('button', { name: 'heteroAgent.kimiCodeQuota.tooltip' }),
- ).toBeTruthy();
- expect(mockService.getKimiCodeQuota).toHaveBeenCalledWith({ env: undefined });
- expect(mockService.getCodexQuota).not.toHaveBeenCalled();
- });
-
- it('shows Kimi Code quota sampled by a bound remote device', async () => {
- effectiveAgencyConfig.current = {
- boundDeviceId: 'remote-device',
- executionTarget: 'device',
- heterogeneousProvider: { command: 'kimi', type: 'kimi-code' },
- };
- mockLambdaKimiCodeQuota.mockResolvedValue(
- kimiCodeSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
- );
-
- render(<HeteroControlBar />);
-
- expect(
- await screen.findByRole('button', { name: 'heteroAgent.kimiCodeQuota.tooltip' }),
- ).toBeTruthy();
- expect(mockLambdaKimiCodeQuota).toHaveBeenCalledWith({
- deviceId: 'remote-device',
- env: undefined,
- });
- expect(mockService.getKimiCodeQuota).not.toHaveBeenCalled();
- });
-});
-
describe('KimiCodeQuotaMenu', () => {
it('renders all four windows and the Extra Usage footer from the snapshot', async () => {
mockService.getKimiCodeQuota.mockResolvedValue(
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/testUtils.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/testUtils.ts
new file mode 100644
index 00000000000..a22ae52f16e
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/testUtils.ts
@@ -0,0 +1,30 @@
+import type * as ElectronClientIpcModule from '@lobechat/electron-client-ipc';
+import type { KimiCodeQuotaSnapshot } from '@lobechat/heterogeneous-agents/quota';
+
+export const codexSnapshot = (
+ overrides: Partial<ElectronClientIpcModule.CodexQuotaSnapshot> = {},
+): ElectronClientIpcModule.CodexQuotaSnapshot => ({
+ error: null,
+ provider: 'codex',
+ rateLimitResetCredits: null,
+ session: null,
+ status: 'ok',
+ updatedAt: Date.now(),
+ weekly: null,
+ ...overrides,
+});
+
+export const kimiCodeSnapshot = (
+ overrides: Partial<KimiCodeQuotaSnapshot> = {},
+): KimiCodeQuotaSnapshot => ({
+ error: null,
+ extraUsage: null,
+ monthly: null,
+ monthlyCode: null,
+ provider: 'kimi-code',
+ session: null,
+ status: 'ok',
+ updatedAt: Date.now(),
+ weekly: null,
+ ...overrides,
+});
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.test.tsx
new file mode 100644
index 00000000000..c8bf939f298
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.test.tsx
@@ -0,0 +1,369 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import type * as LobechatConstModule from '@lobechat/const';
+import type * as ElectronClientIpcModule from '@lobechat/electron-client-ipc';
+import type { HeterogeneousProviderConfig } from '@lobechat/types';
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { openQuotaCalendarModal } from '@/features/AgentQuotaCalendar';
+
+import HeteroControlBar from '.';
+import { codexSnapshot, kimiCodeSnapshot } from './QuotaMenu/testUtils';
+
+const mockService = vi.hoisted(() => ({
+ consumeCodexRateLimitResetCredit: vi.fn(),
+ getClaudeCodeQuota: vi.fn(),
+ getCodexQuota: vi.fn(),
+ getKimiCodeQuota: vi.fn(),
+}));
+
+const effectiveAgencyConfig = vi.hoisted(() => ({
+ current: {
+ boundDeviceId: 'personal-device' as string | undefined,
+ executionTarget: 'local' as 'local' | 'device',
+ heterogeneousProvider: {
+ command: 'codex',
+ type: 'codex',
+ } as HeterogeneousProviderConfig,
+ },
+ workspaceScoped: false,
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<typeof LobechatConstModule>()),
+ isDesktop: true,
+}));
+
+vi.mock('@lobechat/electron-client-ipc', async (importOriginal) => ({
+ ...(await importOriginal<typeof ElectronClientIpcModule>()),
+ useWatchBroadcast: vi.fn(),
+}));
+
+vi.mock('@/business/client/features/ChatInputCredits', () => ({
+ default: () => <div data-testid="api-credits" />,
+}));
+
+vi.mock('@/features/ChatInput/ControlBar/WorkspaceControls', () => ({
+ default: () => <div data-testid="workspace-controls" />,
+}));
+
+vi.mock('@/features/ChatInput/ControlBar/HeteroDeviceSwitcher', () => ({
+ default: () => <div data-testid="hetero-device-switcher" />,
+}));
+
+vi.mock('@/features/AgentQuotaCalendar', () => ({
+ openQuotaCalendarModal: vi.fn(),
+}));
+
+vi.mock('@/features/ChatInput/hooks/useAgentId', () => ({ useAgentId: () => 'agent-1' }));
+vi.mock('@/features/ChatInput/hooks/useTopicId', () => ({ useTopicId: () => 'topic-1' }));
+
+// Resource-access gating is out of scope for quota tests β€” keep it permissive
+// so HeteroControlBar renders its full quota UI without the ChatInput store.
+vi.mock('@/features/ChatInput/hooks/useChatInputResourceAccess', () => ({
+ useChatInputResourceAccess: () => ({
+ canConfigureResource: true,
+ canSendMessage: true,
+ canUseResource: true,
+ isAccessLoading: false,
+ }),
+}));
+
+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
+ useEffectiveAgencyConfig: () => ({
+ agencyConfig: effectiveAgencyConfig.current,
+ workspaceScoped: effectiveAgencyConfig.workspaceScoped,
+ }),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: Record<string, unknown>) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ isAgentConfigLoadingById: () => () => false,
+ isWorkspaceAgentById: () => () => true,
+ },
+}));
+
+const translate = vi.hoisted(() => (key: string, opts?: Record<string, unknown>) => {
+ const values = opts ? Object.values(opts) : [];
+ return values.length > 0 ? `${key}:${values.join(',')}` : key;
+});
+
+vi.mock('@/services/electron/heterogeneousAgent', () => ({
+ heterogeneousAgentService: mockService,
+}));
+
+// A `deviceId` routes the live sample through the device gateway TRPC instead
+// of Electron IPC (see `fetchClaudeCodeQuotaSnapshot`).
+const { mockLambdaClaudeQuota, mockLambdaCodexQuota, mockLambdaKimiCodeQuota } = vi.hoisted(() => ({
+ mockLambdaClaudeQuota: vi.fn(),
+ mockLambdaCodexQuota: vi.fn(),
+ mockLambdaKimiCodeQuota: vi.fn(),
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ device: {
+ getClaudeCodeQuota: { query: mockLambdaClaudeQuota },
+ },
+ },
+}));
+
+// The menu reads persisted quota through TRPC before falling back to the live
+// IPC fetch. Default to "nothing persisted yet" so these cases exercise the live
+// path without each one stalling on a real HTTP request; individual tests can
+// hand it persisted accounts/windows.
+const mockQuotaService = vi.hoisted(() => ({
+ getLatestReadings: vi.fn(async (): Promise<unknown[]> => []),
+ ingestClaudeSnapshot: vi.fn(async () => undefined),
+ ingestCodexSnapshot: vi.fn(async () => undefined),
+ ingestKimiCodeSnapshot: vi.fn(async () => undefined),
+ refreshCodexQuota: vi.fn(),
+ refreshKimiCodeQuota: vi.fn(),
+ listAccounts: vi.fn(async (): Promise<unknown[]> => []),
+ listBindings: vi.fn(async (): Promise<unknown[]> => []),
+}));
+
+vi.mock('@/services/agentQuota', () => ({ agentQuotaService: mockQuotaService }));
+
+// Render keys verbatim (with interpolated values appended) so assertions can
+// target the exact i18n key + params a snapshot should produce.
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: translate,
+ }),
+}));
+
+vi.mock('@lobehub/ui', async (importOriginal) => {
+ return {
+ ...(await importOriginal<object>()),
+ ActionIcon: ({
+ disabled,
+ onClick,
+ title,
+ }: {
+ disabled?: boolean;
+ onClick?: () => void;
+ title?: string;
+ }) => (
+ <button
+ aria-label={title}
+ data-testid={title ? 'calendar' : 'refresh'}
+ disabled={disabled}
+ type="button"
+ onClick={onClick}
+ />
+ ),
+ Flexbox: ({ children, className }: { children?: ReactNode; className?: string }) => (
+ <div className={className}>{children}</div>
+ ),
+ Icon: () => <svg />,
+ // Render the popover content unconditionally so window rows are assertable
+ // without driving the open/close interaction.
+ Popover: ({
+ children,
+ content,
+ onOpenChange,
+ }: {
+ children?: ReactNode;
+ content?: ReactNode;
+ onOpenChange?: (open: boolean) => void;
+ }) => (
+ <div>
+ <div data-testid="popover-content">{content}</div>
+ <div data-testid="quota-trigger" onClick={() => onOpenChange?.(true)}>
+ {children}
+ </div>
+ </div>
+ ),
+ Skeleton: { Button: () => <div data-testid="skeleton" /> },
+ Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+ Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ };
+});
+
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ ActionIcon: ({
+ onClick,
+ title,
+ disabled,
+ }: {
+ disabled?: boolean;
+ onClick?: (e: React.MouseEvent) => void;
+ title?: string;
+ }) => (
+ <button
+ aria-label={title}
+ data-testid={title ? 'calendar' : 'refresh'}
+ disabled={disabled}
+ type="button"
+ onClick={onClick}
+ />
+ ),
+ Skeleton: ({ height }: { height?: number }) => (
+ <div data-height={height} data-testid="skeleton" />
+ ),
+}));
+
+beforeEach(() => {
+ effectiveAgencyConfig.current = {
+ boundDeviceId: 'personal-device',
+ executionTarget: 'local',
+ heterogeneousProvider: { command: 'codex', type: 'codex' },
+ };
+ effectiveAgencyConfig.workspaceScoped = false;
+ mockService.consumeCodexRateLimitResetCredit.mockReset();
+ mockService.getClaudeCodeQuota.mockReset();
+ mockService.getCodexQuota.mockReset();
+ mockService.getKimiCodeQuota.mockReset();
+ mockLambdaClaudeQuota.mockReset();
+ mockLambdaCodexQuota.mockReset();
+ mockLambdaKimiCodeQuota.mockReset();
+ mockQuotaService.refreshCodexQuota.mockImplementation(mockLambdaCodexQuota);
+ mockQuotaService.refreshKimiCodeQuota.mockImplementation(mockLambdaKimiCodeQuota);
+ mockQuotaService.getLatestReadings.mockResolvedValue([]);
+ mockQuotaService.ingestClaudeSnapshot.mockClear();
+ mockQuotaService.ingestKimiCodeSnapshot.mockClear();
+ mockQuotaService.listAccounts.mockResolvedValue([]);
+ mockQuotaService.listBindings.mockResolvedValue([]);
+ vi.mocked(openQuotaCalendarModal).mockClear();
+});
+
+describe('HeteroControlBar', () => {
+ it('shows local Codex quota for a workspace member local-device override', async () => {
+ mockService.getCodexQuota.mockResolvedValue(
+ codexSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
+ );
+
+ render(<HeteroControlBar />);
+
+ expect(
+ await screen.findByRole('button', { name: 'heteroAgent.codexQuota.tooltip' }),
+ ).toBeTruthy();
+ expect(screen.queryByTestId('api-credits')).toBeNull();
+ expect(mockService.getCodexQuota).toHaveBeenCalledWith({ command: 'codex', env: undefined });
+ });
+
+ it('shows Codex quota sampled by a bound remote device', async () => {
+ effectiveAgencyConfig.current = {
+ boundDeviceId: 'remote-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { command: 'codex', type: 'codex' },
+ };
+ mockLambdaCodexQuota.mockResolvedValue(
+ codexSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
+ );
+
+ render(<HeteroControlBar />);
+
+ expect(
+ await screen.findByRole('button', { name: 'heteroAgent.codexQuota.tooltip' }),
+ ).toBeTruthy();
+ expect(mockLambdaCodexQuota).toHaveBeenCalledWith({
+ command: 'codex',
+ deviceId: 'remote-device',
+ env: undefined,
+ });
+ expect(mockService.getCodexQuota).not.toHaveBeenCalled();
+ });
+
+ it('shows remote quota for a workspace shared-device fallback', async () => {
+ effectiveAgencyConfig.current = {
+ boundDeviceId: 'workspace-device',
+ executionTarget: 'local',
+ heterogeneousProvider: { command: 'codex', type: 'codex' },
+ };
+ effectiveAgencyConfig.workspaceScoped = true;
+ mockLambdaCodexQuota.mockResolvedValue(
+ codexSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
+ );
+
+ render(<HeteroControlBar />);
+
+ expect(
+ await screen.findByRole('button', { name: 'heteroAgent.codexQuota.tooltip' }),
+ ).toBeTruthy();
+ expect(mockLambdaCodexQuota).toHaveBeenCalledWith({
+ command: 'codex',
+ deviceId: 'workspace-device',
+ env: undefined,
+ });
+ expect(mockService.getCodexQuota).not.toHaveBeenCalled();
+ });
+
+ it('shows platform credits instead of Codex quota in API mode', () => {
+ effectiveAgencyConfig.current = {
+ boundDeviceId: 'personal-device',
+ executionTarget: 'local',
+ heterogeneousProvider: { authMode: 'api', command: 'codex', type: 'codex' },
+ };
+
+ render(<HeteroControlBar />);
+
+ expect(screen.getByTestId('api-credits')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'heteroAgent.codexQuota.tooltip' })).toBeNull();
+ expect(mockService.getCodexQuota).not.toHaveBeenCalled();
+ });
+
+ it('shows platform credits instead of Claude Code quota in API mode', () => {
+ effectiveAgencyConfig.current = {
+ boundDeviceId: 'personal-device',
+ executionTarget: 'local',
+ heterogeneousProvider: { authMode: 'api', type: 'claude-code' },
+ };
+
+ render(<HeteroControlBar />);
+
+ expect(screen.getByTestId('api-credits')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'heteroAgent.claudeQuota.tooltip' })).toBeNull();
+ expect(mockService.getClaudeCodeQuota).not.toHaveBeenCalled();
+ });
+
+ it('shows local Kimi Code quota for a local execution target', async () => {
+ effectiveAgencyConfig.current = {
+ boundDeviceId: 'personal-device',
+ executionTarget: 'local',
+ heterogeneousProvider: { command: 'kimi', type: 'kimi-code' },
+ };
+ mockService.getKimiCodeQuota.mockResolvedValue(
+ kimiCodeSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
+ );
+
+ render(<HeteroControlBar />);
+
+ expect(
+ await screen.findByRole('button', { name: 'heteroAgent.kimiCodeQuota.tooltip' }),
+ ).toBeTruthy();
+ expect(mockService.getKimiCodeQuota).toHaveBeenCalledWith({ env: undefined });
+ expect(mockService.getCodexQuota).not.toHaveBeenCalled();
+ });
+
+ it('shows Kimi Code quota sampled by a bound remote device', async () => {
+ effectiveAgencyConfig.current = {
+ boundDeviceId: 'remote-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { command: 'kimi', type: 'kimi-code' },
+ };
+ mockLambdaKimiCodeQuota.mockResolvedValue(
+ kimiCodeSnapshot({ session: { resetsAt: null, usedPercent: 20, windowMinutes: 300 } }),
+ );
+
+ render(<HeteroControlBar />);
+
+ expect(
+ await screen.findByRole('button', { name: 'heteroAgent.kimiCodeQuota.tooltip' }),
+ ).toBeTruthy();
+ expect(mockLambdaKimiCodeQuota).toHaveBeenCalledWith({
+ deviceId: 'remote-device',
+ env: undefined,
+ });
+ expect(mockService.getKimiCodeQuota).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
index cf4be9c5e64..a660e318df6 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
@@ -18,6 +18,7 @@ import DeviceSwitcher from '@/features/ChatInput/ControlBar/DeviceSwitcher';
import WorkspaceControls from '@/features/ChatInput/ControlBar/WorkspaceControls';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
+import { useTopicId } from '@/features/ChatInput/hooks/useTopicId';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
@@ -150,6 +151,7 @@ const HeteroControlBarSkeleton = ({ showRight }: { showRight?: boolean }) => (
const HeteroControlBar = memo(() => {
const { t: tChat } = useTranslation('chat');
const agentId = useAgentId();
+ const topicId = useTopicId();
const { canConfigureResource, isAccessLoading } = useChatInputResourceAccess();
const [runtimeStatus, setRuntimeStatus] = useState<HeterogeneousAgentRuntimeStatus>();
@@ -162,7 +164,7 @@ const HeteroControlBar = memo(() => {
const isLoading = useAgentStore(agentByIdSelectors.isAgentConfigLoadingById(agentId));
// Effective config = shared row + this member's device override,
// so the quota badges gate on where THIS member's run actually executes.
- const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);
+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, { topicId });
const heteroProvider = agencyConfig?.heterogeneousProvider;
const executionTarget = resolveExecutionTarget(agencyConfig, {
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 6a4ee28872a..8835b0c712a 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, confirmModal, toast } from '@lobehub/ui/base-ui';
+import { Button, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import {
ChevronDownIcon,
@@ -32,24 +32,21 @@ import {
} from '@/features/ExecutionTargetPicker';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import {
- getTopicBoundDeviceId,
isHeterogeneousSandboxExecutionAvailable,
isLocalSandboxEnabled,
resolveExecutionTarget,
} from '@/helpers/executionTarget';
import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
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 { useTopicId } from '../hooks/useTopicId';
import { formatLockedControlTooltip } from '../utils/lockedControlTooltip';
-import { moveTopicToTarget } from './moveTopicToTarget';
import OptionRow from './OptionRow';
-import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';
+import { useSandboxNetworkToggle } from './useSandboxNetworkToggle';
+import { useTopicAwareTargetSelect } from './useTopicAwareTargetSelect';
const styles = createStaticStyles(({ css }) => ({
button: css`
@@ -266,6 +263,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
const navigate = useWorkspaceAwareNavigate();
const { canUseResource } = useChatInputResourceAccess();
+ // This composer's conversation (see `useTopicId`): a side-by-side pane must
+ // resolve, and re-pin, its own topic rather than the main column's.
+ const topicId = useTopicId();
const agentWorkspaceId = useAgentStore((s) => s.agentMap[agentId]?.workspaceId);
const isWorkspaceAgent = Boolean(agentWorkspaceId);
@@ -278,7 +278,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
canSelectExecutionTarget,
isPreferenceLoading: isWorkspacePreferenceLoading,
workspaceScoped,
- } = useEffectiveAgencyConfig(agentId);
+ } = useEffectiveAgencyConfig(agentId, { topicId });
const canShowExecutionTarget = canUseResource && canDisplayExecutionTarget;
const canShowExecutionTargetSelector = canShowExecutionTarget && canSelectExecutionTarget;
@@ -388,115 +388,21 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
void revalidateSandboxCapability();
}, [open, revalidateSandboxCapability]);
- // `homeFallback: false` on purpose β€” this must reflect whether the user has
- // actually chosen a directory, not the runtime's convenience fallback.
- const configuredWorkingDirectory = useEffectiveWorkingDirectory(agentId, { homeFallback: false });
- const { commit: commitWorkingDirectory } = useCommitWorkingDirectory(agentId);
-
- /**
- * Give a sandboxed agent somewhere to work when the user has not picked a
- * directory yet.
- *
- * The fence is scoped to the working directory, so without one the run is
- * refused β€” a first use that fails on a requirement the picker never
- * mentioned. Rather than fence a directory nobody chose *silently*, the
- * default is written into the same setting the chip reads, so the answer to
- * "where is this running?" stays visible and changeable.
- */
- // `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 { selectTarget, topicDeviceId } = useTopicAwareTargetSelect({
+ agentId,
+ currentDeviceId,
+ devices,
+ selectExecutionTarget,
+ topicId,
+ });
const handleSelect = useCallback(
async (target: DeviceExecutionTarget, deviceId?: string, localSandbox?: boolean) => {
setOpen(false);
- 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'),
- });
+ await selectTarget(target, deviceId, localSandbox);
},
- [
- activeTopicId,
- currentDeviceId,
- devices,
- ensureSandboxWorkingDirectory,
- selectExecutionTarget,
- t,
- topicDeviceId,
- updateTopicMetadata,
- ],
+ [selectTarget],
);
// Setting up the backend raises an elevation prompt and creates a dedicated
@@ -520,15 +426,13 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
// Toggling the network does NOT change which environment is selected β€” same
// dormant semantics the sandbox flag itself has when another environment is
// active, so the popover stays open and nothing is switched behind the user.
- const handleToggleSandboxNetwork = useCallback(
- async (enabled: boolean) => {
- await selectExecutionTarget(executionTarget, boundDeviceId, {
- localSandbox: localSandboxEnabled,
- localSandboxNetwork: enabled,
- });
- },
- [selectExecutionTarget, executionTarget, boundDeviceId, localSandboxEnabled],
- );
+ // Saved on the unpinned default, never the open topic's machine.
+ const handleToggleSandboxNetwork = useSandboxNetworkToggle({
+ agentId,
+ deviceRoutingAvailable,
+ isHetero,
+ selectExecutionTarget,
+ });
// Auto-default to THIS desktop's local execution on first open, for both
// personal and workspace agents (workspace behaviour used to be a hostname
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx
index 85096c981f5..8b7390a90db 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroModel/ModelCatalogSelector.tsx
@@ -49,6 +49,7 @@ import { useElectronStore } from '@/store/electron';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
+import { useTopicId } from '../../hooks/useTopicId';
import { useMenuContentLifecycle } from '../useMenuContentLifecycle';
import { useModelCatalog } from './useModelCatalog';
import { useModelCatalogView } from './useModelCatalogView';
@@ -181,13 +182,16 @@ export const ModelCatalogSelector = memo<ModelCatalogSelectorProps>(
handleOpenChangeComplete: completeOpenChange,
open,
} = useMenuContentLifecycle(onSelect);
- const { agencyConfig, isPreferenceLoading, workspaceScoped } =
- useEffectiveAgencyConfig(agentId);
+ const topicId = useTopicId();
+ const { agencyConfig, isPreferenceLoading, workspaceScoped } = useEffectiveAgencyConfig(
+ agentId,
+ { topicId },
+ );
const isLogin = useUserStore(authSelectors.isLogin);
const { isLoading: isDeviceListLoading } = useDeviceStore((s) => s.useFetchDevices)(
isLogin || isDesktop,
);
- const cwd = useEffectiveWorkingDirectory(agentId);
+ const cwd = useEffectiveWorkingDirectory(agentId, { topicId });
const provider = agencyConfig?.heterogeneousProvider;
useElectronStore((s) => s.useFetchGatewayDeviceInfo)();
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/index.tsx b/src/features/ChatInput/ControlBar/HeteroModel/index.tsx
index ff845575cb3..0d4dedcce30 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel/index.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroModel/index.tsx
@@ -13,6 +13,7 @@ import { topicSelectors } from '@/store/chat/slices/topic/selectors';
import { useAgentId } from '../../hooks/useAgentId';
import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
+import { useTopicId } from '../../hooks/useTopicId';
import { ModelCatalogSelector } from './ModelCatalogSelector';
import SelectorMenu from './SelectorMenu';
import { resolveSelectorShape } from './selectorView';
@@ -30,8 +31,13 @@ const HeteroModel = memo(() => {
const { canConfigureResource } = useChatInputResourceAccess();
const enabled = canCreateContent && canConfigureResource;
const patch = useHeteroProviderPatch({ agentId, enabled, provider });
- // Model AND effort pins: both follow the active topic once one exists.
- const topicPin = useChatStore(topicSelectors.activeTopicHeteroPin, isEqual);
+ // Model AND effort pins: both follow this composer's topic once one exists
+ // (see `useTopicId`), never the global active topic.
+ const topicId = useTopicId();
+ const topicPin = useChatStore(
+ (s) => (topicId ? topicSelectors.getTopicHeteroPinById(topicId)(s) : undefined),
+ isEqual,
+ );
const effectiveProvider = provider
? applyTopicModelToHeterogeneousProvider(provider, topicPin)
: undefined;
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.test.ts b/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.test.ts
index f58adacddc5..aaa053a60dd 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.test.ts
+++ b/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.test.ts
@@ -9,6 +9,13 @@ const state = vi.hoisted(() => ({
activeTopicId: 'topic-a' as string | null,
updateTopicHeteroPin: vi.fn(),
},
+ /** `undefined`: the host publishes no topic; `null`: its conversation has none. */
+ composerTopicId: undefined as string | null | undefined,
+}));
+
+vi.mock('../../store', () => ({
+ useChatInputStore: (selector: (value: object) => unknown) =>
+ selector({ topicId: state.composerTopicId }),
}));
vi.mock('@/store/agent', () => ({
@@ -24,6 +31,48 @@ describe('useHeteroProviderPatch', () => {
state.agent.updateAgentConfigById.mockReset();
state.chat.activeTopicId = 'topic-a';
state.chat.updateTopicHeteroPin.mockReset();
+ state.composerTopicId = undefined;
+ });
+
+ // A side-by-side portal pane renders another topic while the main column's
+ // topic stays globally active.
+ it("pins the composer's own topic rather than the global active topic", async () => {
+ state.composerTopicId = 'topic-pane';
+ const { result } = renderHook(() =>
+ useHeteroProviderPatch({
+ agentId: 'agent-a',
+ enabled: true,
+ provider: { model: 'global-model', type: 'codex' },
+ }),
+ );
+
+ await act(() => result.current({ model: 'pane-model' }));
+
+ expect(state.chat.updateTopicHeteroPin).toHaveBeenCalledWith('topic-pane', {
+ effort: undefined,
+ model: 'pane-model',
+ provider: 'codex',
+ });
+ });
+
+ it('updates the Agent default when the composer conversation has no topic, even with an active topic', async () => {
+ state.composerTopicId = null;
+ const { result } = renderHook(() =>
+ useHeteroProviderPatch({
+ agentId: 'agent-a',
+ enabled: true,
+ provider: { model: 'global-model', type: 'cursor' },
+ }),
+ );
+
+ await act(() => result.current({ model: 'next-default' }));
+
+ expect(state.chat.updateTopicHeteroPin).not.toHaveBeenCalled();
+ expect(state.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-a', {
+ agencyConfig: {
+ heterogeneousProvider: { args: undefined, model: 'next-default' },
+ },
+ });
});
it('writes a model selection to the active topic without changing the Agent default', async () => {
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.ts b/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.ts
index 50076341f37..434fd8d9f27 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.ts
+++ b/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.ts
@@ -5,6 +5,8 @@ import { useCallback } from 'react';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
+import { useTopicId } from '../../hooks/useTopicId';
+
export const useHeteroProviderPatch = ({
agentId,
enabled,
@@ -15,7 +17,8 @@ export const useHeteroProviderPatch = ({
provider: HeterogeneousProviderConfig | undefined;
}) => {
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
- const activeTopicId = useChatStore((s) => s.activeTopicId);
+ // This composer's conversation (see `useTopicId`), never the global active topic.
+ const topicId = useTopicId();
const updateTopicHeteroPin = useChatStore((s) => s.updateTopicHeteroPin);
return useCallback(
@@ -26,9 +29,9 @@ export const useHeteroProviderPatch = ({
// its own pins, see `ChatTopic.model` / `ChatTopicMetadata.heteroEffort`);
// the remaining dimensions (mode, speed) still write the shared agent config.
const { effort, model, ...agentSelection } = selection;
- if (activeTopicId) {
+ if (topicId) {
if (model !== undefined || effort !== undefined) {
- await updateTopicHeteroPin(activeTopicId, { effort, model, provider: provider.type });
+ await updateTopicHeteroPin(topicId, { effort, model, provider: provider.type });
}
if (Object.keys(agentSelection).length === 0) return;
}
@@ -36,11 +39,11 @@ export const useHeteroProviderPatch = ({
agencyConfig: {
heterogeneousProvider: applyHeteroSelection(
provider,
- activeTopicId ? agentSelection : selection,
+ topicId ? agentSelection : selection,
),
},
});
},
- [activeTopicId, agentId, enabled, provider, updateAgentConfigById, updateTopicHeteroPin],
+ [agentId, enabled, provider, topicId, updateAgentConfigById, updateTopicHeteroPin],
);
};
diff --git a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx
index 94097a22aed..6773c8ebc5f 100644
--- a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx
+++ b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx
@@ -5,6 +5,7 @@ import { memo } from 'react';
import SafeBoundary from '@/components/ErrorBoundary';
import { useAgentStore } from '@/store/agent';
+import { useTopicId } from '../hooks/useTopicId';
import SandboxInstancePicker from './SandboxInstancePicker';
import { useSandboxMode } from './useSandboxMode';
import { useSandboxStorageAccess } from './useSandboxStorageAccess';
@@ -31,7 +32,7 @@ interface SandboxStorageSectionProps {
*/
const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }) => {
const { status } = useSandboxStorageAccess(agentId);
- const { selection, setSelection, topicId } = useSandboxMode(agentId);
+ const { selection, setSelection, topicId } = useSandboxMode(agentId, useTopicId());
const agentIsPublic = useAgentStore((s) => s.agentMap[agentId]?.visibility === 'public');
if (status === 'hidden') return null;
diff --git a/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx b/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx
index 939997ac3e8..f07d28f89c9 100644
--- a/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx
+++ b/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx
@@ -62,6 +62,8 @@ interface StaleGitSnapshotProps {
path: string;
/** The source repo the worktree was linked from, when the topic recorded one. */
sourcePath?: string;
+ /** The conversation the switch is recorded on; omitted, the global active topic. */
+ topicId?: string | null;
}
/**
@@ -76,11 +78,16 @@ interface StaleGitSnapshotProps {
* explains why the branch is frozen but leaves no way out of it.
*/
const StaleGitSnapshot = memo<StaleGitSnapshotProps>(
- ({ agentId, git, isGithub, path, sourcePath }) => {
+ ({ agentId, git, isGithub, path, sourcePath, topicId }) => {
const { t } = useTranslation('device');
const [open, setOpen] = useState(false);
const [resetting, setResetting] = useState(false);
- const switchWorktree = useSwitchWorktree({ agentId, isGithub, sourcePath: sourcePath ?? path });
+ const switchWorktree = useSwitchWorktree({
+ agentId,
+ isGithub,
+ sourcePath: sourcePath ?? path,
+ topicId,
+ });
const { explanation, isWorktree, label, pullRequest, reset, worktreePath } =
resolveStaleSnapshot({ git, path, sourcePath });
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
index 9b1b0e865f3..5150bf11ef4 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx
@@ -18,7 +18,6 @@ import {
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useConversationStore } from '@/features/Conversation/store';
import { openPickWorkingDirModal } from '@/features/WorkingDirectory';
import {
resolveAgentWorkingDirectorySource,
@@ -38,6 +37,7 @@ import { useElectronStore } from '@/store/electron';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
+import { useTopicId } from '../hooks/useTopicId';
import DashedFolderIcon from './DashedFolderIcon';
import DirIcon from './DirIcon';
import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';
@@ -234,7 +234,7 @@ interface WorkingDirectoryPickerProps {
* runs in when nothing is picked is never invisible.
*/
const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) => {
- const topicId = useConversationStore((s) => s.context.topicId);
+ const topicId = useTopicId();
const { t } = useTranslation('device');
const [open, setOpen] = useState(false);
const [search, setSearch] = useState('');
@@ -250,7 +250,7 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =
// Effective config (shared row + this member's device override)
// so recents / default cwd / the selected-repo label all resolve against the
// device THIS member's run actually targets.
- const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);
+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, { topicId });
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {
workspaceScoped,
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
index 3503b43daf1..32b80496c60 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
@@ -15,6 +15,7 @@ import { topicSelectors } from '@/store/chat/selectors';
import { deviceSelectors, useDeviceStore } from '@/store/device';
import { useElectronStore } from '@/store/electron';
+import { useTopicId } from '../hooks/useTopicId';
import GitStatus from './GitStatus';
import { useActiveProjectDirectoryTopicId } from './useProjectTopicDirectory';
import { useRepoType } from './useRepoType';
@@ -39,14 +40,15 @@ const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agent
// Effective config (shared row + this member's device override)
// so GitStatus probes the same device `useEffectiveWorkingDirectory` resolved
// the cwd from β€” raw shared config could point them at different machines.
- const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);
+ const topicId = useTopicId();
+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, { topicId });
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {
workspaceScoped,
});
const isLocalDevice = isDesktop && !!targetDeviceId && targetDeviceId === currentDeviceId;
- const rawEffectiveWorkingDirectory = useEffectiveWorkingDirectory(agentId);
+ const rawEffectiveWorkingDirectory = useEffectiveWorkingDirectory(agentId, { topicId });
const effectiveWorkingDirectory = getWorkingDirectoryPathString(rawEffectiveWorkingDirectory);
// Live probes (fs / cached device dirs) can't resolve repoType for a worktree
@@ -57,8 +59,8 @@ const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agent
// also feeds GitStatus's `fallbackGit`, which covers the harder case: the
// recorded worktree directory was DELETED, so the live branch probe reads
// nothing and the chips would vanish even with repoType resolved.
- const topicWorkingDirectoryConfig = useChatStore(
- (s) => topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,
+ const topicWorkingDirectoryConfig = useChatStore((s) =>
+ topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata?.workingDirectoryConfig : undefined,
);
// The project owns this conversation's directory and the device switcher
// already names it, so there is nothing to pick or show here.
@@ -107,6 +109,7 @@ const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agent
isGithub={repoType === 'github'}
path={effectiveWorkingDirectory}
sourcePath={sourceWorkingDirectory}
+ topicId={topicId}
/>
)}
</>
diff --git a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
index 7c69c4e585c..c55a6db8442 100644
--- a/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/WorktreeSwitcher.tsx
@@ -421,6 +421,8 @@ interface WorktreeSwitcherProps {
/** Dropdown placement β€” the runtime bar opens upward, embedding panels open downward. */
placement?: 'topLeft' | 'bottomLeft' | 'bottomRight';
sourcePath: string;
+ /** The conversation the switch is recorded on; omitted, the global active topic. */
+ topicId?: string | null;
worktrees: DeviceGitWorktreeListItem[];
}
@@ -436,6 +438,7 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
path,
placement = 'topLeft',
sourcePath,
+ topicId,
worktrees,
}) => {
const { t } = useTranslation('device');
@@ -449,7 +452,7 @@ const WorktreeSwitcher = memo<WorktreeSwitcherProps>(
// duplicate delete if the dropdown is reopened mid-removal.
const [removingPaths, setRemovingPaths] = useState<Set<string>>(() => new Set());
const currentRowRef = useRef<HTMLDivElement>(null);
- const switchWorktree = useSwitchWorktree({ agentId, isGithub, sourcePath });
+ const switchWorktree = useSwitchWorktree({ agentId, isGithub, sourcePath, topicId });
// Clear the query each time the dropdown closes so it reopens unfiltered.
useEffect(() => {
diff --git a/src/features/ChatInput/ControlBar/__tests__/useActiveProjectDirectoryTopicId.test.ts b/src/features/ChatInput/ControlBar/__tests__/useActiveProjectDirectoryTopicId.test.ts
index 7df5e9bbdee..04f777cc7e3 100644
--- a/src/features/ChatInput/ControlBar/__tests__/useActiveProjectDirectoryTopicId.test.ts
+++ b/src/features/ChatInput/ControlBar/__tests__/useActiveProjectDirectoryTopicId.test.ts
@@ -1,13 +1,20 @@
import { renderHook } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useActiveProjectDirectoryTopicId } from '../useProjectTopicDirectory';
const state = vi.hoisted(() => ({
activeTopicId: undefined as string | undefined,
+ /** `undefined`: the host publishes no topic; `null`: its conversation has none. */
+ composerTopicId: undefined as string | null | undefined,
topics: {} as Record<string, { projectWorkingDirectoryId?: string | null }>,
}));
+vi.mock('../../store', () => ({
+ useChatInputStore: (selector: (s: object) => unknown) =>
+ selector({ topicId: state.composerTopicId }),
+}));
+
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (s: unknown) => unknown) => selector(state),
}));
@@ -24,6 +31,10 @@ vi.mock('@/store/projectWorkingDirectory', () => ({
}));
describe('useActiveProjectDirectoryTopicId', () => {
+ beforeEach(() => {
+ state.composerTopicId = undefined;
+ });
+
it('names the open conversation when it runs in a project directory', () => {
state.activeTopicId = 'project-topic';
state.topics = { 'project-topic': { projectWorkingDirectoryId: 'directory-1' } };
@@ -40,4 +51,22 @@ describe('useActiveProjectDirectoryTopicId', () => {
state.activeTopicId = undefined;
expect(renderHook(() => useActiveProjectDirectoryTopicId()).result.current).toBeUndefined();
});
+
+ // A side-by-side portal pane renders another topic while the main column's
+ // topic stays globally active.
+ it("follows the composer's own topic rather than the global active topic", () => {
+ state.activeTopicId = 'plain-topic';
+ state.composerTopicId = 'project-topic';
+ state.topics = {
+ 'plain-topic': { projectWorkingDirectoryId: null },
+ 'project-topic': { projectWorkingDirectoryId: 'directory-1' },
+ };
+ expect(renderHook(() => useActiveProjectDirectoryTopicId()).result.current).toBe(
+ 'project-topic',
+ );
+
+ state.activeTopicId = 'project-topic';
+ state.composerTopicId = null;
+ expect(renderHook(() => useActiveProjectDirectoryTopicId()).result.current).toBeUndefined();
+ });
});
diff --git a/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.ts b/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.ts
index 79e765d88ce..c5b163224d7 100644
--- a/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.ts
+++ b/src/features/ChatInput/ControlBar/__tests__/useWorkspaceSurface.test.ts
@@ -28,6 +28,8 @@ vi.mock('@/helpers/gatewayMode', () => ({
useIsGatewayModeEnabled: () => true,
}));
+vi.mock('@/features/ChatInput/hooks/useTopicId', () => ({ useTopicId: () => 'topic-1' }));
+
vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
useEffectiveAgencyConfig: () => ({
agencyConfig: effective.agencyConfig,
diff --git a/src/features/ChatInput/ControlBar/useProjectTopicDirectory.ts b/src/features/ChatInput/ControlBar/useProjectTopicDirectory.ts
index 141eff5d856..707fa646818 100644
--- a/src/features/ChatInput/ControlBar/useProjectTopicDirectory.ts
+++ b/src/features/ChatInput/ControlBar/useProjectTopicDirectory.ts
@@ -6,19 +6,25 @@ import {
useProjectDirectoryStore,
} from '@/store/projectWorkingDirectory';
+import { useTopicId } from '../hooks/useTopicId';
+
const EMPTY: ProjectDirectory[] = [];
/**
- * The open conversation's id when it runs in a project directory, otherwise
- * undefined. Such a conversation only chooses among its project's devices and
- * shows its directory read-only, so the control bars branch on this.
+ * This composer's conversation id (see `useTopicId`) when it runs in a project
+ * directory, otherwise undefined. Such a conversation only chooses among its
+ * project's devices and shows its directory read-only, so the control bars
+ * branch on this.
*/
-export const useActiveProjectDirectoryTopicId = (): string | undefined =>
- useChatStore((s) =>
- s.activeTopicId && topicSelectors.getTopicById(s.activeTopicId)(s)?.projectWorkingDirectoryId
- ? s.activeTopicId
+export const useActiveProjectDirectoryTopicId = (): string | undefined => {
+ const topicId = useTopicId();
+
+ return useChatStore((s) =>
+ topicId && topicSelectors.getTopicById(topicId)(s)?.projectWorkingDirectoryId
+ ? topicId
: undefined,
);
+};
/**
* The project directory a conversation runs in, and the project's other
diff --git a/src/features/ChatInput/ControlBar/useSandboxMode.test.ts b/src/features/ChatInput/ControlBar/useSandboxMode.test.ts
new file mode 100644
index 00000000000..04e1198196f
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/useSandboxMode.test.ts
@@ -0,0 +1,80 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getPendingSandboxSelection } from '@/store/chat/pendingSandboxSelection';
+
+import { useSandboxMode } from './useSandboxMode';
+
+interface TopicSandbox {
+ sandboxInstanceId?: string;
+ sandboxMode?: 'ephemeral' | 'persistent';
+}
+
+const state = vi.hoisted(() => ({
+ activeTopicId: undefined as string | undefined,
+ topics: {} as Record<string, TopicSandbox>,
+ updateTopicMetadata: vi.fn(),
+}));
+
+// Store boundary: the real topic selectors run against this state.
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: object) => unknown) =>
+ selector({
+ activeTopicId: state.activeTopicId,
+ topicDataMap: {},
+ topicDetailMap: Object.fromEntries(
+ Object.entries(state.topics).map(([id, metadata]) => [id, { id, metadata }]),
+ ),
+ updateTopicMetadata: state.updateTopicMetadata,
+ }),
+}));
+
+beforeEach(() => {
+ // The main column's topic stays globally active while a side pane renders another.
+ state.activeTopicId = 'main-topic';
+ state.topics = {
+ 'main-topic': { sandboxInstanceId: 'main-instance', sandboxMode: 'persistent' },
+ 'pane-topic': { sandboxMode: 'ephemeral' },
+ };
+ state.updateTopicMetadata.mockReset();
+});
+
+describe('useSandboxMode', () => {
+ it('reads and writes the given topic instead of the global active topic', async () => {
+ const { result } = renderHook(() => useSandboxMode('agent-1', 'pane-topic'));
+
+ expect(result.current.selection).toEqual({ instanceId: undefined, mode: 'ephemeral' });
+ expect(result.current.topicId).toBe('pane-topic');
+
+ await act(() =>
+ result.current.setSelection({ instanceId: 'pane-instance', mode: 'persistent' }),
+ );
+
+ expect(state.updateTopicMetadata).toHaveBeenCalledWith('pane-topic', {
+ sandboxInstanceId: 'pane-instance',
+ sandboxMode: 'persistent',
+ });
+ });
+
+ it('buffers the choice for a conversation without a topic even while another topic is active', async () => {
+ const { result } = renderHook(() => useSandboxMode('agent-new-topic', null));
+
+ expect(result.current.selection).toEqual({});
+ expect(result.current.topicId).toBeUndefined();
+
+ await act(() => result.current.setSelection({ mode: 'persistent' }));
+
+ expect(state.updateTopicMetadata).not.toHaveBeenCalled();
+ expect(getPendingSandboxSelection('agent-new-topic')).toEqual({ mode: 'persistent' });
+ });
+
+ it('follows the global active topic when no topic is given', () => {
+ const { result } = renderHook(() => useSandboxMode('agent-1'));
+
+ expect(result.current.selection).toEqual({
+ instanceId: 'main-instance',
+ mode: 'persistent',
+ });
+ expect(result.current.topicId).toBe('main-topic');
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/useSandboxMode.ts b/src/features/ChatInput/ControlBar/useSandboxMode.ts
index fcad0d4a53e..1e6d830c986 100644
--- a/src/features/ChatInput/ControlBar/useSandboxMode.ts
+++ b/src/features/ChatInput/ControlBar/useSandboxMode.ts
@@ -32,13 +32,18 @@ export interface SandboxSelection {
*
* Before a topic exists the choice is buffered by agent and carried by the
* first send; see `pendingSandboxSelection`.
+ *
+ * `scopeTopicId` is the conversation the caller belongs to; `null` means it has
+ * no topic yet. Omitted, it follows the global active topic.
*/
-export const useSandboxMode = (agentId: string) => {
- const topicId = useChatStore((s) => s.activeTopicId);
- const topicInstanceId = useChatStore(
- (s) => topicSelectors.currentTopicMetadata(s)?.sandboxInstanceId,
+export const useSandboxMode = (agentId: string, scopeTopicId?: string | null) => {
+ const activeTopicId = useChatStore((s) => s.activeTopicId);
+ const topicId = scopeTopicId === undefined ? activeTopicId : scopeTopicId;
+ const topicMetadata = useChatStore((s) =>
+ topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata : undefined,
);
- const topicMode = useChatStore((s) => topicSelectors.currentTopicMetadata(s)?.sandboxMode);
+ const topicInstanceId = topicMetadata?.sandboxInstanceId;
+ const topicMode = topicMetadata?.sandboxMode;
const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);
// The pending value lives outside React, so this subscribes to it the way a
// store would be subscribed to. Every component using this hook re-renders
diff --git a/src/features/ChatInput/ControlBar/useSandboxNetworkToggle.test.ts b/src/features/ChatInput/ControlBar/useSandboxNetworkToggle.test.ts
new file mode 100644
index 00000000000..8e6f33ae192
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/useSandboxNetworkToggle.test.ts
@@ -0,0 +1,123 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useAgentStore } from '@/store/agent';
+import { useUserStore } from '@/store/user';
+
+import { useSandboxNetworkToggle } from './useSandboxNetworkToggle';
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ isDesktop: true,
+}));
+
+vi.mock('@/features/ResourcePermission/useAgentManagementAccess', () => ({
+ useAgentManagementAccess: () => ({ canManageAgent: true, isAccessLoading: false }),
+}));
+
+const topicState = vi.hoisted(() => ({
+ activeTopicId: 'topic-1' as string | undefined,
+ gatewayDeviceInfo: { deviceId: 'device-a' },
+ topics: {} as Record<string, { agentId: string; metadata?: { boundDeviceId?: string } }>,
+}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: typeof topicState) => unknown) => selector(topicState),
+}));
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: {
+ getTopicById: (id: string) => (s: typeof topicState) => s.topics[id],
+ },
+}));
+vi.mock('@/store/electron', () => ({
+ useElectronStore: (selector: (s: typeof topicState) => unknown) => selector(topicState),
+}));
+
+vi.mock('@/store/agent', () => ({ useAgentStore: vi.fn() }));
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById:
+ (id: string) => (s: { agentMap: Record<string, { agencyConfig?: unknown }> }) =>
+ s.agentMap[id]?.agencyConfig,
+ getAgentById: (id: string) => (s: { agentMap: Record<string, unknown> }) => s.agentMap[id],
+ },
+}));
+vi.mock('@/store/user', () => ({ useUserStore: vi.fn() }));
+
+const selectExecutionTarget = vi.fn();
+
+const setupStores = (agencyConfig: unknown) => {
+ const agentState = { agentMap: { 'agent-1': { agencyConfig } } };
+ const userState = {
+ useFetchWorkspaceUserPreference: () => ({ data: {}, isLoading: false }),
+ workspaceUserPreference: {},
+ };
+ vi.mocked(useAgentStore).mockImplementation((selector: any) => selector(agentState));
+ vi.mocked(useUserStore).mockImplementation((selector: any) => selector(userState));
+};
+
+const renderToggle = () =>
+ renderHook(() =>
+ useSandboxNetworkToggle({
+ agentId: 'agent-1',
+ isHetero: true,
+ selectExecutionTarget,
+ }),
+ );
+
+beforeEach(() => {
+ selectExecutionTarget.mockReset().mockResolvedValue(true);
+ topicState.activeTopicId = 'topic-1';
+ topicState.topics = {};
+});
+
+describe('useSandboxNetworkToggle', () => {
+ const localSandboxDefault = {
+ boundDeviceId: 'device-a',
+ executionTarget: 'local',
+ localSandbox: true,
+ };
+
+ // The composer shows the topic's machine, but the save must not move the default there.
+ it('keeps the agent default when the open topic is pinned to another machine', async () => {
+ topicState.topics = {
+ 'topic-1': { agentId: 'agent-1', metadata: { boundDeviceId: 'device-b' } },
+ };
+ setupStores(localSandboxDefault);
+ const { result } = renderToggle();
+
+ await act(() => result.current(true));
+
+ expect(selectExecutionTarget).toHaveBeenCalledWith('local', 'device-a', {
+ localSandbox: true,
+ localSandboxNetwork: true,
+ });
+ });
+
+ it('does not turn the default sandbox flag on from a topic pinned to this machine', async () => {
+ topicState.topics = {
+ 'topic-1': { agentId: 'agent-1', metadata: { boundDeviceId: 'device-a' } },
+ };
+ setupStores({ boundDeviceId: 'device-b', executionTarget: 'device', localSandbox: true });
+ const { result } = renderToggle();
+
+ await act(() => result.current(false));
+
+ expect(selectExecutionTarget).toHaveBeenCalledWith('device', 'device-b', {
+ localSandbox: false,
+ localSandboxNetwork: false,
+ });
+ });
+
+ it('saves the current target unchanged when the topic has no machine binding', async () => {
+ topicState.topics = { 'topic-1': { agentId: 'agent-1' } };
+ setupStores(localSandboxDefault);
+ const { result } = renderToggle();
+
+ await act(() => result.current(false));
+
+ expect(selectExecutionTarget).toHaveBeenCalledWith('local', 'device-a', {
+ localSandbox: true,
+ localSandboxNetwork: false,
+ });
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/useSandboxNetworkToggle.ts b/src/features/ChatInput/ControlBar/useSandboxNetworkToggle.ts
new file mode 100644
index 00000000000..16599325c7a
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/useSandboxNetworkToggle.ts
@@ -0,0 +1,48 @@
+import { isDesktop } from '@lobechat/const';
+import { useCallback } from 'react';
+
+import type { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
+import { isLocalSandboxEnabled, resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
+
+interface UseSandboxNetworkToggleOptions {
+ agentId: string;
+ deviceRoutingAvailable?: boolean;
+ isHetero: boolean;
+ selectExecutionTarget: ReturnType<typeof useSelectExecutionTarget>;
+}
+
+/**
+ * Persist the local-sandbox network flag on top of the agent's UNPINNED default.
+ *
+ * The picker displays the composer topic's machine, but the save writes the
+ * agent/member default for new conversations. Re-sending the topic-bound target
+ * (or its sandbox flag) with the flag would silently re-route future topics to
+ * this topic's machine, so the rest of the write is resolved with `topicId: null`.
+ */
+export const useSandboxNetworkToggle = ({
+ agentId,
+ deviceRoutingAvailable,
+ isHetero,
+ selectExecutionTarget,
+}: UseSandboxNetworkToggleOptions) => {
+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, { topicId: null });
+ const defaultTarget = resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
+ isHetero,
+ workspaceScoped,
+ });
+ const defaultSandbox = isLocalSandboxEnabled(agencyConfig, defaultTarget);
+ const defaultBoundDeviceId = agencyConfig?.boundDeviceId;
+
+ return useCallback(
+ async (enabled: boolean) => {
+ await selectExecutionTarget(defaultTarget, defaultBoundDeviceId, {
+ localSandbox: defaultSandbox,
+ localSandboxNetwork: enabled,
+ });
+ },
+ [defaultBoundDeviceId, defaultSandbox, defaultTarget, selectExecutionTarget],
+ );
+};
diff --git a/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts
index f0b28795e43..abea26c91f2 100644
--- a/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts
+++ b/src/features/ChatInput/ControlBar/useSandboxStorageAccess.ts
@@ -11,6 +11,8 @@ import { agentByIdSelectors } from '@/store/agent/selectors';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
+import { useTopicId } from '../hooks/useTopicId';
+
/**
* What the composer should show where the sandbox working directory goes:
*
@@ -36,7 +38,8 @@ export interface SandboxStorageAccessResult {
*/
const useRunsInSandbox = (agentId: string): boolean => {
const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
- const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);
+ const topicId = useTopicId();
+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, { topicId });
const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);
return (
diff --git a/src/features/ChatInput/ControlBar/useSwitchWorktree.ts b/src/features/ChatInput/ControlBar/useSwitchWorktree.ts
index 47014965da6..527885f33f1 100644
--- a/src/features/ChatInput/ControlBar/useSwitchWorktree.ts
+++ b/src/features/ChatInput/ControlBar/useSwitchWorktree.ts
@@ -8,6 +8,8 @@ interface UseSwitchWorktreeOptions {
isGithub: boolean;
/** The repo the conversation is anchored to; worktrees are recorded relative to it. */
sourcePath: string;
+ /** The conversation the switch is recorded on; omitted, the global active topic. */
+ topicId?: string | null;
}
/**
@@ -15,8 +17,13 @@ interface UseSwitchWorktreeOptions {
* the create-worktree flow, and the branch dropdown β€” which routes into the
* worktree holding a branch rather than attempting a checkout git would reject.
*/
-export const useSwitchWorktree = ({ agentId, isGithub, sourcePath }: UseSwitchWorktreeOptions) => {
- const { commit } = useCommitWorkingDirectory(agentId);
+export const useSwitchWorktree = ({
+ agentId,
+ isGithub,
+ sourcePath,
+ topicId,
+}: UseSwitchWorktreeOptions) => {
+ const { commit } = useCommitWorkingDirectory(agentId, topicId);
return useCallback(
async (worktreePath: string, branch?: string) => {
diff --git a/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.test.ts b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.test.ts
new file mode 100644
index 00000000000..f40ff0ec97e
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.test.ts
@@ -0,0 +1,123 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTopicAwareTargetSelect } from './useTopicAwareTargetSelect';
+
+const state = vi.hoisted(() => ({
+ activeTopicId: undefined as string | undefined,
+ confirmModal: vi.fn(),
+ selectExecutionTarget: vi.fn(),
+ topics: {} as Record<string, { boundDeviceId?: string }>,
+ updateTopicMetadata: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui/base-ui', () => ({
+ confirmModal: state.confirmModal,
+ toast: { error: vi.fn() },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/hooks/useEffectiveWorkingDirectory', () => ({
+ useEffectiveWorkingDirectory: () => '/repo',
+}));
+
+vi.mock('@/services/electron/localFileService', () => ({
+ localFileService: { ensureSandboxWorkspace: vi.fn() },
+}));
+
+vi.mock('./useCommitWorkingDirectory', () => ({
+ useCommitWorkingDirectory: () => ({ commit: vi.fn() }),
+}));
+
+// Store boundary: the real topic selectors run against this state.
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: object) => unknown) =>
+ selector({
+ activeTopicId: state.activeTopicId,
+ topicDataMap: {},
+ topicDetailMap: Object.fromEntries(
+ Object.entries(state.topics).map(([id, metadata]) => [
+ id,
+ { agentId: 'agent-1', id, metadata },
+ ]),
+ ),
+ updateTopicMetadata: state.updateTopicMetadata,
+ }),
+}));
+
+const devices = [
+ { deviceId: 'device-a', friendlyName: 'Device A' },
+ { deviceId: 'device-b', friendlyName: 'Device B' },
+];
+
+const renderSelect = (topicId: string | null) =>
+ renderHook(() =>
+ useTopicAwareTargetSelect({
+ agentId: 'agent-1',
+ devices,
+ selectExecutionTarget: state.selectExecutionTarget,
+ topicId,
+ }),
+ );
+
+beforeEach(() => {
+ // The main column's topic stays globally active while a side pane renders another.
+ state.activeTopicId = 'main-topic';
+ state.topics = {
+ 'main-topic': { boundDeviceId: 'device-b' },
+ 'pane-topic': { boundDeviceId: 'device-a' },
+ };
+ state.confirmModal.mockReset();
+ state.selectExecutionTarget.mockReset().mockResolvedValue(true);
+ state.updateTopicMetadata.mockReset().mockResolvedValue(undefined);
+});
+
+describe('useTopicAwareTargetSelect', () => {
+ // Moving a topic drops its CLI session and cwd, so it must hit the given topic.
+ it('moves the given topic to the picked device after confirmation', async () => {
+ const { result } = renderSelect('pane-topic');
+
+ expect(result.current.topicDeviceId).toBe('device-a');
+ await act(() => result.current.selectTarget('device', 'device-b'));
+ expect(state.confirmModal).toHaveBeenCalledTimes(1);
+
+ await act(() => state.confirmModal.mock.calls[0][0].onOk());
+
+ expect(state.updateTopicMetadata).toHaveBeenCalledTimes(1);
+ expect(state.updateTopicMetadata).toHaveBeenCalledWith(
+ 'pane-topic',
+ expect.objectContaining({ boundDeviceId: 'device-b', heteroSessionId: undefined }),
+ );
+ expect(state.selectExecutionTarget).toHaveBeenCalledWith('device', 'device-b', {
+ localSandbox: undefined,
+ });
+ });
+
+ it('switches the agent target without touching any topic when the conversation has none', async () => {
+ const { result } = renderSelect(null);
+
+ expect(result.current.topicDeviceId).toBeUndefined();
+ await act(() => result.current.selectTarget('device', 'device-a'));
+
+ expect(state.confirmModal).not.toHaveBeenCalled();
+ expect(state.updateTopicMetadata).not.toHaveBeenCalled();
+ expect(state.selectExecutionTarget).toHaveBeenCalledWith('device', 'device-a', {
+ localSandbox: undefined,
+ });
+ });
+
+ it('keeps the topic pin when the picked device is the one it already runs on', async () => {
+ const { result } = renderSelect('pane-topic');
+
+ await act(() => result.current.selectTarget('device', 'device-a'));
+
+ expect(state.confirmModal).not.toHaveBeenCalled();
+ expect(state.updateTopicMetadata).not.toHaveBeenCalled();
+ expect(state.selectExecutionTarget).toHaveBeenCalledWith('device', 'device-a', {
+ localSandbox: undefined,
+ });
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.ts b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.ts
new file mode 100644
index 00000000000..8c06ac23a33
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.ts
@@ -0,0 +1,158 @@
+import type { DeviceExecutionTarget } from '@lobechat/types';
+import { confirmModal, toast } from '@lobehub/ui/base-ui';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
+import { getTopicBoundDeviceId } from '@/helpers/executionTarget';
+import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
+import { localFileService } from '@/services/electron/localFileService';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import { moveTopicToTarget } from './moveTopicToTarget';
+import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';
+
+interface TargetDevice {
+ deviceId: string;
+ friendlyName?: string | null;
+ hostname?: string | null;
+}
+
+interface UseTopicAwareTargetSelectOptions {
+ agentId: string;
+ /** This desktop's own gateway device id, when known. */
+ currentDeviceId?: string;
+ devices?: TargetDevice[];
+ selectExecutionTarget: ReturnType<typeof useSelectExecutionTarget>;
+ /** The composer's own topic (see `useTopicId`); `null` when it has none. */
+ topicId: string | null;
+}
+
+/**
+ * Pick an execution target for the agent while honouring the composer topic's
+ * machine binding: a topic that already ran on another machine is moved only
+ * after confirmation, and the move drops the cwd and CLI session that only hold
+ * on the old machine.
+ */
+export const useTopicAwareTargetSelect = ({
+ agentId,
+ currentDeviceId,
+ devices,
+ selectExecutionTarget,
+ topicId,
+}: UseTopicAwareTargetSelectOptions) => {
+ const { t } = useTranslation('chat');
+
+ // `homeFallback: false` on purpose β€” this must reflect whether the user has
+ // actually chosen a directory, not the runtime's convenience fallback.
+ const configuredWorkingDirectory = useEffectiveWorkingDirectory(agentId, {
+ homeFallback: false,
+ topicId,
+ });
+ const { commit: commitWorkingDirectory } = useCommitWorkingDirectory(agentId, topicId);
+
+ /**
+ * Give a sandboxed agent somewhere to work when the user has not picked a
+ * directory yet.
+ *
+ * The fence is scoped to the working directory, so without one the run is
+ * refused β€” a first use that fails on a requirement the picker never
+ * mentioned. Rather than fence a directory nobody chose *silently*, the
+ * default is written into the same setting the chip reads, so the answer to
+ * "where is this running?" stays visible and changeable.
+ */
+ // `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],
+ );
+
+ // 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 topicDeviceId = useChatStore((s) =>
+ getTopicBoundDeviceId(topicId ? topicSelectors.getTopicById(topicId)(s) : undefined, agentId),
+ );
+ const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);
+
+ const selectTarget = useCallback(
+ async (target: DeviceExecutionTarget, deviceId?: string, localSandbox?: boolean) => {
+ 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 (!topicId || !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(topicId, {
+ 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'),
+ });
+ },
+ [
+ currentDeviceId,
+ devices,
+ ensureSandboxWorkingDirectory,
+ selectExecutionTarget,
+ t,
+ topicDeviceId,
+ topicId,
+ updateTopicMetadata,
+ ],
+ );
+
+ return { selectTarget, topicDeviceId };
+};
diff --git a/src/features/ChatInput/ControlBar/useTopicRepoSelection.test.ts b/src/features/ChatInput/ControlBar/useTopicRepoSelection.test.ts
new file mode 100644
index 00000000000..d873503b5c0
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/useTopicRepoSelection.test.ts
@@ -0,0 +1,82 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getPendingTopicRepos, setPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
+
+import { useTopicRepoSelection } from './useTopicRepoSelection';
+
+const REPO = 'https://github.com/lobehub/lobehub';
+
+const state = vi.hoisted(() => ({
+ activeTopicId: undefined as string | undefined,
+ /** `undefined`: the host publishes no topic; `null`: its conversation has none. */
+ composerTopicId: undefined as string | null | undefined,
+ topics: {} as Record<string, { repos?: string[]; workingDirectory?: string }>,
+ updateTopicMetadata: vi.fn(),
+}));
+
+vi.mock('../store', () => ({
+ useChatInputStore: (selector: (s: object) => unknown) =>
+ selector({ topicId: state.composerTopicId }),
+}));
+
+// Store boundary: the real topic selectors run against this state.
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: object) => unknown) =>
+ selector({
+ activeTopicId: state.activeTopicId,
+ topicDataMap: {},
+ topicDetailMap: Object.fromEntries(
+ Object.entries(state.topics).map(([id, metadata]) => [id, { id, metadata }]),
+ ),
+ updateTopicMetadata: state.updateTopicMetadata,
+ }),
+}));
+
+beforeEach(() => {
+ // The main column's topic stays globally active while a side pane renders another.
+ state.activeTopicId = 'main-topic';
+ state.composerTopicId = undefined;
+ state.topics = {
+ 'main-topic': { repos: [REPO], workingDirectory: REPO },
+ 'pane-topic': {},
+ };
+ state.updateTopicMetadata.mockReset();
+ setPendingTopicRepos('agent-1', []);
+});
+
+describe('useTopicRepoSelection', () => {
+ it("toggles repos on the composer's own topic rather than the global active topic", async () => {
+ state.composerTopicId = 'pane-topic';
+ const { result } = renderHook(() => useTopicRepoSelection('agent-1', true));
+
+ expect(result.current.displayRepos).toEqual([]);
+ await act(() => result.current.toggleRepo(REPO));
+
+ expect(state.updateTopicMetadata).toHaveBeenCalledWith('pane-topic', {
+ repos: [REPO],
+ workingDirectory: REPO,
+ workingDirectoryConfig: { path: REPO, repoType: 'github' },
+ });
+ });
+
+ it('buffers the selection when the composer conversation has no topic, even with an active topic', async () => {
+ state.composerTopicId = null;
+ const { result } = renderHook(() => useTopicRepoSelection('agent-1', true));
+
+ await act(() => result.current.toggleRepo(REPO));
+
+ expect(state.updateTopicMetadata).not.toHaveBeenCalled();
+ expect(getPendingTopicRepos('agent-1')).toEqual([REPO]);
+ expect(result.current.displayRepos).toEqual([REPO]);
+ });
+
+ it('ignores toggles without edit permission', async () => {
+ state.composerTopicId = 'pane-topic';
+ const { result } = renderHook(() => useTopicRepoSelection('agent-1', false));
+
+ await act(() => result.current.toggleRepo(REPO));
+
+ expect(state.updateTopicMetadata).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/useTopicRepoSelection.ts b/src/features/ChatInput/ControlBar/useTopicRepoSelection.ts
new file mode 100644
index 00000000000..98ac67966ad
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/useTopicRepoSelection.ts
@@ -0,0 +1,71 @@
+import { useCallback, useState } from 'react';
+
+import { useChatStore } from '@/store/chat';
+import { getPendingTopicRepos, setPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import { useTopicId } from '../hooks/useTopicId';
+
+/**
+ * The cloud repos selected for this composer's conversation, and the toggle
+ * that edits them.
+ *
+ * The topic is the composer's own (see `useTopicId`), never the global active
+ * topic: a side-by-side pane must not toggle the main column's repos. Before a
+ * topic exists the selection is buffered by agent and carried by the first send.
+ */
+export const useTopicRepoSelection = (agentId: string, canEdit: boolean) => {
+ // Incremented to trigger re-renders when the module-singleton pending selection changes.
+ const [, forceUpdate] = useState(0);
+
+ const topicId = useTopicId();
+ // Repos persisted to the topic (empty when no topic or none set)
+ const topicRepos: string[] = useChatStore(
+ (s) => (topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata?.repos : undefined) ?? [],
+ );
+ const currentWorkingDirectory = useChatStore((s) =>
+ topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata?.workingDirectory : undefined,
+ );
+ const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);
+
+ const toggleRepo = useCallback(
+ async (repo: string) => {
+ if (!canEdit) return;
+
+ if (!topicId) {
+ // No topic yet β€” buffer in the module singleton keyed by agentId.
+ // gateway.ts will read and consume this when the first message creates a topic.
+ const prev = getPendingTopicRepos(agentId);
+ const isSelected = prev.includes(repo);
+ const next = isSelected ? prev.filter((r) => r !== repo) : [...prev, repo];
+ setPendingTopicRepos(agentId, next);
+ forceUpdate((v) => v + 1);
+ return;
+ }
+
+ const isSelected = topicRepos.includes(repo);
+ const nextRepos = isSelected ? topicRepos.filter((r) => r !== repo) : [...topicRepos, repo];
+
+ // Only set workingDirectory when it hasn't been assigned yet (first selection).
+ // Once set, it stays fixed so the topic keeps its sidebar grouping.
+ const patch: {
+ repos: string[];
+ workingDirectory?: string;
+ workingDirectoryConfig?: { path: string; repoType: 'github' };
+ } = { repos: nextRepos };
+ if (!currentWorkingDirectory && nextRepos.length > 0) {
+ patch.workingDirectory = nextRepos[0];
+ patch.workingDirectoryConfig = { path: nextRepos[0], repoType: 'github' };
+ }
+
+ await updateTopicMetadata(topicId, patch);
+ },
+ [agentId, canEdit, currentWorkingDirectory, topicId, topicRepos, updateTopicMetadata],
+ );
+
+ // When a topic exists, show its persisted repos.
+ // When no topic exists yet, show the pending selection from the module singleton.
+ const displayRepos = topicId ? topicRepos : getPendingTopicRepos(agentId);
+
+ return { displayRepos, toggleRepo };
+};
diff --git a/src/features/ChatInput/ControlBar/useWorkspaceSurface.ts b/src/features/ChatInput/ControlBar/useWorkspaceSurface.ts
index 15fa97f2d16..f2f4352ba38 100644
--- a/src/features/ChatInput/ControlBar/useWorkspaceSurface.ts
+++ b/src/features/ChatInput/ControlBar/useWorkspaceSurface.ts
@@ -7,6 +7,8 @@ import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useTopicId } from '../hooks/useTopicId';
+
/**
* Which workspace controls sit next to the device switcher, in order:
*
@@ -102,7 +104,8 @@ export const useWorkspaceSurface = (
alwaysShowWorkspace = false,
): WorkspaceSurface[] => {
const isHetero = useAgentStore(agentByIdSelectors.isAgentHeterogeneousById(agentId));
- const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId);
+ const topicId = useTopicId();
+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, { topicId });
const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);
return resolveWorkspaceSurface({
diff --git a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.projectSkills.test.ts b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.projectSkills.test.ts
new file mode 100644
index 00000000000..7246ca47ad1
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.projectSkills.test.ts
@@ -0,0 +1,87 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useSlashActionItems } from './useSlashActionItems';
+
+const state = vi.hoisted(() => ({
+ /** `undefined`: the host publishes no topic; `null`: its conversation has none. */
+ composerTopicId: undefined as string | null | undefined,
+ useFetchProjectSkills: vi.fn(() => ({ data: undefined })),
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/features/ChatInput/store', () => ({
+ useChatInputStore: (selector: (s: object) => unknown) =>
+ selector({ agentId: 'agent-1', editor: undefined, topicId: state.composerTopicId }),
+}));
+
+vi.mock('@/helpers/gatewayMode', () => ({ useIsGatewayModeEnabled: () => true }));
+
+// The main column's topic runs in the cloud sandbox; the side-by-side pane's
+// topic is pinned to a device.
+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
+ useEffectiveAgencyConfig: (_agentId: string, options?: { topicId?: string | null }) => ({
+ agencyConfig:
+ options?.topicId === 'pane-topic'
+ ? {
+ boundDeviceId: 'pane-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'codex' },
+ }
+ : { executionTarget: 'sandbox', heterogeneousProvider: { type: 'codex' } },
+ workspaceScoped: false,
+ }),
+}));
+
+vi.mock('@/hooks/useEffectiveWorkingDirectory', () => ({
+ useEffectiveWorkingDirectory: () => '/repo/pane',
+}));
+
+vi.mock('@/hooks/useFetchProjectSkills', () => ({
+ useFetchProjectSkills: state.useFetchProjectSkills,
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: object) => unknown) => selector({ agentMap: {} }),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentByIdSelectors: {
+ getAgencyConfigById: () => () => ({ executionTarget: 'sandbox' }),
+ isAgentHeterogeneousById: () => () => true,
+ isWorkspaceAgentById: () => () => false,
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: object) => unknown) => selector({ activeTopicId: 'main-topic' }),
+}));
+
+vi.mock('@/store/tool', () => ({
+ useToolStore: (selector: (s: object) => unknown) =>
+ selector({ useFetchAgentDocumentSkills: () => undefined }),
+}));
+
+vi.mock('@/store/tool/selectors', () => ({
+ agentDocumentSkillsSelectors: { getAgentDocumentSkills: () => () => [] },
+}));
+
+vi.mock('./useInstalledSkillsAndTools', () => ({ useInstalledSkillsAndTools: () => [] }));
+
+beforeEach(() => {
+ state.composerTopicId = undefined;
+ state.useFetchProjectSkills.mockClear();
+});
+
+describe('useSlashActionItems Β· project skills', () => {
+ it("scans project skills on the device the composer's own topic is pinned to", () => {
+ state.composerTopicId = 'pane-topic';
+
+ renderHook(() => useSlashActionItems());
+
+ expect(state.useFetchProjectSkills).toHaveBeenLastCalledWith('/repo/pane', 'pane-device');
+ });
+});
diff --git a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts
index f79656714c3..e6abab5da28 100644
--- a/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts
+++ b/src/features/ChatInput/InputEditor/ActionTag/useSlashActionItems.ts
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { useFetchProjectSkills } from '@/hooks/useFetchProjectSkills';
import { useAgentStore } from '@/store/agent';
@@ -21,6 +22,7 @@ import { agentDocumentSkillsSelectors } from '@/store/tool/selectors';
import type { AgentDocumentSkillItem } from '@/store/tool/slices/agentDocumentSkills/initialState';
import { useAgentId } from '../../hooks/useAgentId';
+import { useTopicId } from '../../hooks/useTopicId';
import { useChatInputStore } from '../../store';
import { INSERT_ACTION_TAG_COMMAND, type InsertActionTagPayload } from './command';
import { insertGoalTag } from './goalTag';
@@ -55,7 +57,9 @@ export const useSlashActionItems = (): SlashOptions['items'] => {
// Unified cwd: topic > agent's per-device choice > device default > home.
// This is what makes project skills load even when only a device default is
// set (and for local-device runs), not just an explicit agent/topic pick.
- const workingDirectory = useEffectiveWorkingDirectory(agentId);
+ // Scoped to this composer's topic (see `useTopicId`), not the global one.
+ const topicId = useTopicId();
+ const workingDirectory = useEffectiveWorkingDirectory(agentId, { topicId });
// Device-bound (remote) runs scan filesystem skills on that device over the
// `device.listProjectSkills` RPC; the local desktop reads over Electron IPC.
@@ -64,22 +68,19 @@ export const useSlashActionItems = (): SlashOptions['items'] => {
// effective target matters because a hetero agent saved as desktop "This
// device" (`local` + boundDeviceId) coerces to `device` when opened on web β€”
// reading the raw stored target would miss that and leave the menu empty even
- // though the sidebar lists the skills.
- const agencyConfig = useAgentStore((s) =>
- agentId ? agentByIdSelectors.getAgencyConfigById(agentId)(s) : undefined,
- );
+ // though the sidebar lists the skills. The config is the same effective one
+ // the working directory above resolved against (member override + this
+ // topic's device binding), so the path is read on the machine it lives on.
+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, { topicId });
const isHetero = useAgentStore((s) =>
agentId ? agentByIdSelectors.isAgentHeterogeneousById(agentId)(s) : false,
);
const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);
- const isWorkspaceAgent = useAgentStore((s) =>
- agentId ? agentByIdSelectors.isWorkspaceAgentById(agentId)(s) : false,
- );
const effectiveTarget = resolveExecutionTarget(agencyConfig, {
clientExecutionAvailable: isDesktop,
deviceRoutingAvailable,
isHetero,
- workspaceScoped: isWorkspaceAgent,
+ workspaceScoped,
});
const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
const remoteDeviceId = isDeviceMode ? agencyConfig.boundDeviceId : undefined;
diff --git a/src/hooks/useEffectiveWorkingDirectory.test.ts b/src/hooks/useEffectiveWorkingDirectory.test.ts
index d3aa5cfc9ba..90711b668e3 100644
--- a/src/hooks/useEffectiveWorkingDirectory.test.ts
+++ b/src/hooks/useEffectiveWorkingDirectory.test.ts
@@ -63,11 +63,13 @@ const setupStores = ({
agencyConfig,
deviceDefaultCwd,
legacyWorkingDirectory,
+ topicMetadata,
topicWorkingDirectory,
}: {
agencyConfig?: unknown;
deviceDefaultCwd?: string;
legacyWorkingDirectory?: string;
+ topicMetadata?: object;
topicWorkingDirectory?: string;
} = {}) => {
effectiveAgencyConfig.agencyConfig = agencyConfig;
@@ -77,7 +79,7 @@ const setupStores = ({
? { 'agent-1': legacyWorkingDirectory }
: {},
};
- const chatState = { topicMetadata: undefined, topicWorkingDirectory };
+ const chatState = { topicMetadata, topicWorkingDirectory };
const deviceState = { deviceDefaultCwd, useFetchDevices: vi.fn() };
const electronState = { gatewayDeviceInfo: { deviceId: 'device-A' } };
const userState = {};
@@ -173,6 +175,24 @@ describe('useEffectiveWorkingDirectory', () => {
expect(result.current).toBe('/repo/agent-default');
});
+ it('does not inherit the active topic directory config for a new-topic pane', () => {
+ setupStores({
+ agencyConfig: { workingDirByDevice: { 'device-A': '/repo/agent-default' } },
+ topicMetadata: {
+ workingDirectoryConfig: { path: '/repo/other-pane-topic', repoType: 'git' },
+ },
+ });
+
+ const { result } = renderHook(() =>
+ useEffectiveWorkingDirectory('agent-1', {
+ homeFallback: false,
+ topicId: null,
+ }),
+ );
+
+ expect(result.current).toBe('/repo/agent-default');
+ });
+
it('keeps the device default cwd with homeFallback disabled', () => {
setupStores({ deviceDefaultCwd: '/repo/device-default' });
diff --git a/src/hooks/useEffectiveWorkingDirectory.ts b/src/hooks/useEffectiveWorkingDirectory.ts
index fb6d8a7f2ac..5528afa8610 100644
--- a/src/hooks/useEffectiveWorkingDirectory.ts
+++ b/src/hooks/useEffectiveWorkingDirectory.ts
@@ -56,10 +56,14 @@ export const useEffectiveWorkingDirectory = (
agentId ? s.localAgentWorkingDirectoryMap[agentId] : undefined,
);
const topicWorkingDirectory = useChatStore(topicSelectors.getTopicWorkingDirectory(topicId));
+ // `null` means "this conversation has no topic", the same as for
+ // `getTopicWorkingDirectory` β€” it must not inherit the active topic's config.
const topicWorkingDirectoryConfig = useChatStore((s) =>
- topicId
- ? topicSelectors.getTopicById(topicId)(s)?.metadata?.workingDirectoryConfig
- : topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,
+ topicId === null
+ ? undefined
+ : topicId
+ ? topicSelectors.getTopicById(topicId)(s)?.metadata?.workingDirectoryConfig
+ : topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,
);
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const targetDeviceId = resolveTargetDeviceId(agencyConfig, currentDeviceId, {
diff --git a/src/hooks/useRemoteAgentDeviceGuard.test.ts b/src/hooks/useRemoteAgentDeviceGuard.test.ts
index 8c6ebb82d97..eced2272818 100644
--- a/src/hooks/useRemoteAgentDeviceGuard.test.ts
+++ b/src/hooks/useRemoteAgentDeviceGuard.test.ts
@@ -142,4 +142,30 @@ describe('useRemoteAgentDeviceGuard', () => {
await waitFor(() => expect(result.current.status).toBe('no-device'));
});
+
+ // A side-by-side portal pane pins its own device while the main column's
+ // topic, still globally active, is bound elsewhere.
+ it("checks the device bound to the conversation's own topic", async () => {
+ mockedUseEffectiveAgencyConfig.mockImplementation((_agentId, options) => ({
+ agencyConfig: {
+ boundDeviceId: options?.topicId === 'pane-topic' ? 'pane-device' : 'main-device',
+ executionTarget: 'device',
+ heterogeneousProvider: { type: 'codex' },
+ },
+ canDisplayExecutionTarget: true,
+ canSelectExecutionTarget: true,
+ isPreferenceLoading: false,
+ workspaceScoped: false,
+ }));
+ mockedListDevices.mockResolvedValue([
+ { deviceId: 'main-device', online: false },
+ { deviceId: 'pane-device', online: true },
+ ] as never);
+
+ const { result } = renderHook(() =>
+ useRemoteAgentDeviceGuard({ agentId: 'agent-1', topicId: 'pane-topic' }),
+ );
+
+ await waitFor(() => expect(result.current.status).toBe('ok'));
+ });
});
diff --git a/src/hooks/useRemoteAgentDeviceGuard.ts b/src/hooks/useRemoteAgentDeviceGuard.ts
index eb0b6edc143..9337422e4bd 100644
--- a/src/hooks/useRemoteAgentDeviceGuard.ts
+++ b/src/hooks/useRemoteAgentDeviceGuard.ts
@@ -11,6 +11,12 @@ interface UseRemoteAgentDeviceGuardOptions {
/** The conversation's agent β€” validate this agent's bound device, not the global active one. */
agentId: string;
enabled?: boolean;
+ /**
+ * The conversation's topic, whose device binding applies β€” a side-by-side
+ * pane must not validate the globally active topic's device. `null` means the
+ * conversation has no topic; omitted, it follows the active topic.
+ */
+ topicId?: string | null;
}
interface UseRemoteAgentDeviceGuardResult {
@@ -26,12 +32,13 @@ interface UseRemoteAgentDeviceGuardResult {
export const useRemoteAgentDeviceGuard = ({
agentId,
enabled = true,
+ topicId,
}: UseRemoteAgentDeviceGuardOptions): UseRemoteAgentDeviceGuardResult => {
// Effective config = shared row + this member's per-agent device override
//. Checking the raw shared `boundDeviceId` would probe whichever
// machine landed on the shared row (usually the creator's, often offline)
// instead of the device THIS member picked β€” a false "device offline".
- const { agencyConfig, isPreferenceLoading } = useEffectiveAgencyConfig(agentId);
+ const { agencyConfig, isPreferenceLoading } = useEffectiveAgencyConfig(agentId, { topicId });
const boundDeviceId = agencyConfig?.boundDeviceId;
const providerType = agencyConfig?.heterogeneousProvider?.type;
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx
index 99055870521..3de84c3c7f5 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx
@@ -8,6 +8,7 @@ import { Select } from '@lobehub/ui/base-ui';
import isEqual from 'fast-deep-equal';
import { memo, useMemo } from 'react';
+import { useTopicId } from '@/features/ChatInput/hooks/useTopicId';
import { useProviderBindingCompatibleProviders } from '@/features/HeterogeneousAgent/hooks/useProviderBinding';
import {
buildServerDefaultModelOptions,
@@ -35,8 +36,12 @@ const ApiModeModelBar = memo<ApiModeModelBarProps>(({ agentId }) => {
const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
const updateAgentConfigById = useAgentStore((state) => state.updateAgentConfigById);
const heterogeneousProvider = agencyConfig?.heterogeneousProvider;
- const activeTopicId = useChatStore((state) => state.activeTopicId);
- const topicModel = useChatStore(topicSelectors.activeTopicHeteroPin, isEqual);
+ // This composer's conversation (see `useTopicId`), never the global active topic.
+ const topicId = useTopicId();
+ const topicModel = useChatStore(
+ (state) => (topicId ? topicSelectors.getTopicHeteroPinById(topicId)(state) : undefined),
+ isEqual,
+ );
const updateTopicModel = useChatStore((state) => state.updateTopicModel);
const { providers } = useProviderBindingCompatibleProviders(heterogeneousProvider?.type);
const providerIds = useMemo(() => providers.map(({ id }) => id), [providers]);
@@ -79,8 +84,8 @@ const ApiModeModelBar = memo<ApiModeModelBarProps>(({ agentId }) => {
effectiveApiConfig?.source !== 'server-default' ? effectiveApiConfig : undefined;
const persist = async (apiConfig: HeterogeneousApiConfig) => {
- if (activeTopicId && apiConfig.source !== 'server-default' && apiConfig.providerId) {
- await updateTopicModel(activeTopicId, {
+ if (topicId && apiConfig.source !== 'server-default' && apiConfig.providerId) {
+ await updateTopicModel(topicId, {
model: apiConfig.model,
provider: apiConfig.providerId,
});
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
index 0d93fcb2218..53e2d8a5220 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
@@ -91,6 +91,9 @@ const HeterogeneousChatInput = memo(() => {
// agent that `agencyConfig`/`isDeviceExecution` are computed from, instead of
// the global (hijack-prone) active agent.
const agentId = useConversationStore(contextSelectors.agentId);
+ // The conversation's own topic: a side-by-side pane must gate on its topic's
+ // device binding, not the main column's.
+ const topicId = useConversationStore(contextSelectors.topicId);
const { isConfigured, goToConfig } = useHeteroAgentCloudConfig(agentId);
const navigate = useWorkspaceAwareNavigate();
@@ -101,7 +104,10 @@ const HeterogeneousChatInput = memo(() => {
// While the preference is loading, the merged config may still reflect only
// the shared row β€” hold the input closed (below) instead of gating device
// runs off a value that can flip once the override arrives.
- const { agencyConfig, isPreferenceLoading, workspaceScoped } = useEffectiveAgencyConfig(agentId);
+ const scopeTopicId = topicId ?? null;
+ const { agencyConfig, isPreferenceLoading, workspaceScoped } = useEffectiveAgencyConfig(agentId, {
+ topicId: scopeTopicId,
+ });
const heterogeneousProvider = agencyConfig?.heterogeneousProvider;
const providerType = heterogeneousProvider?.type;
const isApiAuth = heterogeneousProvider?.authMode === 'api';
@@ -172,7 +178,11 @@ const HeterogeneousChatInput = memo(() => {
// instead of failing at dispatch time.
const isDeviceExecution = executionTarget === 'device' && !!agencyConfig?.boundDeviceId;
- const { status, refresh } = useRemoteAgentDeviceGuard({ agentId, enabled: isDeviceExecution });
+ const { status, refresh } = useRemoteAgentDeviceGuard({
+ agentId,
+ enabled: isDeviceExecution,
+ topicId: scopeTopicId,
+ });
const goToAgentProfile = () => {
if (agentId) navigate(`/agent/${agentId}/profile`);