🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(topic): merge same-project directory groups and add group-by-agent mode (#20592)
Arvin Xu1718a97c9055
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.jsonindex aabc9ac0174..4b19fb91b33 100644--- a/locales/en-US/topic.json+++ b/locales/en-US/topic.json@@ -70,6 +70,7 @@"failedStatusTip": "This run hit an error — open it to take a look.","favorite": "Favorite","filter.filter": "Filter",+ "filter.groupMode.byAgent": "By agent","filter.groupMode.byProject": "By project","filter.groupMode.byStatus": "By status","filter.groupMode.byTime": "By time",@@ -79,6 +80,7 @@"filter.sort": "Sort by","filter.sortBy.createdAt": "Created time","filter.sortBy.updatedAt": "Updated time",+ "groupTitle.byAgent.unknown": "Unknown agent","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.jsonindex 923e82fa565..e364ca1e328 100644--- a/locales/zh-CN/topic.json+++ b/locales/zh-CN/topic.json@@ -70,6 +70,7 @@"failedStatusTip": "当前执行遇到了错误,点击查看详情","favorite": "收藏","filter.filter": "筛选",+ "filter.groupMode.byAgent": "按 Agent","filter.groupMode.byProject": "按项目","filter.groupMode.byStatus": "按状态","filter.groupMode.byTime": "按时间阶段",@@ -79,6 +80,7 @@"filter.sort": "排序","filter.sortBy.createdAt": "按创建时间","filter.sortBy.updatedAt": "按更新时间",+ "groupTitle.byAgent.unknown": "未知 Agent","groupTitle.byProject.noProject": "无目录","groupTitle.byStatus.active": "活跃","groupTitle.byStatus.archived": "已归档",diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.tsindex 8fb2238bce5..fbf082eb9f3 100644--- a/packages/locales/src/default/topic.ts+++ b/packages/locales/src/default/topic.ts@@ -93,6 +93,7 @@ export default {'metaCard.pr.merged': 'Merged','metaCard.pr.open': 'Open','filter.filter': 'Filter',+ 'filter.groupMode.byAgent': 'By agent','filter.groupMode.byProject': 'By project','filter.groupMode.byStatus': 'By status','filter.groupMode.byTime': 'By time',@@ -102,6 +103,7 @@ export default {'filter.sort': 'Sort by','filter.sortBy.createdAt': 'Created time','filter.sortBy.updatedAt': 'Updated time',+ 'groupTitle.byAgent.unknown': 'Unknown agent','groupTitle.byProject.noProject': 'No directory','groupTitle.byStatus.active': 'Active','groupTitle.byStatus.archived': 'Archived',diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.tsindex ce34464003f..ade51378114 100644--- a/packages/types/src/agent/chatConfig.ts+++ b/packages/types/src/agent/chatConfig.ts@@ -308,7 +308,7 @@ export const AgentChatConfigSchema = zthinkingLevel3: z.enum(['low', 'medium', 'high']).optional(),thinkingLevel4: z.enum(['minimal', 'high']).optional(),toolResultMaxLength: z.number().default(25000),- topicGroupMode: z.enum(['byTime', 'byProject', 'flat', 'byStatus']).optional(),+ topicGroupMode: z.enum(['byTime', 'byProject', 'flat', 'byStatus', 'byAgent']).optional(),urlContext: z.boolean().optional(),useModelBuiltinSearch: z.boolean().optional(),})diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 3640b2c0245..0236c1d56dd 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -16,7 +16,7 @@ export type ShareVisibility = 'private' | 'link';export type TimeGroupId ='today' | 'yesterday' | 'week' | 'month' | `${number}-${string}` | `${number}`;-export type TopicGroupMode = 'byTime' | 'byProject' | 'flat' | 'byStatus';+export type TopicGroupMode = 'byTime' | 'byProject' | 'flat' | 'byStatus' | 'byAgent';export type TopicSortBy = 'createdAt' | 'updatedAt';/**diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 011d549aa7f..51fba29c1c7 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -395,7 +395,7 @@ export const UserPreferenceSchema = zsidebarHiddenGroupIds: z.array(z.string()).optional(),terminalFontFamily: z.string().optional(),telemetry: z.boolean().nullable(),- topicGroupMode: z.enum(['byTime', 'byProject', 'flat', 'byStatus']).optional(),+ topicGroupMode: z.enum(['byTime', 'byProject', 'flat', 'byStatus', 'byAgent']).optional(),topicIncludeCompleted: z.boolean().optional(),topicSortBy: z.enum(['createdAt', 'updatedAt']).optional(),useCmdEnterToSend: z.boolean().optional(),diff --git a/packages/utils/src/client/topic.test.ts b/packages/utils/src/client/topic.test.tsindex c38c3ad4d46..c21c16b9baa 100644--- a/packages/utils/src/client/topic.test.ts+++ b/packages/utils/src/client/topic.test.ts@@ -5,6 +5,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';import {getTopicWorkingDirectoryEffectivePath,getTopicWorkingDirectorySourcePath,+ groupTopicsByAgent,groupTopicsByProject,groupTopicsByStatus,groupTopicsByTime,@@ -595,3 +596,193 @@ it('keeps project directory bindings and device identities separate', () => {];expect(groupTopicsByProject(topics, 'updatedAt')).toHaveLength(4);});++describe('groupTopicsByProject project merging', () => {+ const base = { createdAt: 0, title: 'Work', updatedAt: 0 };++ /** @example Two directories of one project must collapse into a single sidebar group. */+ it('merges directories of the same project into one project-id group', () => {+ // ROOT CAUSE:+ //+ // Directory-bound topics were grouped per `projectWorkingDirectoryId`, so+ // two directories bound to the same project rendered as two identically+ // named groups in the sidebar's "by project" mode. Grouping by the+ // topic's `projectId` first merges them into a single group.+ const topics: ChatTopic[] = [+ {+ ...base,+ createdAt: 3,+ updatedAt: 3,+ id: 'recent',+ projectId: 'project-1',+ projectWorkingDirectoryId: 'directory-a',+ metadata: { workingDirectory: '/work/lobehub' },+ },+ {+ ...base,+ createdAt: 1,+ updatedAt: 1,+ id: 'older',+ projectId: 'project-1',+ projectWorkingDirectoryId: 'directory-b',+ metadata: { workingDirectory: '/home/lobehub' },+ },+ ];++ expect(groupTopicsByProject(topics, 'updatedAt')).toEqual([+ {+ children: [topics[0], topics[1]],+ id: 'project-id:project-1',+ // Same-basename directories collide, so the label expands to the+ // distinguishing parent of the most recently active directory.+ title: 'work/lobehub',+ },+ ]);+ });++ /** @example A project conversation without a working directory still belongs to its project group. */+ it('merges pathless project topics into their project group', () => {+ const topics: ChatTopic[] = [+ {+ ...base,+ createdAt: 2,+ updatedAt: 2,+ id: 'with-directory',+ projectId: 'project-1',+ projectWorkingDirectoryId: 'directory-a',+ metadata: { workingDirectory: '/work/lobehub' },+ },+ { ...base, createdAt: 1, updatedAt: 1, id: 'conversation-only', projectId: 'project-1' },+ ];++ expect(groupTopicsByProject(topics, 'updatedAt')).toEqual([+ {+ children: [topics[0], topics[1]],+ id: 'project-id:project-1',+ title: 'lobehub',+ },+ ]);+ });++ /** @example Topics without a project binding keep their per-directory groups. */+ it('keeps directory grouping when topics have no project binding', () => {+ const topics: ChatTopic[] = [+ {+ ...base,+ id: 'a',+ projectWorkingDirectoryId: 'directory-a',+ metadata: { workingDirectory: '/repo-a' },+ },+ {+ ...base,+ id: 'b',+ projectWorkingDirectoryId: 'directory-b',+ metadata: { workingDirectory: '/repo-b' },+ },+ ];++ expect(groupTopicsByProject(topics, 'updatedAt')).toEqual([+ {+ children: [topics[0]],+ id: 'project-directory:directory-a',+ title: 'repo-a',+ },+ {+ children: [topics[1]],+ id: 'project-directory:directory-b',+ title: 'repo-b',+ },+ ]);+ });++ /** @example Distinct projects never merge, and project groups stay above unbound topics. */+ it('keeps distinct projects separate and sorts the no-project bucket last', () => {+ const topics: ChatTopic[] = [+ { ...base, createdAt: 1, updatedAt: 1, id: 'unbound' },+ {+ ...base,+ createdAt: 2,+ updatedAt: 2,+ id: 'mobile',+ projectId: 'project-2',+ metadata: { workingDirectory: '/home/lobehub_mobile' },+ },+ {+ ...base,+ createdAt: 3,+ updatedAt: 3,+ id: 'main',+ projectId: 'project-1',+ metadata: { workingDirectory: '/home/lobehub' },+ },+ ];++ expect(groupTopicsByProject(topics, 'updatedAt').map((group) => group.id)).toEqual([+ 'project-id:project-1',+ 'project-id:project-2',+ 'no-project',+ ]);+ });+});++describe('groupTopicsByAgent', () => {+ type AgentRow = ChatTopic & {+ agentId?: string | null;+ agentName?: string | null;+ agentTitle?: string | null;+ };++ const createRow = (+ id: string,+ updatedAt: number,+ agent?: { agentId?: string | null; agentName?: string | null; agentTitle?: string | null },+ ): AgentRow => ({ agentId: null, createdAt: updatedAt, id, title: id, updatedAt, ...agent });++ it('should return empty array for empty input', () => {+ expect(groupTopicsByAgent([], 'updatedAt')).toEqual([]);+ });++ it('groups topics by agent with titles from agent metadata', () => {+ const topics = [+ createRow('a1', 2, { agentId: 'agent-x', agentTitle: 'LobeHub' }),+ createRow('a2', 1, { agentId: 'agent-x', agentTitle: 'LobeHub' }),+ createRow('b1', 3, { agentId: 'agent-y', agentName: 'lobehub_mobile' }),+ ];++ expect(groupTopicsByAgent(topics, 'updatedAt')).toEqual([+ { children: [topics[2]], id: 'agent:agent-y', title: 'lobehub_mobile' },+ { children: [topics[0], topics[1]], id: 'agent:agent-x', title: 'LobeHub' },+ ]);+ });++ it('falls back to agentName when agentTitle is absent', () => {+ const topics = [createRow('a1', 1, { agentId: 'agent-x', agentName: 'lobehub' })];++ expect(groupTopicsByAgent(topics, 'updatedAt')[0]).toEqual({+ children: topics,+ id: 'agent:agent-x',+ title: 'lobehub',+ });+ });++ it('buckets rows without agent attribution as a title-less no-agent group', () => {+ const topics = [createRow('a', 2), createRow('b', 1)];++ expect(groupTopicsByAgent(topics, 'updatedAt')).toEqual([+ { children: topics, id: 'no-agent', title: undefined },+ ]);+ });++ it('sorts children and groups by the chosen field descending', () => {+ const topics = [+ createRow('old', 1, { agentId: 'agent-x' }),+ createRow('new', 5, { agentId: 'agent-x' }),+ createRow('other-recent', 4, { agentId: 'agent-y' }),+ ];++ const result = groupTopicsByAgent(topics, 'createdAt');++ expect(result.map((group) => group.id)).toEqual(['agent:agent-x', 'agent:agent-y']);+ expect(result[0].children.map((topic) => topic.id)).toEqual(['new', 'old']);+ });+});diff --git a/packages/utils/src/client/topic.ts b/packages/utils/src/client/topic.tsindex 3458741642d..df81c077117 100644--- a/packages/utils/src/client/topic.ts+++ b/packages/utils/src/client/topic.ts@@ -117,6 +117,7 @@ export const groupTopicsByUpdatedTime = (topics: ChatTopic[]) =>// Project-based groupingconst NO_PROJECT_GROUP_ID = 'no-project';const PROJECT_GROUP_PREFIX = 'project:';+const PROJECT_ID_GROUP_PREFIX = 'project-id:';/*** Normalizes project display names to their shortest distinguishing path suffix.@@ -179,17 +180,21 @@ export const getTopicWorkingDirectoryEffectivePath = (topic: ChatTopic): stringgetTopicMetadataWorkingDirectoryEffectivePath(topic.metadata);/**- * Groups topics by source directory with distinguishable project titles.+ * Groups topics by their owning project, falling back to source directory and+ * raw path identities for topics that carry no project binding.** Use when:* - Rendering project groups in a topic sidebar or management view.** Expects:- * - Topics with optional source or worktree directory metadata.+ * - Topics with optional `projectId` / `projectWorkingDirectoryId` bindings+ * and optional source or worktree directory metadata.* - A timestamp field for descending activity order.** Returns:- * - Stable path-based group IDs and sorted topics, with no-project topics last.+ * - `project-id:{projectId}` groups that merge every directory of one project+ * into a single group, `project-directory:{id}` / path-based IDs for topics+ * without a project, and `no-project` last.* - Basenames for unique projects and distinguishing path suffixes for collisions.*/export const groupTopicsByProject = (@@ -198,25 +203,26 @@ export const groupTopicsByProject = (): GroupedTopic[] => {if (!topics.length) return [];- const groupsMap = new Map<string, { children: ChatTopic[]; path: string; segments: string[] }>();+ const groupsMap = new Map<string, { children: ChatTopic[]; paths: Set<string> }>();for (const topic of topics) {const normalized = getTopicWorkingDirectorySourcePath(topic) ?? '';const deviceId = topic.metadata?.boundDeviceId;- const id = topic.projectWorkingDirectoryId- ? `project-directory:${topic.projectWorkingDirectoryId}`- : normalized- ? `${PROJECT_GROUP_PREFIX}${deviceId ? `${deviceId}:` : ''}${normalized}`- : NO_PROJECT_GROUP_ID;+ const id = topic.projectId+ ? `${PROJECT_ID_GROUP_PREFIX}${topic.projectId}`+ : topic.projectWorkingDirectoryId+ ? `project-directory:${topic.projectWorkingDirectoryId}`+ : normalized+ ? `${PROJECT_GROUP_PREFIX}${deviceId ? `${deviceId}:` : ''}${normalized}`+ : NO_PROJECT_GROUP_ID;const existing = groupsMap.get(id);if (existing) {existing.children.push(topic);+ if (normalized) existing.paths.add(normalized);} else {- // Parse each source path once; display labels never change its grouping identity.groupsMap.set(id, {children: [topic],- path: normalized,- segments: normalized.split(/[/\\]+/).filter(Boolean),+ paths: normalized ? new Set([normalized]) : new Set(),});}}@@ -226,20 +232,42 @@ export const groupTopicsByProject = (group.children.sort((a, b) => getTopicSortTime(b, field) - getTopicSortTime(a, field));}- // Count suffixes once so an expanding project list does not compare every pair of paths.+ // Count suffixes once so an expanding project list does not compare every pair+ // of paths. A merged project group contributes each of its directories once.const suffixCounts = new Map<string, number>();- for (const { segments } of groupsMap.values()) {- for (let depth = 1; depth <= segments.length; depth++) {- const suffix = segments.slice(-depth).join('/');- suffixCounts.set(suffix, (suffixCounts.get(suffix) ?? 0) + 1);+ for (const { paths } of groupsMap.values()) {+ for (const path of paths) {+ const segments = path.split(/[/\\]+/).filter(Boolean);+ for (let depth = 1; depth <= segments.length; depth++) {+ const suffix = segments.slice(-depth).join('/');+ suffixCounts.set(suffix, (suffixCounts.get(suffix) ?? 0) + 1);+ }}}const groups: GroupedTopic[] = Array.from(groupsMap.entries()).map(- ([id, { children, path, segments }]) => ({- children,- id,- title: id === NO_PROJECT_GROUP_ID ? undefined : getProjectName(path, segments, suffixCounts),- }),+ ([id, { children, paths }]) => {+ // A merged project group spans directories; its most recently active+ // directory names the group. Groups without any path stay title-less and+ // let the renderer resolve the project name from its directory registry.+ const primaryPath =+ id === NO_PROJECT_GROUP_ID+ ? undefined+ : (children+ .map((topic) => getTopicWorkingDirectorySourcePath(topic))+ .find((path): path is string => !!path) ?? [...paths][0]);+ return {+ children,+ id,+ title:+ id === NO_PROJECT_GROUP_ID || !primaryPath+ ? undefined+ : getProjectName(+ primaryPath,+ primaryPath.split(/[/\\]+/).filter(Boolean),+ suffixCounts,+ ),+ };+ },);// Most-recently-active project first; "no project" always last@@ -252,6 +280,68 @@ export const groupTopicsByProject = (});};+// Agent-based grouping+const NO_AGENT_GROUP_ID = 'no-agent';+const AGENT_GROUP_PREFIX = 'agent:';++/**+ * Topics only carry agent attribution on feeds that join it in (the project+ * topic list selects `agentId` / `agentTitle` / `agentName` / `agentAvatar`+ * per row); per-agent sidebar buckets omit it and every row resolves to the+ * single `no-agent` bucket, where the renderer shows the active agent.+ */+interface AgentAttributedTopic extends ChatTopic {+ agentId?: string | null;+ agentName?: string | null;+ agentTitle?: string | null;+}++/**+ * Groups topics by their creating agent with agent-attributed titles.+ *+ * Use when:+ * - Rendering the "group by agent" mode in a topic sidebar whose topics span+ * multiple agents (e.g. the project topic list).+ *+ * Returns:+ * - `agent:{agentId}` groups sorted by most recent activity, titled from the+ * first row's agent metadata, and a title-less `no-agent` bucket for rows+ * without attribution (the renderer names those from its agent context).+ */+export const groupTopicsByAgent = (+ topics: AgentAttributedTopic[],+ field: 'createdAt' | 'updatedAt',+): GroupedTopic[] => {+ if (!topics.length) return [];++ const groupsMap = new Map<string, AgentAttributedTopic[]>();+ for (const topic of topics) {+ const id = topic.agentId ? `${AGENT_GROUP_PREFIX}${topic.agentId}` : NO_AGENT_GROUP_ID;+ const existing = groupsMap.get(id);+ if (existing) {+ existing.push(topic);+ } else {+ groupsMap.set(id, [topic]);+ }+ }++ for (const children of groupsMap.values()) {+ children.sort((a, b) => getTopicSortTime(b, field) - getTopicSortTime(a, field));+ }++ return Array.from(groupsMap.entries())+ .map(([id, children]) => ({+ children,+ id,+ title: children[0]?.agentTitle ?? children[0]?.agentName ?? undefined,+ }))+ .sort((a, b) => {+ const aTime = a.children[0] ? getTopicSortTime(a.children[0], field) : 0;+ const bTime = b.children[0] ? getTopicSortTime(b.children[0], field) : 0;+ return bTime - aTime;+ });+};+// The display buckets for status grouping. These are NOT raw `ChatTopicStatus`// values: the three states that need the user's attention — awaiting a human,// failed, and an unread completion — collapse into a single `pending` bucket sodiff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsxindex ddd70c99fef..49e4d0948fb 100644--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx@@ -225,6 +225,12 @@ interface TopicItemProps {*/showWorkingDirectory?: boolean;status?: ChatTopicStatus | null;+ /**+ * Group headers that already identify the owning agent (the by-agent+ * grouping) suppress the row's leading agent avatar — the identity lives in+ * the header, and the row keeps its status/identity icons instead.+ */+ suppressAgentAvatar?: boolean;title: string;/** Creator of the topic; drives the workspace creator avatar. */userId?: string;@@ -257,6 +263,7 @@ const TopicItemRow = memo<TopicItemRowProps>(isTopicActive,navRef,showThreadList,+ suppressAgentAvatar,}) => {const scopedTopic = useScopedTopic(id);const scope = useTopicListScope();@@ -553,21 +560,22 @@ const TopicItemRow = memo<TopicItemRowProps>(// shrinks into a bottom-right corner badge. Personal mode keeps the// original layout untouched.const ownIconNode = statusIconNode ?? identityIconNode;- const leadingIconNode = scopedTopic ? (- <Avatar- name={scopedTopic.agentName || scopedTopic.agentTitle || undefined}- size={20}- title={scopedTopic.agentName || scopedTopic.agentTitle || undefined}- avatar={- scopedTopic.agentAvatar ||- (activeAgentId === inboxId ? DEFAULT_INBOX_AVATAR : DEFAULT_AVATAR)- }- />- ) : author ? (- <TopicCreatorAvatar corner={ownIconNode} userId={userId} />- ) : (- (ownIconNode ?? idleIconPlaceholder)- );+ const leadingIconNode =+ scopedTopic && !suppressAgentAvatar ? (+ <Avatar+ name={scopedTopic.agentName || scopedTopic.agentTitle || undefined}+ size={20}+ title={scopedTopic.agentName || scopedTopic.agentTitle || undefined}+ avatar={+ scopedTopic.agentAvatar ||+ (activeAgentId === inboxId ? DEFAULT_INBOX_AVATAR : DEFAULT_AVATAR)+ }+ />+ ) : author ? (+ <TopicCreatorAvatar corner={ownIconNode} userId={userId} />+ ) : (+ (ownIconNode ?? idleIconPlaceholder)+ );const navItem = (<TopicItemContextMenu fav={fav} id={id} status={status} title={title}>@@ -583,7 +591,7 @@ const TopicItemRow = memo<TopicItemRowProps>(titleColor={cssVar.colorText}extra={<>- {scopedTopic && ownIconNode}+ {scopedTopic && !suppressAgentAvatar && ownIconNode}<TopicMigrationIndicator agentId={activeAgentId} topicId={id} />{/* Gated on the SAME boolean that draws the running ring: both say"this row is visibly running", and a row that stopped spinningdiff --git a/src/features/AgentSidebar/Topic/List/index.tsx b/src/features/AgentSidebar/Topic/List/index.tsxindex e7a6a2ec30b..ce9298c8ac9 100644--- a/src/features/AgentSidebar/Topic/List/index.tsx+++ b/src/features/AgentSidebar/Topic/List/index.tsx@@ -14,6 +14,7 @@ import { topicSelectors } from '@/store/chat/selectors';import AllTopicsDrawer from '../AllTopicsDrawer';import { useAgentTopicGroupMode } from '../hooks/useAgentTopicGroupMode';+import ByAgentMode from '../TopicListContent/ByAgentMode';import ByProjectMode from '../TopicListContent/ByProjectMode';import ByStatusMode from '../TopicListContent/ByStatusMode';import ByTimeMode from '../TopicListContent/ByTimeMode';@@ -62,6 +63,8 @@ const TopicList = memo(() => {<ByProjectMode />) : topicGroupMode === 'byStatus' ? (<ByStatusMode />+ ) : topicGroupMode === 'byAgent' ? (+ <ByAgentMode />) : (<ByTimeMode />)}diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsxnew file mode 100644index 00000000000..e351b9e64f9--- /dev/null+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx@@ -0,0 +1,59 @@+/**+ * @vitest-environment happy-dom+ */+import { AccordionRoot } from '@lobehub/ui/base-ui';+import { render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import GroupItem from './GroupItem';++vi.mock('@/store/agent', () => ({+ useAgentStore: (selector: (state: unknown) => unknown) => selector({ activeAgentId: 'agent-1' }),+}));++vi.mock('@/store/agent/selectors', () => ({+ agentSelectors: {+ currentAgentMeta: () => ({ title: '验收合并-Alpha', avatar: '🅰️' }),+ getAgentMetaById: () => () => ({}),+ },+}));++// Capture what the group hands each row: by-agent buckets are named in the+// group header, so rows must not render a second leading agent avatar.+vi.mock('../../List/Item', () => ({+ default: (props: { suppressAgentAvatar?: boolean; title: string }) => (+ <div data-suppress={props.suppressAgentAvatar ? 'yes' : 'no'}>{props.title}</div>+ ),+}));++vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ ...(await import('~base-ui-stubs')).baseUiStubs,+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++describe('TopicByAgentGroupItem', () => {+ /** @example Review feedback: rows under an agent-named bucket must not repeat the avatar. */+ it('suppresses the row leading agent avatar because the group header already identifies the agent', () => {+ // ROOT CAUSE: the by-agent grouping named every bucket after its agent,+ // but each row still rendered the same avatar at its leading position —+ // the same identity twice in one row.+ render(+ <AccordionRoot defaultValue={['agent:agt_acc_merge_alpha']}>+ <GroupItem+ expanded+ group={{+ children: [{ createdAt: 1, id: 't1', title: 'A1-目录A任务', updatedAt: 1 }],+ id: 'agent:agt_acc_merge_alpha',+ title: '验收合并-Alpha',+ }}+ />+ </AccordionRoot>,+ );++ expect(screen.getByText('A1-目录A任务').getAttribute('data-suppress')).toBe('yes');+ });+});diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsxnew file mode 100644index 00000000000..fb501dd0753--- /dev/null+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx@@ -0,0 +1,113 @@+'use client';++import { Center, Flexbox } from '@lobehub/ui';+import {+ AccordionHeader,+ AccordionItem,+ AccordionPanel,+ AccordionTrigger,+ Text,+} from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import isEqual from 'fast-deep-equal';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import Avatar from '@/components/Avatar';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';++import TopicItem from '../../List/Item';+import { type GroupItemComponentProps } from '../GroupedAccordion';++const AGENT_GROUP_PREFIX = 'agent:';++const styles = createStaticStyles(({ css }) => ({+ avatarWrap: css`+ flex: none;+ border-radius: 50%;+ background: ${cssVar.colorFillTertiary};+ `,+}));++/**+ * Agent attribution only exists on feeds that join it in (the project topic+ * list selects agent columns per row); per-agent sidebar buckets omit it, so+ * those rows flow into the `no-agent` bucket and resolve to the active agent.+ */+interface AgentAttributedRow {+ agentAvatar?: string | null;+ agentId?: string | null;+ agentName?: string | null;+ agentTitle?: string | null;+}++const GroupItem = memo<GroupItemComponentProps>(({ group }) => {+ const { t } = useTranslation('topic');+ const { id, title, children } = group;+ const agentId = id.startsWith(AGENT_GROUP_PREFIX)+ ? id.slice(AGENT_GROUP_PREFIX.length)+ : undefined;++ const activeAgentId = useAgentStore((s) => s.activeAgentId);+ const activeMeta = useAgentStore(agentSelectors.currentAgentMeta);+ const registeredMeta = useAgentStore((s) =>+ agentId ? agentSelectors.getAgentMetaById(agentId)(s) : undefined,+ );++ const row = children[0] as AgentAttributedRow | undefined;+ // The unattributed bucket — or a bucket of the currently open agent — speaks+ // for the agent context the list already has; any other bucket must resolve+ // from its own rows or the agent registry to avoid mislabeling.+ const isOwnBucket = !agentId || agentId === activeAgentId;++ const avatar =+ row?.agentAvatar || registeredMeta?.avatar || (isOwnBucket ? activeMeta.avatar : undefined);+ const name =+ title ??+ registeredMeta?.title ??+ registeredMeta?.name ??+ (isOwnBucket ? (activeMeta.title ?? activeMeta.name) : undefined) ??+ t('groupTitle.byAgent.unknown');++ return (+ <AccordionItem value={id}>+ <AccordionHeader>+ <AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>+ <Flexbox horizontal align="center" gap={8} height={24} style={{ overflow: 'hidden' }}>+ <Center className={styles.avatarWrap} flex={'none'} height={18} width={18}>+ <Avatar avatar={avatar} name={name} size={18} />+ </Center>+ <Text ellipsis fontSize={14} style={{ flex: 1 }}>+ {name}+ </Text>+ </Flexbox>+ </AccordionTrigger>+ </AccordionHeader>+ <AccordionPanel contentStyle={{ padding: 0 }}>+ <Flexbox gap={1} paddingBlock={1}>+ {children.map((topic) => (+ <TopicItem+ // The group header already names the owning agent — the row+ // must not repeat the avatar at its leading position.+ showWorkingDirectory+ suppressAgentAvatar+ fav={topic.favorite}+ id={topic.id}+ key={topic.id}+ metadata={topic.metadata}+ runStartedAt={topic.runStartedAt}+ status={topic.status}+ title={topic.title}+ userId={topic.userId}+ />+ ))}+ </Flexbox>+ </AccordionPanel>+ </AccordionItem>+ );+}, isEqual);++GroupItem.displayName = 'TopicByAgentGroupItem';++export default GroupItem;diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/index.tsxnew file mode 100644index 00000000000..4d9a978ed82--- /dev/null+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/index.tsx@@ -0,0 +1,8 @@+'use client';++import GroupedAccordion from '../GroupedAccordion';+import GroupItem from './GroupItem';++const ByAgentMode = () => <GroupedAccordion GroupItem={GroupItem} />;++export default ByAgentMode;diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsxindex 0b89c781517..fe5a63425f6 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx@@ -40,6 +40,11 @@ vi.mock('@/features/Projects/WorkingDirectories/AgentDirectoryActions', () => ({),}));+const openProjectTopicModalMock = vi.hoisted(() => vi.fn());+vi.mock('@/features/Projects/WorkingDirectories/StartDirectoryModal', () => ({+ openProjectTopicModal: openProjectTopicModalMock,+}));+vi.mock('react-router', () => ({useParams: () => routeParamsMock,}));@@ -308,3 +313,156 @@ it('shows the directory title inside Project scope rather than repeating the proexpect(screen.getByText('repo-a')).toBeInTheDocument();expect(screen.queryByRole('link', { name: 'Shared Project' })).not.toBeInTheDocument();});++it('resolves a merged project group through any directory of that project', () => {+ // Merged `project-id:` groups span several directories of one project, and+ // their most recent topic may not name a directory at all — the project+ // identity must come from the group id, not from the first child's directory.+ directoryRows.push(+ {+ id: 'binding-a',+ projectName: 'LobeHub',+ projectSlug: 'lobehub',+ projectId: 'prj-merged',+ projectAvatar: '📦',+ },+ {+ id: 'binding-b',+ projectName: 'LobeHub',+ projectSlug: 'lobehub',+ projectId: 'prj-merged',+ projectAvatar: '📦',+ },+ );+ render(+ <AccordionRoot defaultValue={['project-id:prj-merged']}>+ <GroupItem+ expanded+ group={{+ id: 'project-id:prj-merged',+ title: 'lobehub',+ children: [+ {+ id: 'topic-conversation-only',+ title: 'Chat',+ createdAt: 3,+ updatedAt: 3,+ projectId: 'prj-merged',+ },+ {+ id: 'topic-directory',+ title: 'Work',+ createdAt: 2,+ updatedAt: 2,+ projectId: 'prj-merged',+ projectWorkingDirectoryId: 'binding-b',+ metadata: { workingDirectory: '/other/lobehub' },+ },+ ],+ }}+ />+ </AccordionRoot>,+ );+ fireEvent.click(screen.getByRole('link', { name: 'LobeHub' }));+ expect(routerPushMock).toHaveBeenCalledWith('/project/lobehub');+});++it('opens the plain new-topic composer when a merged project group spans multiple directories', () => {+ // ROOT CAUSE: the first fix opened a chooser modal here, but the expected+ // habit is the plain new-topic composer — the user picks the machine in the+ // composer control bar, so no modal may pop and no directory default may be+ // pre-committed for a multi-machine merged group.+ directoryRows.length = 0;+ openProjectTopicModalMock.mockClear();+ commitAgentDefaultMock.mockClear();+ switchTopicMock.mockClear();+ routerPushMock.mockClear();+ directoryRows.push(+ {+ id: 'binding-multi-a',+ projectName: 'Multi Project',+ projectSlug: 'multi-project',+ projectId: 'prj-multi',+ projectAvatar: '📦',+ },+ {+ id: 'binding-multi-b',+ projectName: 'Multi Project',+ projectSlug: 'multi-project',+ projectId: 'prj-multi',+ projectAvatar: '📦',+ },+ );+ render(+ <AccordionRoot defaultValue={['project-id:prj-multi']}>+ <GroupItem+ expanded+ group={{+ id: 'project-id:prj-multi',+ title: 'multi',+ children: [+ {+ id: 'topic-multi-a',+ title: 'Work A',+ createdAt: 2,+ updatedAt: 2,+ projectId: 'prj-multi',+ projectWorkingDirectoryId: 'binding-multi-a',+ metadata: { workingDirectory: '/repo-a' },+ },+ {+ id: 'topic-multi-b',+ title: 'Work B',+ createdAt: 1,+ updatedAt: 1,+ projectId: 'prj-multi',+ projectWorkingDirectoryId: 'binding-multi-b',+ metadata: { workingDirectory: '/repo-b' },+ },+ ],+ }}+ />+ </AccordionRoot>,+ );+ fireEvent.click(screen.getByRole('button', { name: 'directories.start' }));+ expect(openProjectTopicModalMock).not.toHaveBeenCalled();+ expect(commitAgentDefaultMock).not.toHaveBeenCalled();+ expect(switchTopicMock).toHaveBeenCalledWith(null, { skipRefreshMessage: true });+ expect(routerPushMock).toHaveBeenCalledWith('/agent/agent-1');+});++it('keeps the direct start action when a merged project group has a single directory', () => {+ directoryRows.length = 0;+ openProjectTopicModalMock.mockClear();+ directoryRows.push({+ id: 'binding-single',+ projectName: 'Single Project',+ projectSlug: 'single-project',+ projectId: 'prj-single',+ projectAvatar: '📦',+ });+ render(+ <AccordionRoot defaultValue={['project-id:prj-single']}>+ <GroupItem+ expanded+ group={{+ id: 'project-id:prj-single',+ title: 'single',+ children: [+ {+ id: 'topic-single',+ title: 'Work',+ createdAt: 1,+ updatedAt: 1,+ projectId: 'prj-single',+ projectWorkingDirectoryId: 'binding-single',+ metadata: { workingDirectory: '/repo' },+ },+ ],+ }}+ />+ </AccordionRoot>,+ );+ expect(screen.queryByRole('button', { name: 'directories.start' })).not.toBeInTheDocument();+ expect(openProjectTopicModalMock).not.toHaveBeenCalled();+});diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsxindex 02819818d4f..ccffb2f08f7 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx@@ -6,11 +6,12 @@ import {AccordionPanel,accordionStyles,AccordionTrigger,+ ActionIcon,Text,} from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';import isEqual from 'fast-deep-equal';-import { FolderClosedIcon, FolderOpenIcon, type LucideIcon } from 'lucide-react';+import { FolderClosedIcon, FolderOpenIcon, type LucideIcon, PlusIcon } from 'lucide-react';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -43,6 +44,7 @@ import {} from './statusCounts';const PROJECT_GROUP_PREFIX = 'project:';+const PROJECT_ID_GROUP_PREFIX = 'project-id:';const styles = createStaticStyles(({ css }) => ({statusBadge: css`@@ -170,12 +172,24 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {const { id, title, children } = group;const scope = useTopicListScope();const navigate = useWorkspaceAwareNavigate();+ // `project-id:` groups merge every directory of one project — resolve the+ // project through any of its directories; directory/path groups keep the+ // first child's exact directory so a shared path can't cross projects.+ const projectId = id.startsWith(PROJECT_ID_GROUP_PREFIX)+ ? id.slice(PROJECT_ID_GROUP_PREFIX.length)+ : undefined;useProjectDirectoryStore((s) => s.useFetchDirectories)(undefined,- !!children[0]?.projectWorkingDirectoryId,+ !!children[0]?.projectWorkingDirectoryId || !!projectId,);const directories = useProjectDirectories();- const project = directories.find((d) => d.id === children[0]?.projectWorkingDirectoryId);+ const project = projectId+ ? directories.find((d) => d.projectId === projectId)+ : directories.find((d) => d.id === children[0]?.projectWorkingDirectoryId);+ const projectDirectories = useMemo(+ () => (projectId ? directories.filter((d) => d.projectId === projectId) : []),+ [directories, projectId],+ );const workingDirectory = useMemo(() =>@@ -214,7 +228,22 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {activeWorkspaceSlug,]);+ // A merged project group may span several machines. It opens the plain new+ // topic composer — no directory is pre-committed and no chooser modal pops;+ // the user picks the machine/directory in the composer control bar, the+ // same habit as the header's new-topic action. Single-directory groups keep+ // the legacy direct start above.+ const handleStartPlain = useCallback(() => {+ if (!currentAgentId || !targetAgentId) return;+ useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });+ router.push(+ buildPrefixedAgentRoutePath(AGENT_CHAT_URL(targetAgentId), agentRoute, activeWorkspaceSlug),+ );+ }, [currentAgentId, targetAgentId, router, agentRoute, activeWorkspaceSlug]);+const canAddTopic = !scope && !!currentAgentId && !!workingDirectory;+ const needsPlainStart = !!projectId && projectDirectories.length > 1;+ const { t: tProject } = useTranslation('project');const statusCounts = useChatStore((s) => getProjectTopicStatusCounts(children, operationSelectors.visiblyRunningTopicIds(s)),@@ -233,12 +262,33 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {{hasCollapsedUnread && <CollapsedUnreadDot count={unreadCount} />}{canAddTopic && (<span className={hasCollapsedIndicators ? styles.addTopicAction : undefined}>- <AgentDirectoryActions- agentId={currentAgentId!}- path={workingDirectory!}- topics={children}- onLegacyStart={handleAddTopic}- />+ {needsPlainStart ? (+ <>+ <AgentDirectoryActions+ hideStartAction+ agentId={currentAgentId!}+ path={workingDirectory!}+ topics={children}+ onLegacyStart={handleAddTopic}+ />+ <ActionIcon+ icon={PlusIcon}+ size={'small'}+ title={tProject('directories.start')}+ onClick={(e) => {+ e.stopPropagation();+ handleStartPlain();+ }}+ />+ </>+ ) : (+ <AgentDirectoryActions+ agentId={currentAgentId!}+ path={workingDirectory!}+ topics={children}+ onLegacyStart={handleAddTopic}+ />+ )}</span>)}</Flexbox>diff --git a/src/features/AgentSidebar/Topic/TopicListContent/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/index.tsxindex 6622b89fcb7..408808f8b86 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/index.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/index.tsx@@ -13,6 +13,7 @@ import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';import { useAgentTopicGroupMode } from '../hooks/useAgentTopicGroupMode';+import ByAgentMode from './ByAgentMode';import ByProjectMode from './ByProjectMode';import ByStatusMode from './ByStatusMode';import ByTimeMode from './ByTimeMode';@@ -57,6 +58,8 @@ const TopicListContent = memo(() => {<ByProjectMode />) : topicGroupMode === 'byStatus' ? (<ByStatusMode />+ ) : topicGroupMode === 'byAgent' ? (+ <ByAgentMode />) : (<ByTimeMode />)}diff --git a/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsxnew file mode 100644index 00000000000..8226c13d185--- /dev/null+++ b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx@@ -0,0 +1,81 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useTopicFilterDropdownMenu } from './useFilterMenu';++const scopeMock = vi.hoisted(() => ({ scope: null as null | { projectId: string } }));+const groupModeMock = vi.hoisted(() => ({ mode: 'byTime' as string }));+const preferenceMock = vi.hoisted(() => ({+ topicSortBy: 'updatedAt',+ topicIncludeCompleted: true,+ updatePreference: vi.fn(),+}));+const updateAgentModeMock = vi.hoisted(() => vi.fn());++vi.mock('./TopicListScope', () => ({+ useTopicListScope: () => scopeMock.scope,+}));++vi.mock('./hooks/useAgentTopicGroupMode', () => ({+ useAgentTopicGroupMode: () => ({+ topicGroupMode: groupModeMock.mode,+ updateTopicGroupMode: updateAgentModeMock,+ }),+}));++vi.mock('@/store/user', () => ({+ useUserStore: (selector: (state: unknown) => unknown) =>+ selector({+ updatePreference: preferenceMock.updatePreference,+ }),+}));++vi.mock('@/store/user/selectors', () => ({+ preferenceSelectors: {+ topicSortBy: () => preferenceMock.topicSortBy,+ topicIncludeCompleted: () => preferenceMock.topicIncludeCompleted,+ },+}));++const organizeLabels = (items: any[]): string[] => {+ const organize = items.find((item) => item.key === 'organize');+ return organize.children.map((child: any) => child.label);+};++describe('useTopicFilterDropdownMenu group modes', () => {+ beforeEach(() => {+ scopeMock.scope = null;+ groupModeMock.mode = 'byTime';+ vi.clearAllMocks();+ });++ /** @example A single agent's own sidebar must not offer grouping by agent. */+ it('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.flat',+ ]);+ });++ /** @example The project sidebar keeps by agent because its topics span agents. */+ it('offers by agent inside a project-scoped list', () => {+ scopeMock.scope = { projectId: 'prj-1' };++ const { result } = renderHook(() => useTopicFilterDropdownMenu());++ expect(organizeLabels(result.current())).toEqual([+ 'filter.groupMode.byStatus',+ 'filter.groupMode.byTime',+ 'filter.groupMode.byProject',+ 'filter.groupMode.byAgent',+ 'filter.groupMode.flat',+ ]);+ });+});diff --git a/src/features/AgentSidebar/Topic/useFilterMenu.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.tsxindex bcf1b6c09bb..890fd21feb4 100644--- a/src/features/AgentSidebar/Topic/useFilterMenu.tsx+++ b/src/features/AgentSidebar/Topic/useFilterMenu.tsx@@ -9,10 +9,12 @@ import { preferenceSelectors } from '@/store/user/selectors';import type { TopicGroupMode, TopicSortBy } from '@/types/topic';import { useAgentTopicGroupMode } from './hooks/useAgentTopicGroupMode';+import { useTopicListScope } from './TopicListScope';export const useTopicFilterDropdownMenu = (): (() => DropdownItem[]) => {const { t } = useTranslation('topic');const { topicGroupMode, updateTopicGroupMode } = useAgentTopicGroupMode();+ const scope = useTopicListScope();const [topicSortBy, topicIncludeCompleted, updatePreference] = useUserStore((s) => [preferenceSelectors.topicSortBy(s),@@ -21,7 +23,11 @@ export const useTopicFilterDropdownMenu = (): (() => DropdownItem[]) => {]);return useCallback(() => {- const groupModes: TopicGroupMode[] = ['byStatus', 'byTime', 'byProject', 'flat'];+ // "by agent" only exists where topics span multiple agents — the+ // project-scoped list. A single agent's own sidebar hides it.+ const groupModes: TopicGroupMode[] = scope+ ? ['byStatus', 'byTime', 'byProject', 'byAgent', 'flat']+ : ['byStatus', 'byTime', 'byProject', 'flat'];const sortByOptions: TopicSortBy[] = ['createdAt', 'updatedAt'];return [@@ -75,6 +81,7 @@ export const useTopicFilterDropdownMenu = (): (() => DropdownItem[]) => {topicIncludeCompleted,updatePreference,updateTopicGroupMode,+ scope,t,]);};diff --git a/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts b/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.tsindex 479adfc6afe..974848ade63 100644--- a/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts+++ b/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts@@ -74,4 +74,21 @@ describe('resolveAgentTopicGroupMode', () => {}),).toBe('byTime');});++ /** @example byAgent picked in a project sidebar must not leak into a single agent's own sidebar. */+ it.each([{ agentTopicGroupMode: undefined }, { agentTopicGroupMode: 'byAgent' as const }])(+ 'normalizes byAgent to byTime for unscoped agent sidebars (config %o)',+ ({ agentTopicGroupMode }) => {+ // ROOT CAUSE: the project sidebar persists byAgent into the global+ // preference and (before this fix) the per-agent config could hold it+ // too; a single agent's topics then rendered as one self-named bucket.+ // Project-scoped lists read the global mode directly and keep byAgent.+ expect(+ resolveAgentTopicGroupMode({+ agentTopicGroupMode,+ globalMode: 'byAgent',+ }),+ ).toBe('byTime');+ },+ );});diff --git a/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts b/src/features/AgentSidebar/Topic/utils/topicGroupMode.tsindex dd058924e49..9fd0b23f135 100644--- a/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts+++ b/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts@@ -33,7 +33,14 @@ export const resolveAgentTopicGroupMode = ({agentType?: HeterogeneousAgentType;globalMode: TopicGroupMode;}): TopicGroupMode => {- if (agentTopicGroupMode) return agentTopicGroupMode;+ const resolved = agentTopicGroupMode+ ? agentTopicGroupMode+ : getDefaultTopicGroupModeByAgentType(globalMode, agentType);- return getDefaultTopicGroupModeByAgentType(globalMode, agentType);+ // "by agent" is only offered in project-scoped lists. When it leaks into+ // the global preference (set from a project sidebar), a single agent's own+ // topics would render as one pointless self-named bucket — keep the+ // previous default grouping. Project-scoped lists read the global mode+ // directly and are unaffected by this fallback.+ return resolved === 'byAgent' ? 'byTime' : resolved;};diff --git a/src/features/AgentTopicManager/TopicGrid.tsx b/src/features/AgentTopicManager/TopicGrid.tsxindex 23158fbdfe4..8d43747a2f4 100644--- a/src/features/AgentTopicManager/TopicGrid.tsx+++ b/src/features/AgentTopicManager/TopicGrid.tsx@@ -56,7 +56,7 @@ const TopicGrid = memo<TopicGridProps>(({ groups, agentId, showGroupTitles, grouif (group.children.length === 0) return null;const title =groupBy === 'byProject'- ? getProjectGroupTitle(group.id, group.title, t)+ ? getProjectGroupTitle(group, t): group.title || getTimeGroupTitle(group.id, t);return (<Fragment key={group.id}>diff --git a/src/features/AgentTopicManager/TopicListView.tsx b/src/features/AgentTopicManager/TopicListView.tsxindex 53c224b832e..5d660c42fec 100644--- a/src/features/AgentTopicManager/TopicListView.tsx+++ b/src/features/AgentTopicManager/TopicListView.tsx@@ -294,7 +294,7 @@ const TopicListView = memo<TopicListViewProps>(({ groups, agentId, showGroupTitlif (group.children.length === 0) return null;const title =groupBy === 'byProject'- ? getProjectGroupTitle(group.id, group.title, t)+ ? getProjectGroupTitle(group, t): group.title || getTimeGroupTitle(group.id, t);return (<Fragment key={group.id}>diff --git a/src/features/AgentTopicManager/utils.ts b/src/features/AgentTopicManager/utils.tsindex 51edfffbfb8..2da7faac5a9 100644--- a/src/features/AgentTopicManager/utils.ts+++ b/src/features/AgentTopicManager/utils.ts@@ -1,3 +1,4 @@+import type { GroupedTopic } from '@lobechat/types';import {getTopicWorkingDirectoryEffectivePath,getTopicWorkingDirectorySourcePath,@@ -182,16 +183,20 @@ export const getTimeGroupTitle = (id: string, t: LooseT): string => {};/**- * Resolve the human-readable title for a project-bucket group ID produced by- * `groupTopicsByProject` (`project:<workingDirectory>` or `no-project`).+ * Resolve the human-readable title for a project-bucket group produced by+ * `groupTopicsByProject` (`project-id:{projectId}`, `project-directory:{id}`,+ * `project:{device}:{path}` or `no-project`).+ *+ * Merged `project-id:` groups follow the most recently active directory, so+ * the util already carries a path-derived title; when it doesn't (project+ * topics without directory metadata), derive the label from the first child's+ * source path — the same basename the project filter chips use.*/-export const getProjectGroupTitle = (- id: string,- fallback: string | undefined,- t: LooseT,-): string => {- if (id === 'no-project') return t('management.group.noProject');- // Project groups carry the trimmed working-directory name in `group.title`;- // fall back to the raw path segment if it isn't pre-populated.- return fallback ?? id.replace(/^project:/, '');+export const getProjectGroupTitle = (group: GroupedTopic, t: LooseT): string => {+ if (group.id === 'no-project') return t('management.group.noProject');+ if (group.title) return group.title;+ const withPath = group.children.find((topic) => getTopicWorkingDirectorySourcePath(topic));+ const label = withPath ? getProjectFilterLabel(withPath) : undefined;+ if (label) return label;+ return group.id.replace(/^(project-id|project-directory|project):/, '');};diff --git a/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx b/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsxindex 669693a93fd..aee5d7646b8 100644--- a/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx+++ b/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx@@ -18,11 +18,14 @@ export function AgentDirectoryActions({path,topics,onLegacyStart,+ hideStartAction = false,}: {agentId: string;path: string;topics: ChatTopic[];onLegacyStart: () => Promise<void>;+ /** Render only the binding/menu affordance; the caller provides its own start action. */+ hideStartAction?: boolean;}) {const { t } = useTranslation('project');const navigate = useWorkspaceAwareNavigate();@@ -105,22 +108,24 @@ export function AgentDirectoryActions({onClick={(e) => e.stopPropagation()}/></DropdownMenu>- <ActionIcon- icon={PlusIcon}- size="small"- title={t('directories.start')}- disabled={- pending ||- !request.hasData ||- !!request.error ||- bindings.length > 1 ||- (!!bindingId && !bindings.length)- }- onClick={(e) => {- e.stopPropagation();- void start(bindings[0]?.id);- }}- />+ {!hideStartAction && (+ <ActionIcon+ icon={PlusIcon}+ size="small"+ title={t('directories.start')}+ disabled={+ pending ||+ !request.hasData ||+ !!request.error ||+ bindings.length > 1 ||+ (!!bindingId && !bindings.length)+ }+ onClick={(e) => {+ e.stopPropagation();+ void start(bindings[0]?.id);+ }}+ />+ )}</>);}diff --git a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx b/src/features/Projects/WorkingDirectories/SidebarTopics.tsxindex 7b2bdd00b84..95e70602b4e 100644--- a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx+++ b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx@@ -1,143 +1,28 @@import { Flexbox } from '@lobehub/ui';-import {- ActionIcon,- Button,- createModal,- ModalFooter,- Select,- Text,- useModalContext,-} from '@lobehub/ui/base-ui';+import { ActionIcon, Text } from '@lobehub/ui/base-ui';import { PlusIcon } from 'lucide-react';-import { useMemo, useState } from 'react';+import { useMemo } from 'react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';import Filter from '@/features/AgentSidebar/Topic/Filter';import { useAgentTopicGroupMode } from '@/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode';import ToggleGroups from '@/features/AgentSidebar/Topic/ToggleGroups';+import ByAgentMode from '@/features/AgentSidebar/Topic/TopicListContent/ByAgentMode';import ByProjectMode from '@/features/AgentSidebar/Topic/TopicListContent/ByProjectMode';import ByStatusMode from '@/features/AgentSidebar/Topic/TopicListContent/ByStatusMode';import ByTimeMode from '@/features/AgentSidebar/Topic/TopicListContent/ByTimeMode';import FlatMode from '@/features/AgentSidebar/Topic/TopicListContent/FlatMode';import { TopicListScopeContext } from '@/features/AgentSidebar/Topic/TopicListScope';-import AssigneeAgentSelector from '@/features/AgentTasks/features/AssigneeAgentSelector';import SkeletonList from '@/features/NavPanel/components/SkeletonList';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import type { ProjectDirectory } from '@/store/projectWorkingDirectory';import {useProjectDirectories,useProjectDirectoryStore,useProjectTopics,} from '@/store/projectWorkingDirectory';-import { getProjectConversationPath } from '../Layout/navigation';-import { openAddDirectoryModal } from './AddDirectoryModal';-import { openEnvironmentModal } from './EnvironmentModal';-import { useDirectoryAgent } from './useDirectoryAgent';+import { openProjectTopicModal } from './StartDirectoryModal';-function StartDirectoryContent({- directories,- coordinatorAgentId,- projectId,- initialDirectoryId,-}: {- directories: ProjectDirectory[];- coordinatorAgentId: string;- projectId: string;- initialDirectoryId?: string;-}) {- const [directoryId, setDirectoryId] = useState(- initialDirectoryId ?? (directories.length === 1 ? directories[0].id : ''),- );- useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);- const liveDirectories = useProjectDirectories(projectId);- const locations = liveDirectories.length ? liveDirectories : directories;- const directory = locations.find((d) => d.id === directoryId);- const attachEnvironment = useProjectDirectoryStore((s) => s.attachEnvironment);- const { t } = useTranslation('project');- const { close } = useModalContext();- const navigate = useWorkspaceAwareNavigate();- const { agentId, agentName, setAgentId } = useDirectoryAgent(coordinatorAgentId);- const startTopic = useProjectDirectoryStore((s) => s.startTopic);- const createTopic = useProjectDirectoryStore((s) => s.createProjectTopic);- const [pending, setPending] = useState(false);- const [error, setError] = useState<unknown>();- const start = async () => {- setPending(true);- setError(undefined);- try {- const topic = directory- ? await startTopic(directory.id, agentId, t('directories.untitled'))- : await createTopic({ projectId, agentId, title: t('directories.untitled') });- close();- navigate(getProjectConversationPath(projectId, topic.id));- } catch (error) {- console.error('Failed to start directory work', error);- setError(error);- } finally {- setPending(false);- }- };- return (- <>- <Flexbox gap={16} padding={16}>- <Text>{t('topics.executionContext')}</Text>- <Select- aria-label={t('topics.executionContext')}- disabled={pending}- value={directoryId || '__none__'}- options={[- { value: '__none__', label: t('topics.conversationOnly') },- ...locations- .filter((d) => d.instanceId)- .map((d) => ({- value: d.id,- label: `${d.environmentName || d.name} · ${d.deviceName || d.deviceId} · ${d.path}`,- })),- ]}- onChange={(id) => setDirectoryId(id === '__none__' ? '' : (id ?? ''))}- />- {!locations.length && (- <Button- onClick={() =>- openEnvironmentModal({- onSaved: async (env) => {- await attachEnvironment(projectId, env.id);- openAddDirectoryModal(projectId, env.id);- },- })- }- >- {t('settings.addDirectory')}- </Button>- )}- <AssigneeAgentSelector- currentAgentId={agentId}- disabled={pending}- onChange={(id) => id && setAgentId(id)}- >- <span>{agentName || t('directories.coordinator')}</span>- </AssigneeAgentSelector>- {error ? (- <AsyncError- description={error instanceof Error ? error.message : undefined}- error={error}- onRetry={start}- />- ) : null}- </Flexbox>- <ModalFooter>- <Button disabled={pending} onClick={close}>- {t('cancel', { ns: 'common' })}- </Button>- <Button loading={pending} type="primary" onClick={start}>- {t('directories.start')}- </Button>- </ModalFooter>- </>- );-}export function ProjectDirectoryTopics(props: { projectId: string; coordinatorAgentId: string }) {const scope = useMemo(() => ({ projectId: props.projectId }), [props.projectId]);return (@@ -176,17 +61,11 @@ function ProjectTopicList({size="small"title={t('sidebar.newConversation')}onClick={() =>- createModal({+ openProjectTopicModal({title: t('sidebar.newConversation'),- content: (- <StartDirectoryContent- coordinatorAgentId={coordinatorAgentId}- directories={directories}- projectId={projectId}- />- ),- footer: null,- width: 520,+ coordinatorAgentId,+ directories,+ projectId,})}/>@@ -209,24 +88,11 @@ function ProjectTopicList({<ByStatusMode />) : topicGroupMode === 'byProject' ? (<ByProjectMode />+ ) : topicGroupMode === 'byAgent' ? (+ <ByAgentMode />) : (<ByTimeMode />)}</Flexbox>);}--export function openProjectTopicModal(options: {- projectId: string;- coordinatorAgentId: string;- directories: ProjectDirectory[];- initialDirectoryId?: string;- title: string;-}) {- return createModal({- title: options.title,- content: <StartDirectoryContent {...options} />,- footer: null,- width: 520,- });-}diff --git a/src/features/Projects/WorkingDirectories/StartDirectoryModal.tsx b/src/features/Projects/WorkingDirectories/StartDirectoryModal.tsxnew file mode 100644index 00000000000..7fd16c98b77--- /dev/null+++ b/src/features/Projects/WorkingDirectories/StartDirectoryModal.tsx@@ -0,0 +1,145 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import {+ Button,+ createModal,+ ModalFooter,+ Select,+ Text,+ useModalContext,+} from '@lobehub/ui/base-ui';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import AssigneeAgentSelector from '@/features/AgentTasks/features/AssigneeAgentSelector';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import {+ type ProjectDirectory,+ useProjectDirectories,+ useProjectDirectoryStore,+} from '@/store/projectWorkingDirectory';++import { getProjectConversationPath } from '../Layout/navigation';+import { openAddDirectoryModal } from './AddDirectoryModal';+import { openEnvironmentModal } from './EnvironmentModal';+import { useDirectoryAgent } from './useDirectoryAgent';++export function StartDirectoryContent({+ directories,+ coordinatorAgentId,+ projectId,+ initialDirectoryId,+}: {+ directories: ProjectDirectory[];+ coordinatorAgentId: string;+ projectId: string;+ initialDirectoryId?: string;+}) {+ const [directoryId, setDirectoryId] = useState(+ initialDirectoryId ?? (directories.length === 1 ? directories[0].id : ''),+ );+ useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);+ const liveDirectories = useProjectDirectories(projectId);+ const locations = liveDirectories.length ? liveDirectories : directories;+ const directory = locations.find((d) => d.id === directoryId);+ const attachEnvironment = useProjectDirectoryStore((s) => s.attachEnvironment);+ const { t } = useTranslation('project');+ const { close } = useModalContext();+ const navigate = useWorkspaceAwareNavigate();+ const { agentId, agentName, setAgentId } = useDirectoryAgent(coordinatorAgentId);+ const startTopic = useProjectDirectoryStore((s) => s.startTopic);+ const createTopic = useProjectDirectoryStore((s) => s.createProjectTopic);+ const [pending, setPending] = useState(false);+ const [error, setError] = useState<unknown>();+ const start = async () => {+ setPending(true);+ setError(undefined);+ try {+ const topic = directory+ ? await startTopic(directory.id, agentId, t('directories.untitled'))+ : await createTopic({ projectId, agentId, title: t('directories.untitled') });+ close();+ navigate(getProjectConversationPath(projectId, topic.id));+ } catch (error) {+ console.error('Failed to start directory work', error);+ setError(error);+ } finally {+ setPending(false);+ }+ };+ return (+ <>+ <Flexbox gap={16} padding={16}>+ <Text>{t('topics.executionContext')}</Text>+ <Select+ aria-label={t('topics.executionContext')}+ disabled={pending}+ value={directoryId || '__none__'}+ options={[+ { value: '__none__', label: t('topics.conversationOnly') },+ ...locations+ .filter((d) => d.instanceId)+ .map((d) => ({+ value: d.id,+ label: `${d.environmentName || d.name} · ${d.deviceName || d.deviceId} · ${d.path}`,+ })),+ ]}+ onChange={(id) => setDirectoryId(id === '__none__' ? '' : (id ?? ''))}+ />+ {!locations.length && (+ <Button+ onClick={() =>+ openEnvironmentModal({+ onSaved: async (env) => {+ await attachEnvironment(projectId, env.id);+ openAddDirectoryModal(projectId, env.id);+ },+ })+ }+ >+ {t('settings.addDirectory')}+ </Button>+ )}+ <AssigneeAgentSelector+ currentAgentId={agentId}+ disabled={pending}+ onChange={(id) => id && setAgentId(id)}+ >+ <span>{agentName || t('directories.coordinator')}</span>+ </AssigneeAgentSelector>+ {error ? (+ <AsyncError+ description={error instanceof Error ? error.message : undefined}+ error={error}+ onRetry={start}+ />+ ) : null}+ </Flexbox>+ <ModalFooter>+ <Button disabled={pending} onClick={close}>+ {t('cancel', { ns: 'common' })}+ </Button>+ <Button loading={pending} type="primary" onClick={start}>+ {t('directories.start')}+ </Button>+ </ModalFooter>+ </>+ );+}++export function openProjectTopicModal(options: {+ projectId: string;+ coordinatorAgentId: string;+ directories: ProjectDirectory[];+ initialDirectoryId?: string;+ title: string;+}) {+ return createModal({+ title: options.title,+ content: <StartDirectoryContent {...options} />,+ footer: null,+ width: 520,+ });+}diff --git a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsxindex a3ac04ca507..c7c775bedca 100644--- a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx+++ b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx@@ -18,7 +18,7 @@ import {import { openAddDirectoryModal } from './AddDirectoryModal';import { openBindDirectoryModal } from './BindDirectoryModal';-import { openProjectTopicModal } from './SidebarTopics';+import { openProjectTopicModal } from './StartDirectoryModal';export function WorkingDirectorySettings({ projectId }: { projectId: string }) {const { t } = useTranslation('project');diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.test.ts b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.test.tsnew file mode 100644index 00000000000..7115369826e--- /dev/null+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';++import { resolveGroupSidebarMode } from './resolveGroupSidebarMode';++describe('resolveGroupSidebarMode', () => {+ /** @example A byAgent preference leaked from a project sidebar must not render as time-bucket translation keys in group chats. */+ it('falls back to byTime for byAgent, which the group sidebar cannot render', () => {+ // ROOT CAUSE: the project sidebar persists byAgent into the global+ // preference, and the group-chat sidebar renders every non-flat mode+ // through its time renderer, whose headers format unknown group ids as+ // `groupTitle.byTime.*` translation keys.+ expect(resolveGroupSidebarMode('byAgent')).toBe('byTime');+ });++ it('keeps every mode the group sidebar menu offers', () => {+ expect(resolveGroupSidebarMode('byTime')).toBe('byTime');+ expect(resolveGroupSidebarMode('byProject')).toBe('byProject');+ expect(resolveGroupSidebarMode('byStatus')).toBe('byStatus');+ expect(resolveGroupSidebarMode('flat')).toBe('flat');+ });+});diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsxindex fce6f8bae4c..3871153947f 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx@@ -18,6 +18,7 @@ import { useUserStore } from '@/store/user';import { preferenceSelectors } from '@/store/user/selectors';import GroupItem from './GroupItem';+import { resolveGroupSidebarMode } from './resolveGroupSidebarMode';const ByTimeMode = memo(() => {const { t } = useTranslation('topic');@@ -25,6 +26,7 @@ const ByTimeMode = memo(() => {const topicSortBy = useUserStore(preferenceSelectors.topicSortBy);const topicGroupMode = useUserStore(preferenceSelectors.topicGroupMode);const topicIncludeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);+ const groupMode = resolveGroupSidebarMode(topicGroupMode);const [hasMore, isExpandingPageSize, openAllTopicsDrawer] = useChatStore((s) => [topicSelectors.hasMoreTopicsForSidebar(s),@@ -38,15 +40,15 @@ const ByTimeMode = memo(() => {topicSelectors.groupedTopicsForSidebar(topicPageSize,topicSortBy,- topicGroupMode,+ groupMode,topicIncludeCompleted,),- [topicPageSize, topicSortBy, topicGroupMode, topicIncludeCompleted],+ [topicPageSize, topicSortBy, groupMode, topicIncludeCompleted],);const groupTopics = useChatStore(groupSelector, isEqual);const groupIds = useMemo(() => groupTopics.map((group) => group.id), [groupTopics]);- const { expandedKeys, setExpandedKeys } = useTopicGroupCollapse(topicGroupMode, groupIds);+ const { expandedKeys, setExpandedKeys } = useTopicGroupCollapse(groupMode, groupIds);return (<Flexbox gap={2}>diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/resolveGroupSidebarMode.ts b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/resolveGroupSidebarMode.tsnew file mode 100644index 00000000000..921f678e5f9--- /dev/null+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/resolveGroupSidebarMode.ts@@ -0,0 +1,12 @@+import type { TopicGroupMode } from '@/types/topic';++/**+ * The group-chat sidebar renders every non-flat preference through its time+ * renderer, but its menu never offers `byAgent` and group topics carry no+ * per-row agent attribution. When a project-scoped sidebar persists `byAgent`+ * into the global preference, grouping by it here would emit `agent:*` buckets+ * that this surface's headers format as time-bucket translation keys — so the+ * mode falls back to the default time grouping.+ */+export const resolveGroupSidebarMode = (mode: TopicGroupMode): TopicGroupMode =>+ mode === 'byAgent' ? 'byTime' : mode;diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.tsindex 0d8d228a977..5bcd0452fec 100644--- a/src/store/chat/slices/topic/selectors.ts+++ b/src/store/chat/slices/topic/selectors.ts@@ -14,6 +14,7 @@ import {} from '@/types/topic';import {getTopicSortTime,+ groupTopicsByAgent,groupTopicsByProject,groupTopicsByStatus,groupTopicsByTime,@@ -373,6 +374,12 @@ const getGroupFn = (title: t(`groupTitle.byStatus.${group.id}` as any, { ns: 'topic' }),}));}+ if (groupMode === 'byAgent') {+ // Agent names come from row metadata (project feeds join them per topic);+ // buckets without attribution stay title-less and the group item names+ // them from its agent context.+ return (topics: ChatTopic[]) => groupTopicsByAgent(topics, field);+ }return sortBy === 'updatedAt' ? groupTopicsByUpdatedTime : groupTopicsByTime;};