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): show the staged project directory after a device subgroup "+" (#21076)

Arvin Xu095202056f4e
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index b031dba2ce2..da49d05c9c5 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -73,6 +73,7 @@
"directories.repository": "GitHub repository URL (optional)",
"directories.repositoryHint": "This records the source repository. It does not clone or synchronize files. Do not include credentials.",
"directories.sourceSummary": "Existing directory",
+ "directories.stagedNewTopic": "A new topic will start in <project>{{name}}</project>",
"directories.start": "Start work here",
"directories.startInProject": "Start work in {{name}}",
"directories.title": "Working directories",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index b8aa5bfdc50..7f297a1af4d 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -73,6 +73,7 @@
"directories.repository": "GitHub 仓库地址(可选)",
"directories.repositoryHint": "此处记录来源仓库,不会克隆或同步文件。请勿填写凭据。",
"directories.sourceSummary": "已有目录",
+ "directories.stagedNewTopic": "将在 <project>{{name}}</project> 项目中开始新话题",
"directories.start": "在此开始工作",
"directories.startInProject": "在 {{name}} 中开始工作",
"directories.title": "工作目录",
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 5f59e44e511..b229eb4ac29 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -92,6 +92,7 @@ export default {
'directories.boundRoot':
'This conversation is bound to a project directory. Start a new conversation to use a different directory.',
'directories.detectRepository': 'Detect GitHub repository',
+ 'directories.stagedNewTopic': 'A new topic will start in <project>{{name}}</project>',
'directories.unavailable':
'Device is offline or the directory is unavailable. Reconnect and retry.',
diff --git a/src/features/AgentHome/StagedProjectHint.tsx b/src/features/AgentHome/StagedProjectHint.tsx
new file mode 100644
index 00000000000..da9bd1c0709
--- /dev/null
+++ b/src/features/AgentHome/StagedProjectHint.tsx
@@ -0,0 +1,90 @@
+'use client';
+
+import { createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
+import { FolderIcon } from 'lucide-react';
+import { memo } from 'react';
+import { Trans } from 'react-i18next';
+
+import Avatar from '@/components/Avatar';
+import { projectDirectoryDeviceName } from '@/features/ChatInput/ControlBar/projectDeviceTargets';
+import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
+import { ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';
+
+import { useStagedNewTopicDirectory } from './useStagedNewTopicDirectory';
+
+const styles = createStaticStyles(({ css }) => ({
+ card: css`
+ overflow: hidden;
+
+ width: 100%;
+ padding-block: 12px;
+ padding-inline: 12px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ path: css`
+ overflow: hidden;
+
+ min-width: 0;
+
+ font-family: ${cssVar.fontFamilyCode};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ project: css`
+ font-weight: 600;
+ color: ${cssVar.colorText};
+ `,
+}));
+
+/**
+ * Tells a blank conversation opened by a project device group's "+" where its
+ * first message will start the topic: the project, the device and the
+ * project's directory there. The composer's device chip says the same in
+ * short; this is the sentence that makes it read as "a new topic in this
+ * project" rather than a stray setting.
+ */
+const StagedProjectHint = memo(() => {
+ const directory = useStagedNewTopicDirectory();
+ const { data: devices } = useDeviceList();
+
+ if (!directory) return null;
+
+ return (
+ <Flexbox horizontal align={'center'} className={styles.card} gap={12}>
+ <Avatar
+ avatar={directory.projectAvatar || undefined}
+ name={directory.projectName}
+ shape={'square'}
+ size={32}
+ />
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Text fontSize={14}>
+ <Trans
+ components={{ project: <span className={styles.project} /> }}
+ i18nKey={'directories.stagedNewTopic'}
+ ns={'project'}
+ values={{ name: directory.projectName }}
+ />
+ </Text>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={6}
+ style={{ color: cssVar.colorTextTertiary, fontSize: 12, minWidth: 0 }}
+ >
+ <ExecutionTargetIcon devicePlatform={directory.platform} target={'device'} />
+ <span style={{ flex: 'none' }}>{projectDirectoryDeviceName(directory, devices)}</span>
+ <Icon icon={FolderIcon} size={12} style={{ flex: 'none', marginInlineStart: 4 }} />
+ <span className={styles.path} title={directory.path}>
+ {directory.path}
+ </span>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default StagedProjectHint;
diff --git a/src/features/AgentHome/index.tsx b/src/features/AgentHome/index.tsx
index 5873acd10f1..c929a18b589 100644
--- a/src/features/AgentHome/index.tsx
+++ b/src/features/AgentHome/index.tsx
@@ -10,6 +10,7 @@ import { agentSelectors } from '@/store/agent/selectors';
import AgentInfo from './AgentInfo';
import OpeningQuestions from './OpeningQuestions';
+import StagedProjectHint from './StagedProjectHint';
import { useWelcomeExtra } from './WelcomeExtraContext';
const AgentHome = memo(() => {
@@ -20,7 +21,10 @@ const AgentHome = memo(() => {
<>
<Flexbox flex={1} />
<Flexbox gap={32} style={{ paddingBottom: 'max(4vh, 16px)' }} width={'100%'}>
- <AgentInfo />
+ <Flexbox gap={16}>
+ <AgentInfo />
+ <StagedProjectHint />
+ </Flexbox>
{extra}
{openingQuestions.length > 0 && <OpeningQuestions questions={openingQuestions} />}
<ToolAuthAlert />
diff --git a/src/features/AgentHome/useStagedNewTopicDirectory.test.ts b/src/features/AgentHome/useStagedNewTopicDirectory.test.ts
new file mode 100644
index 00000000000..dc9957e6ba2
--- /dev/null
+++ b/src/features/AgentHome/useStagedNewTopicDirectory.test.ts
@@ -0,0 +1,79 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useStagedNewTopicDirectory } from './useStagedNewTopicDirectory';
+
+const state = vi.hoisted(() => ({
+ context: { agentId: 'agent-1', topicId: null as string | null },
+ pendingNewTopicDirectory: undefined as
+ { agentId: string; projectWorkingDirectoryId: string } | undefined,
+}));
+
+const directories = vi.hoisted(() => [
+ {
+ deviceId: 'device-b',
+ deviceName: 'Main MBP',
+ id: 'dir-b',
+ path: '/Users/me/Code/lobehub',
+ projectId: 'project-1',
+ projectName: 'LobeHub',
+ },
+]);
+
+vi.mock('@/features/Conversation/store', () => ({
+ contextSelectors: {
+ agentId: (s: typeof state) => s.context.agentId,
+ topicId: (s: typeof state) => s.context.topicId,
+ },
+ useConversationStore: (selector: (s: typeof state) => unknown) => selector(state),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: typeof state) => unknown) => selector(state),
+}));
+
+vi.mock('@/store/projectWorkingDirectory', () => ({
+ useProjectDirectories: () => directories,
+ useProjectDirectoryStore: (selector: (s: object) => unknown) =>
+ selector({ useFetchDirectories: () => undefined }),
+}));
+
+describe('useStagedNewTopicDirectory', () => {
+ beforeEach(() => {
+ state.context = { agentId: 'agent-1', topicId: null };
+ state.pendingNewTopicDirectory = undefined;
+ });
+
+ // A device subgroup's "+" opens a blank conversation; the welcome has to say
+ // the new topic starts in that project, on that device and directory.
+ it('returns the staged directory of a blank conversation', () => {
+ state.pendingNewTopicDirectory = { agentId: 'agent-1', projectWorkingDirectoryId: 'dir-b' };
+
+ const { result } = renderHook(() => useStagedNewTopicDirectory());
+
+ expect(result.current).toBe(directories[0]);
+ });
+
+ it('is undefined without a staging', () => {
+ const { result } = renderHook(() => useStagedNewTopicDirectory());
+
+ expect(result.current).toBeUndefined();
+ });
+
+ it("ignores another agent's staging", () => {
+ state.pendingNewTopicDirectory = { agentId: 'agent-2', projectWorkingDirectoryId: 'dir-b' };
+
+ const { result } = renderHook(() => useStagedNewTopicDirectory());
+
+ expect(result.current).toBeUndefined();
+ });
+
+ it('is undefined once the conversation has a topic', () => {
+ state.context.topicId = 'topic-1';
+ state.pendingNewTopicDirectory = { agentId: 'agent-1', projectWorkingDirectoryId: 'dir-b' };
+
+ const { result } = renderHook(() => useStagedNewTopicDirectory());
+
+ expect(result.current).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentHome/useStagedNewTopicDirectory.ts b/src/features/AgentHome/useStagedNewTopicDirectory.ts
new file mode 100644
index 00000000000..26e155df131
--- /dev/null
+++ b/src/features/AgentHome/useStagedNewTopicDirectory.ts
@@ -0,0 +1,24 @@
+import { stagedProjectDirectoryIdSelector } from '@/features/ChatInput/ControlBar/useProjectTopicDirectory';
+import { contextSelectors, useConversationStore } from '@/features/Conversation/store';
+import { useChatStore } from '@/store/chat';
+import {
+ type ProjectDirectory,
+ useProjectDirectories,
+ useProjectDirectoryStore,
+} from '@/store/projectWorkingDirectory';
+
+/**
+ * The project directory this welcome's blank conversation was opened in by a
+ * project device group's "+", or undefined for any other conversation. Its
+ * ids come from the conversation, not the composer, since the welcome sits
+ * outside the ChatInput.
+ */
+export const useStagedNewTopicDirectory = (): ProjectDirectory | undefined => {
+ const agentId = useConversationStore(contextSelectors.agentId);
+ const topicId = useConversationStore(contextSelectors.topicId);
+ const directoryId = useChatStore(stagedProjectDirectoryIdSelector(agentId, topicId));
+ useProjectDirectoryStore((s) => s.useFetchDirectories)(undefined, !!directoryId);
+ const directories = useProjectDirectories();
+
+ return directoryId ? directories.find((d) => d.id === directoryId) : undefined;
+};
diff --git a/src/features/ChatInput/ControlBar/DeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/DeviceSwitcher.tsx
index 6219c6b95da..68f23d1fd5e 100644
--- a/src/features/ChatInput/ControlBar/DeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/DeviceSwitcher.tsx
@@ -1,28 +1,100 @@
'use client';
+import { confirmModal, toast } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+
import HeteroDeviceSwitcher from './HeteroDeviceSwitcher';
import ProjectDeviceSwitcher from './ProjectDeviceSwitcher';
-import { useActiveProjectDirectoryTopicId } from './useProjectTopicDirectory';
+import { type ProjectDeviceTarget } from './projectDeviceTargets';
+import {
+ useActiveProjectDirectoryTopicId,
+ useProjectTopicDirectory,
+ useStagedProjectDirectory,
+ useStagedProjectDirectoryId,
+} from './useProjectTopicDirectory';
interface DeviceSwitcherProps {
agentId: string;
}
+/** A project-directory topic moves to another device's directory once confirmed. */
+const ProjectTopicDeviceSwitcher = ({ agentId, topicId }: { agentId: string; topicId: string }) => {
+ const { t } = useTranslation('chat');
+ const { directories, directoryId } = useProjectTopicDirectory(topicId);
+ const moveTopic = useProjectDirectoryStore((s) => s.moveTopic);
+ const refreshTopic = useChatStore((s) => s.refreshTopic);
+
+ const handleSelect = ({ directory, label }: ProjectDeviceTarget) => {
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('heteroAgent.executionTarget.switchProjectTopic.content', {
+ device: label,
+ directory: directory.name,
+ }),
+ okText: t('heteroAgent.executionTarget.switchTopic.ok'),
+ onOk: async () => {
+ try {
+ await moveTopic({ directoryId: directory.id, topicId });
+ await refreshTopic();
+ } catch (error) {
+ toast.error((error as Error).message);
+ }
+ },
+ title: t('heteroAgent.executionTarget.switchTopic.title'),
+ });
+ };
+
+ return (
+ <ProjectDeviceSwitcher
+ activeTag={t('heteroAgent.executionTarget.topicTag')}
+ agentId={agentId}
+ directories={directories}
+ directoryId={directoryId}
+ onSelect={handleSelect}
+ />
+ );
+};
+
+/**
+ * A blank conversation staged in a project directory has nothing persisted
+ * yet, so switching devices just restages it in that device's directory.
+ */
+const StagedProjectDeviceSwitcher = ({ agentId }: { agentId: string }) => {
+ const { directories, directoryId } = useStagedProjectDirectory(agentId);
+
+ return (
+ <ProjectDeviceSwitcher
+ agentId={agentId}
+ directories={directories}
+ directoryId={directoryId}
+ onSelect={({ directory }) =>
+ useChatStore
+ .getState()
+ .setPendingNewTopicDirectory({ agentId, projectWorkingDirectoryId: directory.id })
+ }
+ />
+ );
+};
+
/**
* The execution-device control for whichever conversation is open. A
- * project-directory conversation runs in its project's directory, so it only
+ * project-directory conversation — or a blank one a project group's "+"
+ * staged in a directory — runs in its project's directory, so it only
* chooses among the project's devices; everything else gets the general
* execution-target picker. Every bar that shows a device control mounts this,
* so no surface can fall back to the general picker for a project topic.
*/
const DeviceSwitcher = ({ agentId }: DeviceSwitcherProps) => {
const projectTopicId = useActiveProjectDirectoryTopicId();
+ const stagedDirectoryId = useStagedProjectDirectoryId(agentId);
- return projectTopicId ? (
- <ProjectDeviceSwitcher agentId={agentId} topicId={projectTopicId} />
- ) : (
- <HeteroDeviceSwitcher agentId={agentId} />
- );
+ if (projectTopicId)
+ return <ProjectTopicDeviceSwitcher agentId={agentId} topicId={projectTopicId} />;
+ if (stagedDirectoryId) return <StagedProjectDeviceSwitcher agentId={agentId} />;
+ return <HeteroDeviceSwitcher agentId={agentId} />;
};
export default DeviceSwitcher;
diff --git a/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
index 35067bc2380..2ed77b9f0ae 100644
--- a/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
@@ -1,15 +1,6 @@
'use client';
-import {
- confirmModal,
- createStaticStyles,
- cssVar,
- Flexbox,
- Icon,
- Popover,
- toast,
- Tooltip,
-} from '@lobehub/ui';
+import { createStaticStyles, cssVar, Flexbox, Icon, Popover, Tooltip } from '@lobehub/ui';
import { ChevronDownIcon } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -19,12 +10,14 @@ import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
-import { useChatStore } from '@/store/chat';
-import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+import { type ProjectDirectory } from '@/store/projectWorkingDirectory';
import OptionRow from './OptionRow';
-import { listProjectDeviceTargets, projectDirectoryDeviceName } from './projectDeviceTargets';
-import { useProjectTopicDirectory } from './useProjectTopicDirectory';
+import {
+ listProjectDeviceTargets,
+ type ProjectDeviceTarget,
+ projectDirectoryDeviceName,
+} from './projectDeviceTargets';
import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';
const styles = createStaticStyles(({ css }) => ({
@@ -55,8 +48,13 @@ const styles = createStaticStyles(({ css }) => ({
}));
interface ProjectDeviceSwitcherProps {
+ /** Tag on the current directory's row, naming what runs there. */
+ activeTag?: string;
agentId: string;
- topicId: string;
+ directories: ProjectDirectory[];
+ directoryId?: string;
+ /** Picked another device's project directory. */
+ onSelect: (target: ProjectDeviceTarget) => void;
}
/**
@@ -69,14 +67,18 @@ interface ProjectDeviceSwitcherProps {
* directory itself has no chip of its own; its path rides on this trigger's
* tooltip.
*/
-const ProjectDeviceSwitcher = ({ agentId, topicId }: ProjectDeviceSwitcherProps) => {
+const ProjectDeviceSwitcher = ({
+ activeTag,
+ agentId,
+ directories,
+ directoryId,
+ onSelect,
+}: ProjectDeviceSwitcherProps) => {
const { t } = useTranslation('chat');
const [open, setOpen] = useState(false);
const { canUseResource } = useChatInputResourceAccess();
- const { directories, directory, directoryId } = useProjectTopicDirectory(topicId);
+ const directory = directories.find((d) => d.id === directoryId);
const { data: devices } = useDeviceList();
- const moveTopic = useProjectDirectoryStore((s) => s.moveTopic);
- const refreshTopic = useChatStore((s) => s.refreshTopic);
// The shared row, not the topic-pinned effective config: a fixed target is
// the author's setting, and it is what the server checks the move against.
const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
@@ -89,26 +91,9 @@ const ProjectDeviceSwitcher = ({ agentId, topicId }: ProjectDeviceSwitcherProps)
const targets = listProjectDeviceTargets(directories, devices, directoryId, fixedDeviceId);
- const handleSelect = ({ active, directory: target, label }: (typeof targets)[number]) => {
+ const handleSelect = (target: ProjectDeviceTarget) => {
setOpen(false);
- if (active) return;
- confirmModal({
- cancelText: t('cancel', { ns: 'common' }),
- content: t('heteroAgent.executionTarget.switchProjectTopic.content', {
- device: label,
- directory: target.name,
- }),
- okText: t('heteroAgent.executionTarget.switchTopic.ok'),
- onOk: async () => {
- try {
- await moveTopic({ directoryId: target.id, topicId });
- await refreshTopic();
- } catch (error) {
- toast.error((error as Error).message);
- }
- },
- title: t('heteroAgent.executionTarget.switchTopic.title'),
- });
+ if (!target.active) onSelect(target);
};
const content = (
@@ -122,7 +107,7 @@ const ProjectDeviceSwitcher = ({ agentId, topicId }: ProjectDeviceSwitcherProps)
disabled={!selectable}
key={target.directory.id}
label={target.label}
- tags={target.active ? [t('heteroAgent.executionTarget.topicTag')] : []}
+ tags={target.active && activeTag ? [activeTag] : []}
desc={
target.allowed ? (
<>
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
index 32b80496c60..d76bfd5b99f 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
@@ -17,7 +17,10 @@ import { useElectronStore } from '@/store/electron';
import { useTopicId } from '../hooks/useTopicId';
import GitStatus from './GitStatus';
-import { useActiveProjectDirectoryTopicId } from './useProjectTopicDirectory';
+import {
+ useActiveProjectDirectoryTopicId,
+ useStagedProjectDirectoryId,
+} from './useProjectTopicDirectory';
import { useRepoType } from './useRepoType';
import WorkingDirectoryPicker from './WorkingDirectoryPicker';
@@ -118,11 +121,18 @@ const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agent
WorkingDirectorySectionInner.displayName = 'WorkingDirectorySectionInner';
-const WorkingDirectorySection = memo<WorkingDirectorySectionProps>(({ agentId }) => (
- <SafeBoundary minHeight={22} resetKeys={[agentId]}>
- <WorkingDirectorySectionInner agentId={agentId} />
- </SafeBoundary>
-));
+const WorkingDirectorySection = memo<WorkingDirectorySectionProps>(({ agentId }) => {
+ // A blank conversation staged in a project directory runs there, not in the
+ // agent default this section resolves; the device switcher names it.
+ const stagedDirectoryId = useStagedProjectDirectoryId(agentId);
+ if (stagedDirectoryId) return null;
+
+ return (
+ <SafeBoundary minHeight={22} resetKeys={[agentId]}>
+ <WorkingDirectorySectionInner agentId={agentId} />
+ </SafeBoundary>
+ );
+});
WorkingDirectorySection.displayName = 'WorkingDirectorySection';
diff --git a/src/features/ChatInput/ControlBar/__tests__/DeviceSwitcher.test.tsx b/src/features/ChatInput/ControlBar/__tests__/DeviceSwitcher.test.tsx
new file mode 100644
index 00000000000..c9bbbda11ea
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/__tests__/DeviceSwitcher.test.tsx
@@ -0,0 +1,129 @@
+import { render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import DeviceSwitcher from '../DeviceSwitcher';
+
+const state = vi.hoisted(() => ({
+ activeTopicId: undefined as string | undefined,
+ pendingNewTopicDirectory: undefined as
+ { agentId: string; projectWorkingDirectoryId: string } | undefined,
+ setPendingNewTopicDirectory: vi.fn(),
+ topics: {} as Record<string, { projectId?: string; projectWorkingDirectoryId?: string }>,
+}));
+
+const directoryState = vi.hoisted(() => ({
+ all: [] as { deviceId: string; id: string; projectId: string }[],
+ directoriesMap: {} as Record<string, { deviceId: string; id: string; projectId: string }[]>,
+}));
+
+const directories = vi.hoisted(() => [
+ { deviceId: 'device-a', id: 'dir-a', projectId: 'project-1' },
+ { deviceId: 'device-b', id: 'dir-b', projectId: 'project-1' },
+]);
+
+const pickerProps = vi.hoisted(() => ({ current: undefined as any }));
+
+vi.mock('../../store', () => ({
+ useChatInputStore: (selector: (s: object) => unknown) => selector({ topicId: undefined }),
+}));
+
+vi.mock('@/store/chat', () => {
+ const useChatStore = (selector: (s: unknown) => unknown) => selector(state);
+ useChatStore.getState = () => state;
+ return { useChatStore };
+});
+
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: {
+ getTopicById: (id: string) => (s: typeof state) => s.topics[id],
+ },
+}));
+
+vi.mock('@/store/projectWorkingDirectory', () => ({
+ useProjectDirectories: (projectId?: string) =>
+ projectId ? (directoryState.directoriesMap[projectId] ?? []) : directoryState.all,
+ useProjectDirectoryStore: (selector: (s: object) => unknown) =>
+ selector({
+ directoriesMap: directoryState.directoriesMap,
+ moveTopic: vi.fn(),
+ useFetchDirectories: () => undefined,
+ }),
+}));
+
+vi.mock('../HeteroDeviceSwitcher', () => ({
+ default: () => <div>general-picker</div>,
+}));
+
+vi.mock('../ProjectDeviceSwitcher', () => ({
+ default: (props: any) => {
+ pickerProps.current = props;
+ return <div>project-picker:{props.directoryId}</div>;
+ },
+}));
+
+describe('DeviceSwitcher', () => {
+ beforeEach(() => {
+ state.activeTopicId = undefined;
+ state.pendingNewTopicDirectory = undefined;
+ state.setPendingNewTopicDirectory.mockClear();
+ state.topics = {};
+ pickerProps.current = undefined;
+ directoryState.all = directories;
+ directoryState.directoriesMap = { 'project-1': directories };
+ });
+
+ // A device subgroup's "+" stages a blank conversation in that device's
+ // directory; the composer must show that device, not the agent default.
+ it('shows the staged project directory for a blank conversation', () => {
+ state.pendingNewTopicDirectory = { agentId: 'agent-1', projectWorkingDirectoryId: 'dir-b' };
+
+ render(<DeviceSwitcher agentId="agent-1" />);
+
+ expect(screen.getByText('project-picker:dir-b')).toBeInTheDocument();
+ expect(pickerProps.current.directories).toEqual(directories);
+ });
+
+ // The project-keyed entry is still loading (or failed) on a first visit; the
+ // warm scope-wide rows already know the project's devices.
+ it("falls back to the scope-wide rows until the project's own entry loads", () => {
+ const otherProject = { deviceId: 'device-c', id: 'dir-c', projectId: 'project-2' };
+ directoryState.all = [...directories, otherProject];
+ directoryState.directoriesMap = {};
+ state.pendingNewTopicDirectory = { agentId: 'agent-1', projectWorkingDirectoryId: 'dir-b' };
+
+ render(<DeviceSwitcher agentId="agent-1" />);
+
+ expect(screen.getByText('project-picker:dir-b')).toBeInTheDocument();
+ expect(pickerProps.current.directories).toEqual(directories);
+ });
+
+ it('restages the blank conversation when another device is picked', () => {
+ state.pendingNewTopicDirectory = { agentId: 'agent-1', projectWorkingDirectoryId: 'dir-b' };
+
+ render(<DeviceSwitcher agentId="agent-1" />);
+ pickerProps.current.onSelect({ directory: directories[0], label: 'Device A' });
+
+ expect(state.setPendingNewTopicDirectory).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ projectWorkingDirectoryId: 'dir-a',
+ });
+ });
+
+ it("ignores a staging made on another agent's conversation", () => {
+ state.pendingNewTopicDirectory = { agentId: 'agent-2', projectWorkingDirectoryId: 'dir-b' };
+
+ render(<DeviceSwitcher agentId="agent-1" />);
+
+ expect(screen.getByText('general-picker')).toBeInTheDocument();
+ });
+
+ it('leaves an open plain topic on the general picker', () => {
+ state.activeTopicId = 'topic-1';
+ state.topics = { 'topic-1': {} };
+ state.pendingNewTopicDirectory = { agentId: 'agent-1', projectWorkingDirectoryId: 'dir-b' };
+
+ render(<DeviceSwitcher agentId="agent-1" />);
+
+ expect(screen.getByText('general-picker')).toBeInTheDocument();
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/useProjectTopicDirectory.ts b/src/features/ChatInput/ControlBar/useProjectTopicDirectory.ts
index 707fa646818..d97f13caced 100644
--- a/src/features/ChatInput/ControlBar/useProjectTopicDirectory.ts
+++ b/src/features/ChatInput/ControlBar/useProjectTopicDirectory.ts
@@ -1,4 +1,6 @@
-import { useChatStore } from '@/store/chat';
+import { useMemo } from 'react';
+
+import { type ChatStoreState, useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import {
type ProjectDirectory,
@@ -26,6 +28,58 @@ export const useActiveProjectDirectoryTopicId = (): string | undefined => {
);
};
+/**
+ * The staged directory of the blank conversation `agentId` / `topicId`
+ * describes — see `useStagedProjectDirectoryId`. Shared with the welcome
+ * screen, which reads its ids from the conversation rather than the composer.
+ */
+export const stagedProjectDirectoryIdSelector =
+ (agentId: string | undefined, topicId: string | null | undefined) =>
+ (s: ChatStoreState): string | undefined => {
+ const pending = s.pendingNewTopicDirectory;
+ return agentId && !topicId && pending?.agentId === agentId
+ ? pending.projectWorkingDirectoryId
+ : undefined;
+ };
+
+/**
+ * The project directory a blank conversation was opened in by a project
+ * group's "+" (`pendingNewTopicDirectory`). Its first send binds the new topic
+ * there, so until then the composer has to show that directory rather than
+ * the agent's default device and path. Undefined once the composer belongs to
+ * a topic, or when the staging was made on another agent.
+ */
+export const useStagedProjectDirectoryId = (agentId: string): string | undefined => {
+ const topicId = useTopicId();
+
+ return useChatStore(stagedProjectDirectoryIdSelector(agentId, topicId));
+};
+
+/**
+ * The staged directory of a blank conversation (see
+ * `useStagedProjectDirectoryId`) and the project's other directories it may
+ * move to before the first send.
+ */
+export const useStagedProjectDirectory = (agentId: string) => {
+ const directoryId = useStagedProjectDirectoryId(agentId);
+ useProjectDirectoryStore((s) => s.useFetchDirectories)(undefined, !!directoryId);
+ const scopeRows = useProjectDirectories();
+ const projectId = scopeRows.find((d) => d.id === directoryId)?.projectId;
+ useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId, !!projectId);
+ const projectRows = useProjectDirectoryStore((s) =>
+ projectId ? s.directoriesMap[projectId] : undefined,
+ );
+ // The project's own entry is the authority once loaded. Until then — or if
+ // its fetch fails — the warm scope-wide rows already list the project's
+ // directories, so the switcher never waits on an empty picker.
+ const directories = useMemo(() => {
+ if (!projectId) return EMPTY;
+ return projectRows ?? scopeRows.filter((d) => d.projectId === projectId);
+ }, [projectId, projectRows, scopeRows]);
+
+ return { directories, directoryId };
+};
+
/**
* The project directory a conversation runs in, and the project's other
* directories it may move to. Empty for conversations outside a project