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.

✨ feat(topic): group an agent's topics by device, then by directory (#23172)

Bryan71ab2b484e22
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index 1a17c65a85e..a3dbaab01d8 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -94,6 +94,7 @@
"forkTitle": "{{title}} (Branch)",
"groupTitle.byAgent.unknown": "Unknown agent",
"groupTitle.byDevice.unknown": "Unknown device",
+ "groupTitle.byDevice.unknownDirectory": "Unknown directory",
"groupTitle.byProject.noProject": "No directory",
"groupTitle.byStatus.active": "Active",
"groupTitle.byStatus.archived": "Archived",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index d238315bec3..36e22949aa6 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -94,6 +94,7 @@
"forkTitle": "{{title}} 的分支",
"groupTitle.byAgent.unknown": "未知 Agent",
"groupTitle.byDevice.unknown": "未知设备",
+ "groupTitle.byDevice.unknownDirectory": "未知目录",
"groupTitle.byProject.noProject": "无目录",
"groupTitle.byStatus.active": "活跃",
"groupTitle.byStatus.archived": "已归档",
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index 8268b23716a..ae972a8e1de 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -130,6 +130,7 @@ export default {
'filter.sortBy.updatedAt': 'Updated time',
'groupTitle.byAgent.unknown': 'Unknown agent',
'groupTitle.byDevice.unknown': 'Unknown device',
+ 'groupTitle.byDevice.unknownDirectory': 'Unknown directory',
'groupTitle.byProject.noProject': 'No directory',
'groupTitle.byStatus.active': 'Active',
'groupTitle.byStatus.archived': 'Archived',
diff --git a/src/features/AgentSidebar/Topic/ToggleGroups.tsx b/src/features/AgentSidebar/Topic/ToggleGroups.tsx
index 1c9c6e45c49..25cf275a49b 100644
--- a/src/features/AgentSidebar/Topic/ToggleGroups.tsx
+++ b/src/features/AgentSidebar/Topic/ToggleGroups.tsx
@@ -1,48 +1,15 @@
import { ActionIcon } from '@lobehub/ui';
-import isEqual from 'fast-deep-equal';
import { Maximize2, Minimize2 } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useLocalMachineDeviceIds } from '@/hooks/useLocalMachineDeviceIds';
import { useTopicGroupCollapse } from '@/hooks/useTopicGroupCollapse';
-import { useChatStore } from '@/store/chat';
-import { topicSelectors } from '@/store/chat/selectors';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { useUserStore } from '@/store/user';
-import { preferenceSelectors } from '@/store/user/selectors';
-import { useAgentTopicGroupMode } from './hooks/useAgentTopicGroupMode';
-import { useScopedSidebarTopics } from './useScopedTopics';
+import { useSidebarTopicGroups } from './hooks/useSidebarTopicGroups';
const ToggleGroups = memo(() => {
const { t } = useTranslation('topic');
- const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
- const topicSortBy = useUserStore(preferenceSelectors.topicSortBy);
- const topicIncludeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);
- const { topicGroupMode } = useAgentTopicGroupMode();
-
- const localDeviceIds = useLocalMachineDeviceIds();
- const groupSelector = useMemo(
- () =>
- topicSelectors.groupedTopicsForSidebar(
- topicPageSize,
- topicSortBy,
- topicGroupMode,
- topicIncludeCompleted,
- localDeviceIds,
- ),
- [topicPageSize, topicSortBy, topicGroupMode, topicIncludeCompleted, localDeviceIds],
- );
- const agentGroups = useChatStore(groupSelector, isEqual);
- const scoped = useScopedSidebarTopics(
- topicPageSize,
- topicSortBy,
- topicGroupMode,
- topicIncludeCompleted,
- );
- const groupTopics = scoped.scope ? scoped.groups : agentGroups;
+ const { groups: groupTopics, topicGroupMode } = useSidebarTopicGroups();
const groupIds = useMemo(() => groupTopics.map((group) => group.id), [groupTopics]);
const { expandedKeys, setExpandedKeys } = useTopicGroupCollapse(topicGroupMode, groupIds);
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/DirectoryTopicList.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/DirectoryTopicList.tsx
new file mode 100644
index 00000000000..a18b67ed337
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/DirectoryTopicList.tsx
@@ -0,0 +1,103 @@
+import { AccordionRoot, cssVar, Flexbox, Icon } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { FolderClosedIcon, FolderXIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ProjectAvatar from '@/features/Projects/ProjectAvatar';
+import { canStageDraftOn } from '@/features/Projects/WorkingDirectories/startProjectTopicDraft';
+import { useAgentFixedDeviceId } from '@/features/Projects/WorkingDirectories/useAgentFixedDeviceId';
+import { useProjectDirectories } from '@/store/projectWorkingDirectory';
+import { type ChatTopic } from '@/types/topic';
+
+import TopicSubGroupItem, { renderSubGroupTopic, useSubGroupExpansion } from '../TopicSubGroupItem';
+import { useStartTopicInDirectory } from '../useStartTopicInDirectory';
+import {
+ directorySectionTag,
+ directorySectionTitle,
+ groupTopicsByDirectory,
+ NO_DIRECTORY_SECTION_ID,
+} from './directorySections';
+
+interface DirectoryTopicListProps {
+ topics: ChatTopic[];
+}
+
+/**
+ * The second level of an agent's by-device grouping: one device's topics,
+ * sectioned by the directory they work in.
+ */
+const DirectoryTopicList = memo<DirectoryTopicListProps>(({ topics }) => {
+ const { t } = useTranslation('topic');
+ const directories = useProjectDirectories();
+ const sections = useMemo(() => groupTopicsByDirectory(topics), [topics]);
+ const { expandedIds, onExpandedChange } = useSubGroupExpansion(sections);
+
+ // A project directory section starts a topic in place, where the agent can
+ // run there — an agent fixed to another device never could.
+ const { agentId, startInDirectory } = useStartTopicInDirectory();
+ const fixedDeviceId = useAgentFixedDeviceId(agentId);
+
+ if (!sections) {
+ return (
+ <Flexbox gap={1} paddingBlock={1}>
+ {topics.map((topic) => renderSubGroupTopic(topic))}
+ </Flexbox>
+ );
+ }
+
+ const labels = {
+ noDirectory: t('groupTitle.byProject.noProject'),
+ unknownDirectory: t('groupTitle.byDevice.unknownDirectory'),
+ };
+ const titles = sections.map((section) => directorySectionTitle(section, directories, labels));
+
+ return (
+ <AccordionRoot
+ indicatorPlacement="inline"
+ style={{ gap: 1, paddingBlock: 1 }}
+ value={expandedIds}
+ onValueChange={onExpandedChange}
+ >
+ {sections.map((section, index) => {
+ const directory = section.directoryId
+ ? directories.find((item) => item.id === section.directoryId)
+ : undefined;
+ const startable = !!agentId && !!directory && canStageDraftOn(directory, fixedDeviceId);
+ const duplicated = titles.filter((title) => title === titles[index]).length > 1;
+
+ return (
+ <TopicSubGroupItem
+ expanded={!!expandedIds?.includes(section.id)}
+ group={section}
+ key={section.id}
+ startDirectoryId={startable ? directory.id : undefined}
+ tag={duplicated ? directorySectionTag(section, directories) : undefined}
+ title={titles[index]}
+ icon={
+ directory ? (
+ <ProjectAvatar
+ avatar={directory.projectAvatar}
+ id={directory.projectId}
+ name={directory.projectName}
+ size={14}
+ />
+ ) : (
+ <Icon
+ color={cssVar.colorTextTertiary}
+ icon={section.id === NO_DIRECTORY_SECTION_ID ? FolderXIcon : FolderClosedIcon}
+ size={{ size: 12 }}
+ />
+ )
+ }
+ onStartInDirectory={startInDirectory}
+ />
+ );
+ })}
+ </AccordionRoot>
+ );
+}, isEqual);
+
+DirectoryTopicList.displayName = 'DeviceDirectoryTopicList';
+
+export default DirectoryTopicList;
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx
index a04bd56ed42..78158b149eb 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx
@@ -32,10 +32,12 @@ import { deviceSelectors } from '@/store/device/selectors';
import { useElectronStore } from '@/store/electron';
import { useProjectDirectories } from '@/store/projectWorkingDirectory';
-import TopicItem from '../../List/Item';
import { useTopicListScope } from '../../TopicListScope';
import { deviceCategoryKey } from '../ByProjectMode/deviceIdentity';
import { type GroupItemComponentProps } from '../GroupedAccordion';
+import { renderSubGroupTopic } from '../TopicSubGroupItem';
+import { sectionsDeviceGroupByDirectory } from './directorySections';
+import DirectoryTopicList from './DirectoryTopicList';
import {
findDeviceTopicDirectory,
hasNamesakeDevice,
@@ -102,6 +104,8 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
});
};
+ const sectionByDirectory = sectionsDeviceGroupByDirectory(id, !!scope);
+
return (
<AccordionItem value={id}>
<AccordionHeader>
@@ -154,21 +158,13 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
)}
</AccordionHeader>
<AccordionPanel contentStyle={{ padding: 0 }}>
- <Flexbox gap={1} paddingBlock={1}>
- {children.map((topic) => (
- <TopicItem
- fav={topic.favorite}
- hasGoal={topic.hasGoal}
- id={topic.id}
- key={topic.id}
- metadata={topic.metadata}
- runStartedAt={topic.runStartedAt}
- status={topic.status}
- title={topic.title}
- userId={topic.userId}
- />
- ))}
- </Flexbox>
+ {sectionByDirectory ? (
+ <DirectoryTopicList topics={children} />
+ ) : (
+ <Flexbox gap={1} paddingBlock={1}>
+ {children.map((topic) => renderSubGroupTopic(topic))}
+ </Flexbox>
+ )}
</AccordionPanel>
</AccordionItem>
);
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/directorySections.test.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/directorySections.test.ts
new file mode 100644
index 00000000000..eb4496d448d
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/directorySections.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it } from 'vitest';
+
+import { type ChatTopic } from '@/types/topic';
+
+import {
+ directorySectionTag,
+ directorySectionTitle,
+ groupTopicsByDirectory,
+ NO_DIRECTORY_SECTION_ID,
+ sectionsDeviceGroupByDirectory,
+} from './directorySections';
+
+const topic = (id: string, extra: Partial<ChatTopic> = {}) =>
+ ({ id, title: id, ...extra }) as ChatTopic;
+
+const labels = { noDirectory: 'No directory', unknownDirectory: 'Unknown directory' };
+
+describe('groupTopicsByDirectory', () => {
+ it('sections topics by project directory, then folder path, with directory-less topics last', () => {
+ const sections = groupTopicsByDirectory([
+ topic('loose'),
+ topic('a1', { projectWorkingDirectoryId: 'dir-a' }),
+ topic('p1', { metadata: { workingDirectory: '/tmp/scratch' } } as Partial<ChatTopic>),
+ topic('a2', { projectWorkingDirectoryId: 'dir-a' }),
+ ]);
+
+ expect(sections?.map((section) => [section.id, section.children.map((t) => t.id)])).toEqual([
+ ['directory:dir-a', ['a1', 'a2']],
+ ['path:/tmp/scratch', ['p1']],
+ [NO_DIRECTORY_SECTION_ID, ['loose']],
+ ]);
+ });
+});
+
+describe('groupTopicsByDirectory without directories', () => {
+ /** @example a device with only directory-less topics must not nest them under a lone "No directory". */
+ it('returns undefined so the device lists its topics flat', () => {
+ expect(groupTopicsByDirectory([topic('a'), topic('b')])).toBeUndefined();
+ });
+});
+
+describe('directorySectionTitle', () => {
+ const directories = [
+ { id: 'dir-a', name: 'lobehub', path: '/Users/me/lobehub', projectName: 'LobeHub' },
+ ];
+
+ it('names a project directory by its project and a bare folder by its last segment', () => {
+ const [project, folder] = groupTopicsByDirectory([
+ topic('a', { projectWorkingDirectoryId: 'dir-a' }),
+ topic('p', { metadata: { workingDirectory: '/tmp/scratch/' } } as Partial<ChatTopic>),
+ ])!;
+
+ expect(directorySectionTitle(project, directories, labels)).toBe('LobeHub');
+ expect(directorySectionTitle(folder, directories, labels)).toBe('scratch');
+ });
+
+ /** @example a directory the registry no longer lists must not render an empty title. */
+ it('falls back to the folder, then the unknown label, for an unlisted directory', () => {
+ const [withPath, withoutPath] = groupTopicsByDirectory([
+ topic('a', {
+ metadata: { workingDirectory: '/srv/app' },
+ projectWorkingDirectoryId: 'gone-1',
+ } as Partial<ChatTopic>),
+ topic('b', { projectWorkingDirectoryId: 'gone-2' }),
+ ])!;
+
+ expect(directorySectionTitle(withPath, directories, labels)).toBe('app');
+ expect(directorySectionTitle(withoutPath, directories, labels)).toBe('Unknown directory');
+ expect(directorySectionTag(withoutPath, directories)).toBeUndefined();
+ });
+
+ it('labels the directory-less section', () => {
+ const [, loose] = groupTopicsByDirectory([
+ topic('a', { projectWorkingDirectoryId: 'dir-a' }),
+ topic('loose'),
+ ])!;
+ expect(directorySectionTitle(loose, directories, labels)).toBe('No directory');
+ });
+});
+
+describe('sectionsDeviceGroupByDirectory', () => {
+ /** @example by device in an agent sidebar: the device leads, its directories nest below it. */
+ it.each(['device:device-1', 'no-device'])('nests %s by directory in an agent sidebar', (id) => {
+ expect(sectionsDeviceGroupByDirectory(id, false)).toBe(true);
+ });
+
+ it('keeps project-scoped device groups and synthetic buckets flat', () => {
+ expect(sectionsDeviceGroupByDirectory('device:device-1', true)).toBe(false);
+ expect(sectionsDeviceGroupByDirectory('favorite', false)).toBe(false);
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/directorySections.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/directorySections.ts
new file mode 100644
index 00000000000..666983b5de9
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/directorySections.ts
@@ -0,0 +1,105 @@
+import { type ChatTopic, type GroupedTopic } from '@/types/topic';
+import { getTopicWorkingDirectorySourcePath } from '@/utils/client/topic';
+
+export const NO_DIRECTORY_SECTION_ID = 'no-directory';
+const DEVICE_GROUP_PREFIX = 'device:';
+const NO_DEVICE_GROUP_ID = 'no-device';
+
+/**
+ * Whether a by-device group nests its topics by directory. An agent's topics
+ * on one device spread over its directories, so the device leads and its
+ * directories follow. A project-scoped list already is one project — its
+ * directory on a device needs no row of its own — and synthetic buckets
+ * (favorites) stay flat.
+ */
+export const sectionsDeviceGroupByDirectory = (groupId: string, projectScoped: boolean) =>
+ !projectScoped && (groupId.startsWith(DEVICE_GROUP_PREFIX) || groupId === NO_DEVICE_GROUP_ID);
+const DIRECTORY_SECTION_PREFIX = 'directory:';
+const PATH_SECTION_PREFIX = 'path:';
+
+export interface DirectorySection extends GroupedTopic {
+ /** The project directory the section stands for, when its topics are bound to one. */
+ directoryId?: string;
+ /** The folder the section's newest topic works in. */
+ path?: string;
+}
+
+interface DirectoryLike {
+ id: string;
+ name?: string | null;
+ path?: string | null;
+ projectName?: string | null;
+}
+
+const basename = (path: string) => path.split(/[/\\]+/).findLast(Boolean) ?? path;
+
+/**
+ * Section one device's topics by the directory they work in: a bound project
+ * directory first, else the topic's own folder path. Sections keep the
+ * incoming (sidebar-sorted) order, so the directory with the most recent topic
+ * leads; topics without any directory trail in their own section. Returns
+ * `undefined` when no topic has a directory, so the caller lists them flat.
+ */
+export const groupTopicsByDirectory = (topics: ChatTopic[]): DirectorySection[] | undefined => {
+ const sections = new Map<string, DirectorySection>();
+ const loose: ChatTopic[] = [];
+
+ for (const topic of topics) {
+ const path = getTopicWorkingDirectorySourcePath(topic);
+ const directoryId = topic.projectWorkingDirectoryId ?? undefined;
+ const id = directoryId
+ ? `${DIRECTORY_SECTION_PREFIX}${directoryId}`
+ : path
+ ? `${PATH_SECTION_PREFIX}${path}`
+ : undefined;
+ if (!id) {
+ loose.push(topic);
+ continue;
+ }
+ const existing = sections.get(id);
+ if (existing) {
+ existing.children.push(topic);
+ existing.path ??= path;
+ } else {
+ sections.set(id, { children: [topic], directoryId, id, path });
+ }
+ }
+
+ // Sections only tell directories apart: a device without any directory
+ // lists its topics directly instead of nesting them under "No directory".
+ if (sections.size === 0) return undefined;
+ const result = [...sections.values()];
+ if (loose.length) result.push({ children: loose, id: NO_DIRECTORY_SECTION_ID });
+ return result;
+};
+
+/**
+ * A project directory reads as its project; a bare folder as its last path
+ * segment. A directory the registry no longer lists falls back to its folder,
+ * and only without one to the unknown label — never an empty title.
+ */
+export const directorySectionTitle = (
+ section: DirectorySection,
+ directories: DirectoryLike[],
+ labels: { noDirectory: string; unknownDirectory: string },
+): string => {
+ if (section.id === NO_DIRECTORY_SECTION_ID) return labels.noDirectory;
+ const directory = section.directoryId
+ ? directories.find((item) => item.id === section.directoryId)
+ : undefined;
+ const path = directory?.path || section.path;
+ return (
+ directory?.projectName || directory?.name || (path && basename(path)) || labels.unknownDirectory
+ );
+};
+
+/** The full folder path, shown only to tell apart sections whose titles match. */
+export const directorySectionTag = (
+ section: DirectorySection,
+ directories: DirectoryLike[],
+): string | undefined => {
+ const directory = section.directoryId
+ ? directories.find((item) => item.id === section.directoryId)
+ : undefined;
+ return directory?.path || section.path || undefined;
+};
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
index 91d8abd0f2d..3f634e9a006 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
@@ -330,6 +330,32 @@ describe('Project topic group item', () => {
expect(document.body.textContent).not.toContain('groupTitle.byDevice.unknown');
});
+ /** @example a single directory lives on one device; device sections would nest the device under its own folder. */
+ it('offers no device grouping for a single project-directory group', async () => {
+ render(
+ <AccordionRoot defaultValue={['project-directory:dir-1']}>
+ <GroupItem
+ expanded
+ group={{
+ children: [
+ {
+ id: 't1',
+ metadata: { boundDeviceId: 'device-2' },
+ projectWorkingDirectoryId: 'dir-1',
+ title: 'Directory topic',
+ },
+ ] as any,
+ id: 'project-directory:dir-1',
+ }}
+ />
+ </AccordionRoot>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'topics.subGroup.title' }));
+ expect(await screen.findByText('topics.subGroup.byTime')).toBeTruthy();
+ expect(screen.queryByText('topics.subGroup.byDevice')).toBeNull();
+ });
+
it("sections a folder by device once it merges this machine's two device identities", () => {
subGroupModeMock.value = 'byDevice';
const folder = (id: string, boundDeviceId: string) => ({
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
index ed8306b1e7d..3701fc1479d 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
@@ -62,6 +62,7 @@ import { buildPrefixedAgentRoutePath, parseAgentPathname } from '../../../utils/
import { useTopicListScope } from '../../TopicListScope';
import { getMergedPullRequestTopics } from '../../utils/mergedPullRequestTopics';
import { type GroupItemComponentProps } from '../GroupedAccordion';
+import { useStartTopicInDirectory } from '../useStartTopicInDirectory';
import { indicatorStyles, useCollapsedIndicators } from './CollapsedIndicators';
import { deviceCategoryKey, deviceDisplayName } from './deviceIdentity';
import ProjectTopicList from './ProjectTopicList';
@@ -69,8 +70,11 @@ import ProjectTopicList from './ProjectTopicList';
const PROJECT_GROUP_PREFIX = 'project:';
const PROJECT_ID_GROUP_PREFIX = 'project-id:';
const SUB_GROUP_MODES: ProjectTopicSubGroupMode[] = ['none', 'byDevice', 'byTime', 'byStatus'];
-// A plain folder usually lives on one device, so sectioning it by device says
-// nothing — unless it merges one machine's personal and workspace identities.
+// One directory lives on one device, so sectioning it by device would only
+// nest the device under its own folder — devices lead in the sidebar's own
+// "by device" grouping instead. A project spans directories on several
+// machines, and a folder can merge one machine's personal and workspace
+// identities; only those section by device.
const FOLDER_SUB_GROUP_MODES = SUB_GROUP_MODES.filter((mode) => mode !== 'byDevice');
const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
@@ -192,21 +196,8 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
activeWorkspaceSlug,
]);
- // Start on one specific project directory — the device sub-group "+". The
- // directory pins the device, so nothing is committed to the agent default.
- const handleStartInDirectory = useCallback(
- (projectWorkingDirectoryId: string) => {
- if (!targetAgentId) return;
- useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });
- useChatStore
- .getState()
- .setPendingNewTopicDirectory({ agentId: targetAgentId, projectWorkingDirectoryId });
- router.push(
- buildPrefixedAgentRoutePath(AGENT_CHAT_URL(targetAgentId), agentRoute, activeWorkspaceSlug),
- );
- },
- [targetAgentId, router, agentRoute, activeWorkspaceSlug],
- );
+ // Start on one specific project directory — the device sub-group "+".
+ const { startInDirectory: handleStartInDirectory } = useStartTopicInDirectory();
const canAddTopic = !scope && !!currentAgentId && !!workingDirectory;
const needsPlainStart = !!projectId && projectDirectories.length > 1;
@@ -215,7 +206,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
const isProjectGroup = !!projectId || !!children[0]?.projectWorkingDirectoryId;
const spansDevices =
new Set(children.map((topic) => topic.metadata?.boundDeviceId).filter(Boolean)).size > 1;
- const subGroupModes = isProjectGroup || spansDevices ? SUB_GROUP_MODES : FOLDER_SUB_GROUP_MODES;
+ const subGroupModes = projectId || spansDevices ? SUB_GROUP_MODES : FOLDER_SUB_GROUP_MODES;
// The same folder on another machine is its own group with the same name:
// name the device, and its category for one machine's several identities.
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx
index c01172452e0..bae967785ae 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx
@@ -1,22 +1,7 @@
-import {
- AccordionHeader,
- AccordionItem,
- AccordionPanel,
- AccordionRoot,
- accordionStyles,
- AccordionTrigger,
- ActionIcon,
- Center,
- cssVar,
- cx,
- Flexbox,
- Icon,
- Tag,
- Text,
-} from '@lobehub/ui';
+import { AccordionRoot, cssVar, Flexbox, Icon } from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
-import { LaptopIcon, PlusIcon } from 'lucide-react';
-import { memo, useCallback, useMemo, useState } from 'react';
+import { LaptopIcon } from 'lucide-react';
+import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -24,9 +9,7 @@ import {
TOPIC_GROUP_VISUALS,
TOPIC_STATUS_VISUALS,
} from '@/components/ExecutionStatus';
-import TailMarquee from '@/components/TailMarquee';
import { projectDirectoryDeviceName } from '@/features/ChatInput/ControlBar/projectDeviceTargets';
-import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -39,9 +22,8 @@ import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
import { type ChatTopic, type GroupedTopic } from '@/types/topic';
-import TopicItem from '../../List/Item';
import { formatTimeGroupId } from '../ByTimeMode/timeGroupTitle';
-import { indicatorStyles, useCollapsedIndicators } from './CollapsedIndicators';
+import TopicSubGroupItem, { renderSubGroupTopic, useSubGroupExpansion } from '../TopicSubGroupItem';
import { deviceCategoryKey, deviceDisplayName } from './deviceIdentity';
import {
DEVICE_SUB_GROUP_PREFIX,
@@ -73,129 +55,6 @@ interface AgentPinnedRow {
agentId?: string | null;
}
-const renderTopic = (topic: ChatTopic, suppressAgentAvatar?: boolean) => (
- <TopicItem
- fav={topic.favorite}
- hasGoal={topic.hasGoal}
- id={topic.id}
- key={topic.id}
- metadata={topic.metadata}
- runStartedAt={topic.runStartedAt}
- status={topic.status}
- suppressAgentAvatar={suppressAgentAvatar}
- title={topic.title}
- userId={topic.userId}
- />
-);
-
-interface SubGroupItemProps {
- expanded: boolean;
- group: GroupedTopic;
- icon?: Pick<ExecutionStatusVisual, 'color' | 'icon'>;
- onStartInDirectory?: (projectWorkingDirectoryId: string) => void;
- startDirectoryId?: string;
- suppressAgentAvatar?: boolean;
- /** Tells apart sections whose titles match, e.g. one machine's two device identities. */
- tag?: string;
- title: string;
-}
-
-const SubGroupItem = memo<SubGroupItemProps>(
- ({
- expanded,
- group,
- icon,
- onStartInDirectory,
- startDirectoryId,
- suppressAgentAvatar,
- tag,
- title,
- }) => {
- const { t } = useTranslation('topic');
- const { t: tProject } = useTranslation('project');
- // A folded section keeps the project row's running / awaiting / failed
- // counts and unread dot, so a device section still says how much it does.
- const { hasIndicators, indicators } = useCollapsedIndicators(group.children, expanded);
-
- return (
- <AccordionItem value={group.id}>
- <AccordionHeader className={'accordion-header'}>
- {/* Same icon column and gap as the project row, so the section
- title lines up with the project name and the topics below. */}
- <AccordionTrigger style={{ paddingBlock: 2, paddingInline: 4 }}>
- <Flexbox horizontal align="center" gap={8} height={24} style={{ overflow: 'hidden' }}>
- <Center flex={'none'} height={24} width={28}>
- {icon && <Icon color={icon.color} icon={icon.icon} size={{ size: 12 }} />}
- </Center>
- <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
- {title}
- </Text>
- {tag && (
- <Tag
- size={'small'}
- style={{
- color: cssVar.colorTextDescription,
- flex: '0 1 auto',
- fontSize: 10,
- maxWidth: '50%',
- minWidth: 0,
- overflow: 'hidden',
- }}
- >
- <TailMarquee>{tag}</TailMarquee>
- </Tag>
- )}
- </Flexbox>
- </AccordionTrigger>
- {(startDirectoryId || hasIndicators) && (
- <div
- className={cx(
- 'accordion-action',
- accordionStyles.action,
- accordionStyles.actionBorderless,
- hasIndicators && accordionStyles.actionAlwaysVisible,
- )}
- >
- <Flexbox horizontal align={'center'} gap={4}>
- {indicators}
- {startDirectoryId && (
- <span className={indicatorStyles.hoverActions}>
- <ActionIcon
- icon={PlusIcon}
- size={'small'}
- title={tProject('directories.start')}
- onClick={(e) => {
- e.stopPropagation();
- onStartInDirectory?.(startDirectoryId);
- }}
- />
- </span>
- )}
- </Flexbox>
- </div>
- )}
- </AccordionHeader>
- <AccordionPanel contentStyle={{ padding: 0 }}>
- <Flexbox gap={1} paddingBlock={1}>
- {group.children.length === 0 && startDirectoryId ? (
- // A device listed before any topic ran on it starts one in place.
- <EmptyNavItem
- title={t('actions.addNewTopic')}
- onClick={() => onStartInDirectory?.(startDirectoryId)}
- />
- ) : (
- group.children.map((topic) => renderTopic(topic, suppressAgentAvatar))
- )}
- </Flexbox>
- </AccordionPanel>
- </AccordionItem>
- );
- },
- isEqual,
-);
-
-SubGroupItem.displayName = 'ProjectTopicSubGroupItem';
-
interface ProjectTopicListProps {
/** The group's effective sub-group mode (a folder gets `byDevice` only across machines). */
mode: ProjectTopicSubGroupMode;
@@ -332,25 +191,12 @@ const ProjectTopicList = memo<ProjectTopicListProps>((props) => {
return used ?? candidates[0]?.id;
};
- // Sections start expanded; only the ones the user folds are remembered.
- const [collapsedIds, setCollapsedIds] = useState<string[]>([]);
- const expandedIds = useMemo(
- () => groups?.filter((group) => !collapsedIds.includes(group.id)).map((group) => group.id),
- [groups, collapsedIds],
- );
- const handleExpandedChange = useCallback(
- (next: unknown[]) =>
- setCollapsedIds((prev) => [
- ...prev.filter((id) => !groups?.some((group) => group.id === id)),
- ...(groups ?? []).filter((group) => !next.includes(group.id)).map((group) => group.id),
- ]),
- [groups],
- );
+ const { expandedIds, onExpandedChange } = useSubGroupExpansion(groups);
if (!groups) {
return (
<Flexbox gap={1} paddingBlock={1}>
- {topics.map((topic) => renderTopic(topic, suppressAgentAvatar))}
+ {topics.map((topic) => renderSubGroupTopic(topic, suppressAgentAvatar))}
</Flexbox>
);
}
@@ -362,10 +208,10 @@ const ProjectTopicList = memo<ProjectTopicListProps>((props) => {
indicatorPlacement="inline"
style={{ gap: 1, paddingBlock: 1 }}
value={expandedIds}
- onValueChange={handleExpandedChange}
+ onValueChange={onExpandedChange}
>
{groups.map((group, index) => (
- <SubGroupItem
+ <TopicSubGroupItem
expanded={!!expandedIds?.includes(group.id)}
group={group}
key={group.id}
@@ -374,11 +220,17 @@ const ProjectTopicList = memo<ProjectTopicListProps>((props) => {
tag={getTag(group, titles[index], titles)}
title={titles[index]}
icon={
- mode === 'byStatus'
- ? STATUS_ICON[group.id]
- : mode === 'byDevice'
- ? { color: cssVar.colorTextTertiary, icon: LaptopIcon }
- : undefined
+ mode === 'byStatus' ? (
+ STATUS_ICON[group.id] && (
+ <Icon
+ color={STATUS_ICON[group.id].color}
+ icon={STATUS_ICON[group.id].icon}
+ size={{ size: 12 }}
+ />
+ )
+ ) : mode === 'byDevice' ? (
+ <Icon color={cssVar.colorTextTertiary} icon={LaptopIcon} size={{ size: 12 }} />
+ ) : undefined
}
onStartInDirectory={onStartInDirectory}
/>
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx b/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx
index 327c6959e2f..aae9e39b6f5 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx
@@ -1,27 +1,20 @@
'use client';
import { AccordionRoot, Flexbox } from '@lobehub/ui';
-import isEqual from 'fast-deep-equal';
import { MoreHorizontal } from 'lucide-react';
import { type ComponentType, memo, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
-import { useLocalMachineDeviceIds } from '@/hooks/useLocalMachineDeviceIds';
import { useTopicGroupCollapse } from '@/hooks/useTopicGroupCollapse';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { useUserStore } from '@/store/user';
-import { preferenceSelectors } from '@/store/user/selectors';
import { type GroupedTopic } from '@/types/topic';
-import { useAgentTopicGroupMode } from '../hooks/useAgentTopicGroupMode';
import { useScrollActiveTopicIntoView } from '../hooks/useScrollActiveTopicIntoView';
+import { useSidebarTopicGroups } from '../hooks/useSidebarTopicGroups';
import { useNavigateToAgentTopics } from '../hooks/useTopicNavigation';
-import { useScopedSidebarTopics } from '../useScopedTopics';
export interface GroupItemComponentProps {
expanded: boolean;
@@ -35,10 +28,7 @@ interface GroupedAccordionProps {
const GroupedAccordion = memo<GroupedAccordionProps>(({ GroupItem }) => {
const { t } = useTranslation('chat');
const navigateToAgentTopics = useNavigateToAgentTopics();
- const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
- const topicSortBy = useUserStore(preferenceSelectors.topicSortBy);
- const topicIncludeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);
- const { topicGroupMode } = useAgentTopicGroupMode();
+ const { groups: groupTopics, scoped, topicGroupMode } = useSidebarTopicGroups();
const [hasMore, isExpandingPageSize, activeAgentId, agentActiveTopicId] = useChatStore((s) => [
topicSelectors.hasMoreTopicsForSidebar(s),
@@ -47,27 +37,6 @@ const GroupedAccordion = memo<GroupedAccordionProps>(({ GroupItem }) => {
s.activeTopicId,
]);
- const localDeviceIds = useLocalMachineDeviceIds();
- const groupSelector = useMemo(
- () =>
- topicSelectors.groupedTopicsForSidebar(
- topicPageSize,
- topicSortBy,
- topicGroupMode,
- topicIncludeCompleted,
- localDeviceIds,
- ),
- [topicPageSize, topicSortBy, topicGroupMode, topicIncludeCompleted, localDeviceIds],
- );
- const agentGroups = useChatStore(groupSelector, isEqual);
- const scoped = useScopedSidebarTopics(
- topicPageSize,
- topicSortBy,
- topicGroupMode,
- topicIncludeCompleted,
- );
- const groupTopics = scoped.scope ? scoped.groups : agentGroups;
-
const activeTopicId = scoped.scope ? scoped.activeTopicId : agentActiveTopicId;
const groupIds = useMemo(() => groupTopics.map((group) => group.id), [groupTopics]);
const { expandedKeys, setExpandedKeys } = useTopicGroupCollapse(topicGroupMode, groupIds);
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/TopicSubGroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/TopicSubGroupItem.tsx
new file mode 100644
index 00000000000..adcfb0efc0c
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/TopicSubGroupItem.tsx
@@ -0,0 +1,174 @@
+import {
+ AccordionHeader,
+ AccordionItem,
+ AccordionPanel,
+ accordionStyles,
+ AccordionTrigger,
+ ActionIcon,
+ Center,
+ cssVar,
+ cx,
+ Flexbox,
+ Tag,
+ Text,
+} from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { PlusIcon } from 'lucide-react';
+import { memo, type ReactNode, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import TailMarquee from '@/components/TailMarquee';
+import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';
+import { type ChatTopic, type GroupedTopic } from '@/types/topic';
+
+import TopicItem from '../List/Item';
+import { indicatorStyles, useCollapsedIndicators } from './ByProjectMode/CollapsedIndicators';
+
+export const renderSubGroupTopic = (topic: ChatTopic, suppressAgentAvatar?: boolean) => (
+ <TopicItem
+ fav={topic.favorite}
+ hasGoal={topic.hasGoal}
+ id={topic.id}
+ key={topic.id}
+ metadata={topic.metadata}
+ runStartedAt={topic.runStartedAt}
+ status={topic.status}
+ suppressAgentAvatar={suppressAgentAvatar}
+ title={topic.title}
+ userId={topic.userId}
+ />
+);
+
+interface TopicSubGroupItemProps {
+ expanded: boolean;
+ group: GroupedTopic;
+ /** Sits in the parent row's icon column, so the section title lines up with it. */
+ icon?: ReactNode;
+ onStartInDirectory?: (projectWorkingDirectoryId: string) => void;
+ startDirectoryId?: string;
+ suppressAgentAvatar?: boolean;
+ /** Tells apart sections whose titles match, e.g. one machine's two device identities. */
+ tag?: string;
+ title: string;
+}
+
+/**
+ * The second level of a sidebar topic group: a foldable section with its own
+ * collapsed indicators and an optional "+" that starts a topic in one project
+ * directory.
+ */
+const TopicSubGroupItem = memo<TopicSubGroupItemProps>(
+ ({
+ expanded,
+ group,
+ icon,
+ onStartInDirectory,
+ startDirectoryId,
+ suppressAgentAvatar,
+ tag,
+ title,
+ }) => {
+ const { t } = useTranslation('topic');
+ const { t: tProject } = useTranslation('project');
+ // A folded section keeps the parent row's running / awaiting / failed
+ // counts and unread dot, so it still says how much it does.
+ const { hasIndicators, indicators } = useCollapsedIndicators(group.children, expanded);
+
+ return (
+ <AccordionItem value={group.id}>
+ <AccordionHeader className={'accordion-header'}>
+ {/* Same icon column and gap as the parent row, so the section
+ title lines up with the parent name and the topics below. */}
+ <AccordionTrigger style={{ paddingBlock: 2, paddingInline: 4 }}>
+ <Flexbox horizontal align="center" gap={8} height={24} style={{ overflow: 'hidden' }}>
+ <Center flex={'none'} height={24} width={28}>
+ {icon}
+ </Center>
+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
+ {title}
+ </Text>
+ {tag && (
+ <Tag
+ size={'small'}
+ style={{
+ color: cssVar.colorTextDescription,
+ flex: '0 1 auto',
+ fontSize: 10,
+ maxWidth: '50%',
+ minWidth: 0,
+ overflow: 'hidden',
+ }}
+ >
+ <TailMarquee>{tag}</TailMarquee>
+ </Tag>
+ )}
+ </Flexbox>
+ </AccordionTrigger>
+ {(startDirectoryId || hasIndicators) && (
+ <div
+ className={cx(
+ 'accordion-action',
+ accordionStyles.action,
+ accordionStyles.actionBorderless,
+ hasIndicators && accordionStyles.actionAlwaysVisible,
+ )}
+ >
+ <Flexbox horizontal align={'center'} gap={4}>
+ {indicators}
+ {startDirectoryId && (
+ <span className={indicatorStyles.hoverActions}>
+ <ActionIcon
+ icon={PlusIcon}
+ size={'small'}
+ title={tProject('directories.start')}
+ onClick={(e) => {
+ e.stopPropagation();
+ onStartInDirectory?.(startDirectoryId);
+ }}
+ />
+ </span>
+ )}
+ </Flexbox>
+ </div>
+ )}
+ </AccordionHeader>
+ <AccordionPanel contentStyle={{ padding: 0 }}>
+ <Flexbox gap={1} paddingBlock={1}>
+ {group.children.length === 0 && startDirectoryId ? (
+ // A section listed before any topic ran in it starts one in place.
+ <EmptyNavItem
+ title={t('actions.addNewTopic')}
+ onClick={() => onStartInDirectory?.(startDirectoryId)}
+ />
+ ) : (
+ group.children.map((topic) => renderSubGroupTopic(topic, suppressAgentAvatar))
+ )}
+ </Flexbox>
+ </AccordionPanel>
+ </AccordionItem>
+ );
+ },
+ isEqual,
+);
+
+TopicSubGroupItem.displayName = 'TopicSubGroupItem';
+
+export default TopicSubGroupItem;
+
+/** Sections start expanded; only the ones the user folds are remembered. */
+export const useSubGroupExpansion = (groups: GroupedTopic[] | undefined) => {
+ const [collapsedIds, setCollapsedIds] = useState<string[]>([]);
+ const expandedIds = useMemo(
+ () => groups?.filter((group) => !collapsedIds.includes(group.id)).map((group) => group.id),
+ [groups, collapsedIds],
+ );
+ const onExpandedChange = useCallback(
+ (next: unknown[]) =>
+ setCollapsedIds((prev) => [
+ ...prev.filter((id) => !groups?.some((group) => group.id === id)),
+ ...(groups ?? []).filter((group) => !next.includes(group.id)).map((group) => group.id),
+ ]),
+ [groups],
+ );
+ return { expandedIds, onExpandedChange };
+};
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/useStartTopicInDirectory.ts b/src/features/AgentSidebar/Topic/TopicListContent/useStartTopicInDirectory.ts
new file mode 100644
index 00000000000..ca0813db773
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/useStartTopicInDirectory.ts
@@ -0,0 +1,41 @@
+import { AGENT_CHAT_URL } from '@lobechat/const';
+import { useCallback, useMemo } from 'react';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { useActiveLocation } from '@/hooks/useActiveLocation';
+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
+import { useQueryRoute } from '@/hooks/useQueryRoute';
+import { useAgentStore } from '@/store/agent';
+import { useChatStore } from '@/store/chat';
+
+import { buildPrefixedAgentRoutePath, parseAgentPathname } from '../../utils/agentPathname';
+
+/**
+ * The agent sidebar's "start a topic in this project directory" action. The
+ * directory pins the device, so nothing is committed to the agent default: the
+ * blank composer opens with the directory staged, and the first send binds the
+ * new topic to it.
+ */
+export const useStartTopicInDirectory = () => {
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const { aid: routeAgentId } = useActiveRouteParams<{ aid?: string }>();
+ const { pathname } = useActiveLocation();
+ const agentRoute = useMemo(() => parseAgentPathname(pathname), [pathname]);
+ const agentId = routeAgentId ?? agentRoute?.agentId ?? activeAgentId;
+ const router = useQueryRoute();
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
+
+ const startInDirectory = useCallback(
+ (projectWorkingDirectoryId: string) => {
+ if (!agentId) return;
+ useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });
+ useChatStore.getState().setPendingNewTopicDirectory({ agentId, projectWorkingDirectoryId });
+ router.push(
+ buildPrefixedAgentRoutePath(AGENT_CHAT_URL(agentId), agentRoute, activeWorkspaceSlug),
+ );
+ },
+ [agentId, router, agentRoute, activeWorkspaceSlug],
+ );
+
+ return { agentId, startInDirectory };
+};
diff --git a/src/features/AgentSidebar/Topic/hooks/useSidebarTopicGroups.ts b/src/features/AgentSidebar/Topic/hooks/useSidebarTopicGroups.ts
new file mode 100644
index 00000000000..dd0960a42e3
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/hooks/useSidebarTopicGroups.ts
@@ -0,0 +1,69 @@
+import isEqual from 'fast-deep-equal';
+import { useMemo } from 'react';
+
+import { useLocalMachineDeviceIds } from '@/hooks/useLocalMachineDeviceIds';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useGlobalStore } from '@/store/global';
+import { systemStatusSelectors } from '@/store/global/selectors';
+import { useProjectDirectories, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
+
+import { useScopedSidebarTopics } from '../useScopedTopics';
+import { useAgentTopicGroupMode } from './useAgentTopicGroupMode';
+
+/**
+ * The sidebar's top-level topic groups — the agent's own list, or the
+ * project-scoped one when a scope is mounted. The accordion and its
+ * expand/collapse-all toggle read the same groups, so their ids always match.
+ */
+export const useSidebarTopicGroups = () => {
+ const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
+ const topicSortBy = useUserStore(preferenceSelectors.topicSortBy);
+ const topicIncludeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);
+ const { topicGroupMode } = useAgentTopicGroupMode();
+
+ const scoped = useScopedSidebarTopics(
+ topicPageSize,
+ topicSortBy,
+ topicGroupMode,
+ topicIncludeCompleted,
+ );
+
+ // An agent's topics are placed on a device by their project directory when
+ // they carry no explicit device binding, so by-device grouping needs the
+ // directory registry. The project-scoped list loads its own.
+ const needsDirectories = !scoped.scope && topicGroupMode === 'byDevice';
+ useProjectDirectoryStore((s) => s.useFetchDirectories)(undefined, needsDirectories);
+ const directories = useProjectDirectories();
+
+ const localDeviceIds = useLocalMachineDeviceIds();
+ const groupSelector = useMemo(
+ () =>
+ topicSelectors.groupedTopicsForSidebar(
+ topicPageSize,
+ topicSortBy,
+ topicGroupMode,
+ topicIncludeCompleted,
+ localDeviceIds,
+ needsDirectories ? directories : undefined,
+ ),
+ [
+ topicPageSize,
+ topicSortBy,
+ topicGroupMode,
+ topicIncludeCompleted,
+ localDeviceIds,
+ needsDirectories,
+ directories,
+ ],
+ );
+ const agentGroups = useChatStore(groupSelector, isEqual);
+
+ return {
+ groups: scoped.scope ? scoped.groups : agentGroups,
+ scoped,
+ topicGroupMode,
+ };
+};
diff --git a/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx
index 45b6a87283d..af1fc5afbb0 100644
--- a/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx
+++ b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx
@@ -80,14 +80,15 @@ describe('useTopicFilterDropdownMenu group modes', () => {
vi.clearAllMocks();
});
- /** @example A single agent's own sidebar must not offer grouping by agent. */
- it('hides by agent in an unscoped agent sidebar', () => {
+ /** @example A single agent's own sidebar groups by device but never by agent. */
+ it('offers by device but hides by agent in an unscoped agent sidebar', () => {
const { result } = renderHook(() => useTopicFilterDropdownMenu());
expect(organizeLabels(result.current())).toEqual([
'filter.groupMode.byStatus',
'filter.groupMode.byTime',
'filter.groupMode.byProject',
+ 'filter.groupMode.byDevice',
'filter.groupMode.flat',
]);
});
diff --git a/src/features/AgentSidebar/Topic/useFilterMenu.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.tsx
index 0b601e34076..23549574a4a 100644
--- a/src/features/AgentSidebar/Topic/useFilterMenu.tsx
+++ b/src/features/AgentSidebar/Topic/useFilterMenu.tsx
@@ -27,13 +27,13 @@ export const useTopicFilterDropdownMenu = (): (() => DropdownItem[]) => {
]);
return useCallback(() => {
- // "by agent" and "by device" only exist where topics span multiple agents
- // and machines — the project-scoped list, where "by agent" is the default
- // and listed first. A single agent's own sidebar hides them. The project-scoped list already is one project, so it hides
- // "by project" instead.
+ // "by agent" only exists where topics span multiple agents — the
+ // project-scoped list, where it is the default and listed first. That list
+ // already is one project, so it hides "by project" instead. One agent's
+ // topics still run on several machines, so both lists group by device.
const groupModes: TopicGroupMode[] = scope
? ['byAgent', 'byStatus', 'byTime', 'byDevice', 'flat']
- : ['byStatus', 'byTime', 'byProject', 'flat'];
+ : ['byStatus', 'byTime', 'byProject', 'byDevice', 'flat'];
const sortByOptions: TopicSortBy[] = ['createdAt', 'updatedAt'];
return [
diff --git a/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts b/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts
index 32e04df1607..8a7e6194460 100644
--- a/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts
+++ b/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts
@@ -92,20 +92,13 @@ describe('resolveAgentTopicGroupMode', () => {
},
);
- /** @example byDevice picked in a project sidebar must not leak into a single agent's own sidebar. */
- it.each([{ agentTopicGroupMode: undefined }, { agentTopicGroupMode: 'byDevice' as const }])(
- 'normalizes byDevice to byTime for unscoped agent sidebars (config %o)',
- ({ agentTopicGroupMode }) => {
- // Same leak as byAgent: device attribution only exists on project feeds,
- // so an unscoped sidebar would bucket every topic under `no-device`.
- expect(
- resolveAgentTopicGroupMode({
- agentTopicGroupMode,
- globalMode: 'byDevice',
- }),
- ).toBe('byTime');
- },
- );
+ /** @example an agent's own sidebar groups by device too: its topics place by bound device or project directory. */
+ it.each([
+ { agentTopicGroupMode: undefined, globalMode: 'byDevice' as const },
+ { agentTopicGroupMode: 'byDevice' as const, globalMode: 'byTime' as const },
+ ])('keeps byDevice for unscoped agent sidebars (%o)', ({ agentTopicGroupMode, globalMode }) => {
+ expect(resolveAgentTopicGroupMode({ agentTopicGroupMode, globalMode })).toBe('byDevice');
+ });
});
describe('resolveProjectTopicGroupMode', () => {
diff --git a/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts b/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts
index 09f57dec471..b20d1439518 100644
--- a/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts
+++ b/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts
@@ -33,17 +33,15 @@ export const resolveAgentTopicGroupMode = ({
agentType?: HeterogeneousAgentType;
globalMode: TopicGroupMode;
}): TopicGroupMode => {
- const resolved = agentTopicGroupMode
- ? agentTopicGroupMode
- : getDefaultTopicGroupModeByAgentType(globalMode, agentType);
+ const resolved =
+ agentTopicGroupMode || getDefaultTopicGroupModeByAgentType(globalMode, agentType);
- // "by agent" and "by device" are only offered in project-scoped lists. When
- // they sit in the global preference (set from a project sidebar before
- // projects kept their own), a single
- // agent's own topics would render as one pointless self-named bucket — keep
- // the previous default grouping. Project-scoped lists resolve through
- // `resolveProjectTopicGroupMode` instead.
- return resolved === 'byAgent' || resolved === 'byDevice' ? 'byTime' : resolved;
+ // "by agent" is only offered in project-scoped lists. When it sits in the
+ // global preference (set from a project sidebar before projects kept their
+ // own), a single agent's own topics would render as one pointless self-named
+ // bucket — keep the previous default grouping. Project-scoped lists resolve
+ // through `resolveProjectTopicGroupMode` instead.
+ return resolved === 'byAgent' ? 'byTime' : resolved;
};
/**
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index 08b9acc70a3..df3cc3fad60 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -484,6 +484,8 @@ const groupedTopicsForSidebar =
groupMode: TopicGroupMode = 'byTime',
includeCompleted = true,
localDeviceIds?: readonly string[],
+ /** Project directories, so byDevice can place a topic by its directory's device. */
+ directories?: ReadonlyArray<TopicDeviceDirectory>,
) =>
(s: ChatStoreState): GroupedTopic[] => {
const limitedTopics = displayTopicsForSidebar(pageSize, sortBy, includeCompleted)(s);
@@ -499,7 +501,7 @@ const groupedTopicsForSidebar =
groupMode,
sortBy,
loadingTopicIds,
- undefined,
+ directories,
localDeviceIds,
);
};