🤯 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): add group-by-status mode to topic sidebar (#15366)
Arvin Xuc8096590c4ac
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.jsonindex 9469a52f110..b83fa293169 100644--- a/locales/en-US/topic.json+++ b/locales/en-US/topic.json@@ -29,6 +29,7 @@"favorite": "Favorite","filter.filter": "Filter","filter.groupMode.byProject": "By project",+ "filter.groupMode.byStatus": "By status","filter.groupMode.byTime": "By time","filter.groupMode.flat": "Flat","filter.organize": "Organize",@@ -37,6 +38,13 @@"filter.sortBy.createdAt": "Created time","filter.sortBy.updatedAt": "Updated time","groupTitle.byProject.noProject": "No directory",+ "groupTitle.byStatus.active": "Active",+ "groupTitle.byStatus.archived": "Archived",+ "groupTitle.byStatus.completed": "Completed",+ "groupTitle.byStatus.failed": "Failed",+ "groupTitle.byStatus.paused": "Paused",+ "groupTitle.byStatus.running": "Running",+ "groupTitle.byStatus.waitingForHuman": "Awaiting input","groupTitle.byTime.month": "This Month","groupTitle.byTime.today": "Today","groupTitle.byTime.week": "This Week",diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.jsonindex 3eac5aaf8e4..619a2acf2a3 100644--- a/locales/zh-CN/topic.json+++ b/locales/zh-CN/topic.json@@ -29,6 +29,7 @@"favorite": "收藏","filter.filter": "筛选","filter.groupMode.byProject": "按项目",+ "filter.groupMode.byStatus": "按状态","filter.groupMode.byTime": "按时间阶段","filter.groupMode.flat": "平铺","filter.organize": "整理",@@ -37,6 +38,13 @@"filter.sortBy.createdAt": "按创建时间","filter.sortBy.updatedAt": "按更新时间","groupTitle.byProject.noProject": "无目录",+ "groupTitle.byStatus.active": "活跃",+ "groupTitle.byStatus.archived": "已归档",+ "groupTitle.byStatus.completed": "已完成",+ "groupTitle.byStatus.failed": "已失败",+ "groupTitle.byStatus.paused": "已暂停",+ "groupTitle.byStatus.running": "进行中",+ "groupTitle.byStatus.waitingForHuman": "等待处理","groupTitle.byTime.month": "本月","groupTitle.byTime.today": "今天","groupTitle.byTime.week": "本周",diff --git a/packages/database/src/models/__tests__/topics/topic.query.test.ts b/packages/database/src/models/__tests__/topics/topic.query.test.tsindex e66c77e94cb..72657c51899 100644--- a/packages/database/src/models/__tests__/topics/topic.query.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.query.test.ts@@ -53,6 +53,79 @@ describe('TopicModel - Query', () => {expect(result.items[2].id).toBe('4');});+ it('should order by status priority when sortBy is "status"', async () => {+ await serverDB.insert(topics).values([+ // favorite floats to the top regardless of its (lower-priority) status+ {+ favorite: true,+ id: 'fav',+ sessionId,+ status: 'completed',+ updatedAt: new Date('2023-01-01'),+ userId,+ },+ // null status is treated as `active` (rank 2)+ { id: 'active', sessionId, updatedAt: new Date('2023-09-01'), userId },+ {+ id: 'running-old',+ sessionId,+ status: 'running',+ updatedAt: new Date('2023-02-01'),+ userId,+ },+ {+ id: 'running-new',+ sessionId,+ status: 'running',+ updatedAt: new Date('2023-08-01'),+ userId,+ },+ {+ id: 'waiting',+ sessionId,+ status: 'waitingForHuman',+ updatedAt: new Date('2023-03-01'),+ userId,+ },+ {+ id: 'completed',+ sessionId,+ status: 'completed',+ updatedAt: new Date('2023-07-01'),+ userId,+ },+ ]);++ const result = await topicModel.query({ containerId: sessionId, sortBy: 'status' });++ expect(result.items.map((t) => t.id)).toEqual([+ 'fav', // favorite, rank-independent+ 'waiting', // waitingForHuman = 0+ 'running-new', // running = 1, newer first within the bucket+ 'running-old',+ 'active', // null status → active = 2+ 'completed', // completed = 5+ ]);+ });++ it('should keep updatedAt ordering by default (no sortBy)', async () => {+ await serverDB.insert(topics).values([+ {+ id: 'waiting',+ sessionId,+ status: 'waitingForHuman',+ updatedAt: new Date('2023-01-01'),+ userId,+ },+ { id: 'active', sessionId, updatedAt: new Date('2023-05-01'), userId },+ ]);++ const result = await topicModel.query({ containerId: sessionId });++ // Without status sort, most-recently-updated wins even if lower priority+ expect(result.items.map((t) => t.id)).toEqual(['active', 'waiting']);+ });+it('should query topics with pagination', async () => {await serverDB.insert(topics).values([{ id: '1', userId, updatedAt: new Date('2023-01-01') },diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex fc187f00154..a1433ed1712 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -2,6 +2,7 @@ import type {ChatTopicMetadata,ChatTopicStatus,DBMessageItem,+ TopicQuerySortBy,TopicRankItem,} from '@lobechat/types';import type { TimingSink } from '@lobechat/utils';@@ -84,6 +85,12 @@ interface QueryTopicParams {*/isInbox?: boolean;pageSize?: number;+ /**+ * Server-side ordering. Defaults to `updatedAt`. `status` orders by status+ * priority (see `STATUS_SORT_RANK`) so the sidebar "group by status" mode+ * keeps high-priority topics on the first page.+ */+ sortBy?: TopicQuerySortBy;timing?: ModelTimingContext;/*** Include only topics matching the given trigger types (positive filter)@@ -107,6 +114,27 @@ export interface ListTopicsForMemoryExtractorCursor {id: string;}+// Status priority for the sidebar "group by status" ordering. Lower rank =+// higher in the list. A NULL / unknown status falls through to `active` (2),+// matching the client which treats a missing status as active. Keep this in+// sync with `STATUS_GROUP_ORDER` in `@lobechat/utils` (client-side bucketing).+const STATUS_SORT_RANK = sql`CASE ${topics.status}+ WHEN 'waitingForHuman' THEN 0+ WHEN 'running' THEN 1+ WHEN 'active' THEN 2+ WHEN 'paused' THEN 3+ WHEN 'failed' THEN 4+ WHEN 'completed' THEN 5+ WHEN 'archived' THEN 6+ ELSE 2 END`;++// Favorites always float to the top; the rest are ordered by the requested+// strategy. `status` adds the priority bucket before the recency tiebreaker.+const buildTopicOrderBy = (sortBy?: TopicQuerySortBy): SQL[] =>+ sortBy === 'status'+ ? [desc(topics.favorite), asc(STATUS_SORT_RANK), desc(topics.updatedAt)]+ : [desc(topics.favorite), desc(topics.updatedAt)];+export class TopicModel {private userId: string;private db: LobeChatDatabase;@@ -127,10 +155,12 @@ export class TopicModel {pageSize = 9999,groupId,isInbox,+ sortBy,timing,triggers,withDetails = false,}: QueryTopicParams = {}) => {+ const orderBy = buildTopicOrderBy(sortBy);const queryStartedAt = Date.now();logTiming(timing, 'db.topic.query:start', {current,@@ -233,7 +263,7 @@ export class TopicModel {} as any).from(topics).where(whereCondition)- .orderBy(desc(topics.favorite), desc(topics.updatedAt))+ .orderBy(...orderBy).limit(pageSize).offset(offset),{ current, pageSize },@@ -330,7 +360,7 @@ export class TopicModel {} as any).from(topics).where(agentWhere)- .orderBy(desc(topics.favorite), desc(topics.updatedAt))+ .orderBy(...orderBy).limit(pageSize).offset(offset),{ current, hasAssociatedSessionId: !!associatedSessionId, isInbox: !!isInbox, pageSize },@@ -388,9 +418,7 @@ export class TopicModel {} as any).from(topics).where(whereCondition)- // In boolean sorting, false is considered "smaller" than true.- // So here we use desc to ensure that topics with favorite as true are in front.- .orderBy(desc(topics.favorite), desc(topics.updatedAt))+ .orderBy(...orderBy).limit(pageSize).offset(offset),{ current, pageSize },diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.tsindex 052a690bfd7..09ab363d262 100644--- a/packages/types/src/agent/chatConfig.ts+++ b/packages/types/src/agent/chatConfig.ts@@ -250,7 +250,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']).optional(),+ topicGroupMode: z.enum(['byTime', 'byProject', 'flat', 'byStatus']).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 6092e795aa4..f9b36978977 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -11,9 +11,20 @@ export type TimeGroupId =| `${number}-${string}`| `${number}`;-export type TopicGroupMode = 'byTime' | 'byProject' | 'flat';+export type TopicGroupMode = 'byTime' | 'byProject' | 'flat' | 'byStatus';export type TopicSortBy = 'createdAt' | 'updatedAt';+/**+ * Server-side ordering for the topic list query.+ * - `updatedAt` (default): favorites first, then most-recently-updated.+ * - `status`: favorites first, then by status priority+ * (waitingForHuman → running → active → paused → failed → completed →+ * archived), then most-recently-updated within each status. Backs the+ * sidebar "group by status" mode so the highest-priority topics stay on the+ * first page regardless of pagination.+ */+export type TopicQuerySortBy = 'updatedAt' | 'status';+export interface GroupedTopic {children: ChatTopic[];id: string;@@ -280,6 +291,11 @@ export interface QueryTopicParams {*/isInbox?: boolean;pageSize?: number;+ /**+ * Server-side ordering. Defaults to `updatedAt`. Use `status` to back the+ * sidebar "group by status" mode so high-priority topics stay on page one.+ */+ sortBy?: TopicQuerySortBy;/*** Include only topics matching the given trigger types (positive filter)*/diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 2bbbf366a6c..46130f72acf 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -161,7 +161,7 @@ export const UserPreferenceSchema = zhideSyncAlert: z.boolean().optional(),lab: UserLabSchema.optional(),telemetry: z.boolean().nullable(),- topicGroupMode: z.enum(['byTime', 'byProject', 'flat']).optional(),+ topicGroupMode: z.enum(['byTime', 'byProject', 'flat', 'byStatus']).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 4e603fcaac2..606f1b8f40e 100644--- a/packages/utils/src/client/topic.test.ts+++ b/packages/utils/src/client/topic.test.ts@@ -2,7 +2,7 @@ import type { ChatTopic } from '@lobechat/types';import dayjs from 'dayjs';import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';-import { groupTopicsByTime, groupTopicsByUpdatedTime } from './topic';+import { groupTopicsByStatus, groupTopicsByTime, groupTopicsByUpdatedTime } from './topic';// Mock current date to ensure consistent test resultsconst NOW = '2024-01-15T12:00:00Z';@@ -214,3 +214,85 @@ describe('groupTopicsByUpdatedTime', () => {expect(byUpdated[0].id).toBe('yesterday');});});++describe('groupTopicsByStatus', () => {+ const createTopic = (+ id: string,+ status: ChatTopic['status'],+ updatedAt: number = 0,+ ): ChatTopic => ({+ id,+ title: id,+ createdAt: updatedAt,+ status,+ updatedAt,+ });++ it('should return empty array for empty input', () => {+ expect(groupTopicsByStatus([], 'updatedAt')).toEqual([]);+ });++ it('should order groups by fixed priority: waitingForHuman, running, then active', () => {+ const topics = [+ createTopic('a', 'active'),+ createTopic('r', 'running'),+ createTopic('w', 'waitingForHuman'),+ ];++ const result = groupTopicsByStatus(topics, 'updatedAt');++ expect(result.map((g) => g.id)).toEqual(['waitingForHuman', 'running', 'active']);+ });++ it('should bucket topics without a status as active', () => {+ const topics = [createTopic('1', undefined), createTopic('2', null)];++ const result = groupTopicsByStatus(topics, 'updatedAt');++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe('active');+ expect(result[0].children.map((t) => t.id)).toEqual(['1', '2']);+ });++ it('should only emit non-empty groups and keep the remaining states below the priority ones', () => {+ const topics = [+ createTopic('c', 'completed'),+ createTopic('w', 'waitingForHuman'),+ createTopic('p', 'paused'),+ ];++ const result = groupTopicsByStatus(topics, 'updatedAt');++ expect(result.map((g) => g.id)).toEqual(['waitingForHuman', 'paused', 'completed']);+ });++ it('should sort topics inside a group by the chosen field desc', () => {+ const topics = [+ createTopic('old', 'running', 1),+ createTopic('new', 'running', 100),+ createTopic('mid', 'running', 50),+ ];++ const result = groupTopicsByStatus(topics, 'updatedAt');++ expect(result[0].children.map((t) => t.id)).toEqual(['new', 'mid', 'old']);+ });++ it('should bucket a topic that is streaming on this client (loadingTopicIds) as running', () => {+ const topics = [createTopic('loading', 'active'), createTopic('idle', 'active')];++ const result = groupTopicsByStatus(topics, 'updatedAt', new Set(['loading']));++ expect(result.map((g) => g.id)).toEqual(['running', 'active']);+ expect(result[0].children.map((t) => t.id)).toEqual(['loading']);+ expect(result[1].children.map((t) => t.id)).toEqual(['idle']);+ });++ it('should keep a loading topic in waitingForHuman (it outranks the running overlay)', () => {+ const topics = [createTopic('waiting', 'waitingForHuman')];++ const result = groupTopicsByStatus(topics, 'updatedAt', new Set(['waiting']));++ expect(result.map((g) => g.id)).toEqual(['waitingForHuman']);+ });+});diff --git a/packages/utils/src/client/topic.ts b/packages/utils/src/client/topic.tsindex 36ac2b8be63..dba31c648da 100644--- a/packages/utils/src/client/topic.ts+++ b/packages/utils/src/client/topic.ts@@ -1,4 +1,4 @@-import type { ChatTopic, GroupedTopic, TimeGroupId } from '@lobechat/types';+import type { ChatTopic, ChatTopicStatus, GroupedTopic, TimeGroupId } from '@lobechat/types';import dayjs from 'dayjs';import isToday from 'dayjs/plugin/isToday';import isYesterday from 'dayjs/plugin/isYesterday';@@ -150,3 +150,71 @@ export const groupTopicsByProject = (return bTime - aTime;});};++// Status-based grouping. Fixed priority order: topics awaiting a human come+// first, then running, then active; the remaining states fall below. Topics+// without a status are treated as `active`. The group `id` is the raw status+// value so the sidebar can resolve its title via `groupTitle.byStatus.<id>`.+//+// The server orders the query by the same priority (see `STATUS_SORT_RANK` in+// `@lobechat/database` topic model) so the right page is fetched; this only+// re-buckets that already-ordered page for display. Keep the two in sync. The+// one client-only nuance is `loadingTopicIds` (a topic streaming right now),+// which the server can't know about — see `resolveStatusBucket`.+export const STATUS_GROUP_ORDER: ChatTopicStatus[] = [+ 'waitingForHuman',+ 'running',+ 'active',+ 'paused',+ 'failed',+ 'completed',+ 'archived',+];++/**+ * Resolve the bucket a topic belongs to. Mirrors the icon precedence in the+ * sidebar `TopicItem`: `waitingForHuman` wins, then a topic that is actively+ * streaming on this client (`loadingTopicIds`, a transient client-only state+ * the server can't see) or persisted as `running` lands in `running`, then the+ * persisted status, defaulting to `active`.+ */+const resolveStatusBucket = (+ topic: ChatTopic,+ loadingTopicIds?: ReadonlySet<string>,+): ChatTopicStatus => {+ if (topic.status === 'waitingForHuman') return 'waitingForHuman';+ if (loadingTopicIds?.has(topic.id) || topic.status === 'running') return 'running';+ const status = topic.status ?? 'active';+ return STATUS_GROUP_ORDER.includes(status) ? status : 'active';+};++export const groupTopicsByStatus = (+ topics: ChatTopic[],+ field: 'createdAt' | 'updatedAt',+ loadingTopicIds?: ReadonlySet<string>,+): GroupedTopic[] => {+ if (!topics.length) return [];++ const groupsMap = new Map<ChatTopicStatus, ChatTopic[]>();++ for (const topic of topics) {+ const id = resolveStatusBucket(topic, loadingTopicIds);+ const existing = groupsMap.get(id);+ if (existing) {+ existing.push(topic);+ } else {+ groupsMap.set(id, [topic]);+ }+ }++ // Sort topics inside each group by chosen field desc+ for (const children of groupsMap.values()) {+ children.sort((a, b) => b[field] - a[field]);+ }++ // Emit only non-empty groups, in the fixed priority order+ return STATUS_GROUP_ORDER.filter((status) => groupsMap.has(status)).map((status) => ({+ children: groupsMap.get(status)!,+ id: status,+ }));+};diff --git a/src/hooks/useFetchChatTopics.ts b/src/hooks/useFetchChatTopics.tsindex 6da7919ae16..16bad8c2b71 100644--- a/src/hooks/useFetchChatTopics.ts+++ b/src/hooks/useFetchChatTopics.ts@@ -1,5 +1,7 @@import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';import { useFetchTopics } from '@/hooks/useFetchTopics';+import { useAgentTopicGroupMode } from '@/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useAgentTopicGroupMode';+import { useChatStore } from '@/store/chat';import { useUserStore } from '@/store/user';import { preferenceSelectors } from '@/store/user/selectors';@@ -18,9 +20,19 @@ const EXCLUDE_STATUSES_COMPLETED = ['completed'];*/export const useFetchChatTopics = () => {const includeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);+ const activeGroupId = useChatStore((s) => s.activeGroupId);+ const { topicGroupMode } = useAgentTopicGroupMode();++ // "Group by status" ordering is resolved server-side so the highest-priority+ // topics (awaiting human → running → active) stay on the first page even when+ // the list is paginated — client-side grouping over a partial page is exactly+ // what made the previous approach flaky. Only the agent sidebar supports it;+ // group sessions keep the default updatedAt ordering.+ const sortBy = !activeGroupId && topicGroupMode === 'byStatus' ? 'status' : undefined;return useFetchTopics({excludeStatuses: includeCompleted ? undefined : EXCLUDE_STATUSES_COMPLETED,excludeTriggers: MAIN_SIDEBAR_EXCLUDE_TRIGGERS,+ sortBy,});};diff --git a/src/hooks/useFetchTopics.ts b/src/hooks/useFetchTopics.tsindex 7b9cc995c34..537d0b004b4 100644--- a/src/hooks/useFetchTopics.ts+++ b/src/hooks/useFetchTopics.ts@@ -1,3 +1,5 @@+import type { TopicQuerySortBy } from '@lobechat/types';+import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -10,6 +12,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';export const useFetchTopics = (options?: {excludeStatuses?: string[];excludeTriggers?: string[];+ sortBy?: TopicQuerySortBy;}) => {const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);const [activeAgentId, activeGroupId, useFetchTopicsHook] = useChatStore((s) => [@@ -32,6 +35,7 @@ export const useFetchTopics = (options?: {groupId: activeGroupId,isInbox: activeGroupId ? false : isInbox,pageSize: topicPageSize,+ ...(options?.sortBy ? { sortBy: options.sortBy } : {}),});return {diff --git a/src/locales/default/topic.ts b/src/locales/default/topic.tsindex 795bd423278..6def1e0ff25 100644--- a/src/locales/default/topic.ts+++ b/src/locales/default/topic.ts@@ -30,6 +30,7 @@ export default {'favorite': 'Favorite','filter.filter': 'Filter','filter.groupMode.byProject': 'By project',+ 'filter.groupMode.byStatus': 'By status','filter.groupMode.byTime': 'By time','filter.groupMode.flat': 'Flat','filter.organize': 'Organize',@@ -38,6 +39,13 @@ export default {'filter.sortBy.createdAt': 'Created time','filter.sortBy.updatedAt': 'Updated time','groupTitle.byProject.noProject': 'No directory',+ 'groupTitle.byStatus.active': 'Active',+ 'groupTitle.byStatus.archived': 'Archived',+ 'groupTitle.byStatus.completed': 'Completed',+ 'groupTitle.byStatus.failed': 'Failed',+ 'groupTitle.byStatus.paused': 'Paused',+ 'groupTitle.byStatus.running': 'Running',+ 'groupTitle.byStatus.waitingForHuman': 'Awaiting input','groupTitle.byTime.month': 'This Month','groupTitle.byTime.today': 'Today','groupTitle.byTime.week': 'This Week',diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsxnew file mode 100644index 00000000000..af46b2e8468--- /dev/null+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx@@ -0,0 +1,73 @@+import { AccordionItem, Center, Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from 'antd-style';+import {+ Archive,+ CheckCircle2,+ CircleDot,+ Hand,+ Loader,+ type LucideIcon,+ PauseCircle,+ Star,+ XCircle,+} from 'lucide-react';+import { memo } from 'react';++import TopicItem from '../../List/Item';+import { type GroupItemComponentProps } from '../GroupedAccordion';++// Map each status-group id to its icon + color, mirroring the per-topic status+// glyphs in `List/Item`. `favorite` is the synthetic group split out by+// `buildGroupedTopics`, so it gets a star.+const STATUS_ICON: Record<string, { color: string; icon: LucideIcon }> = {+ active: { color: cssVar.colorTextTertiary, icon: CircleDot },+ archived: { color: cssVar.colorTextDescription, icon: Archive },+ completed: { color: cssVar.colorTextDescription, icon: CheckCircle2 },+ failed: { color: cssVar.colorError, icon: XCircle },+ favorite: { color: cssVar.colorWarning, icon: Star },+ paused: { color: cssVar.colorTextDescription, icon: PauseCircle },+ running: { color: cssVar.colorWarning, icon: Loader },+ waitingForHuman: { color: cssVar.colorInfo, icon: Hand },+};++const GroupItem = memo<GroupItemComponentProps>(({ group, activeTopicId, activeThreadId }) => {+ const { id, title, children } = group;+ const statusIcon = STATUS_ICON[id];++ return (+ <AccordionItem+ itemKey={id}+ paddingBlock={4}+ paddingInline={'8px 4px'}+ title={+ <Flexbox horizontal align="center" gap={6} height={24} style={{ overflow: 'hidden' }}>+ {statusIcon && (+ <Center flex={'none'} height={16} width={16}>+ <Icon color={statusIcon.color} icon={statusIcon.icon} size={{ size: 13 }} />+ </Center>+ )}+ <Text ellipsis fontSize={12} style={{ flex: 1 }} type={'secondary'} weight={500}>+ {title}+ </Text>+ </Flexbox>+ }+ >+ <Flexbox gap={1} paddingBlock={1}>+ {children.map((topic) => (+ <TopicItem+ active={activeTopicId === topic.id}+ fav={topic.favorite}+ id={topic.id}+ key={topic.id}+ metadata={topic.metadata}+ status={topic.status}+ threadId={activeThreadId}+ title={topic.title}+ />+ ))}+ </Flexbox>+ </AccordionItem>+ );+});++export default GroupItem;diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByStatusMode/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByStatusMode/index.tsxnew file mode 100644index 00000000000..631f9566153--- /dev/null+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByStatusMode/index.tsx@@ -0,0 +1,12 @@+'use client';++import { memo } from 'react';++import GroupedAccordion from '../GroupedAccordion';+import GroupItem from './GroupItem';++const ByStatusMode = memo(() => <GroupedAccordion GroupItem={GroupItem} />);++ByStatusMode.displayName = 'ByStatusMode';++export default ByStatusMode;diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsxindex cd3ae59ea5b..4b62faed541 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx@@ -13,6 +13,7 @@ import { topicSelectors } from '@/store/chat/selectors';import { useAgentTopicGroupMode } from '../hooks/useAgentTopicGroupMode';import ByProjectMode from './ByProjectMode';+import ByStatusMode from './ByStatusMode';import ByTimeMode from './ByTimeMode';import FlatMode from './FlatMode';import SearchResult from './SearchResult';@@ -50,6 +51,8 @@ const TopicListContent = memo(() => {<FlatMode />) : topicGroupMode === 'byProject' ? (<ByProjectMode />+ ) : topicGroupMode === 'byStatus' ? (+ <ByStatusMode />) : (<ByTimeMode />)}diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/useFilterMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/useFilterMenu.tsxindex bd1356d2f7b..765884b921b 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/useFilterMenu.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/useFilterMenu.tsx@@ -21,7 +21,7 @@ export const useTopicFilterDropdownMenu = (): DropdownItem[] => {]);return useMemo(() => {- const groupModes: TopicGroupMode[] = ['byTime', 'byProject', 'flat'];+ const groupModes: TopicGroupMode[] = ['byStatus', 'byTime', 'byProject', 'flat'];const sortByOptions: TopicSortBy[] = ['createdAt', 'updatedAt'];return [diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.tsindex bb3f23e6384..4a212cf726a 100644--- a/src/server/routers/lambda/topic.ts+++ b/src/server/routers/lambda/topic.ts@@ -244,6 +244,11 @@ export const topicRouter = router({isInbox: z.boolean().optional(),pageSize: z.number().max(100).optional(),sessionId: z.string().nullable().optional(),+ /**+ * Server-side ordering. Defaults to `updatedAt`; `status` orders by+ * status priority for the sidebar "group by status" mode.+ */+ sortBy: z.enum(['updatedAt', 'status']).optional(),triggers: z.array(z.string()).optional(),/*** When true, returns extra card-detail columns (firstUserMessage,diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex cd896d59a7b..96e187f6ce9 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -50,6 +50,7 @@ export class TopicService {includeTriggers: params.includeTriggers,isInbox: params.isInbox,pageSize: params.pageSize,+ sortBy: params.sortBy,triggers: params.triggers,withDetails: params.withDetails,}) as any;diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex f59138a8ef8..40720add779 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -20,7 +20,12 @@ import { useGlobalStore } from '@/store/global';import { type StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import { systemAgentSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';-import { type ChatTopic, type ChatTopicStatus, type CreateTopicParams } from '@/types/topic';+import {+ type ChatTopic,+ type ChatTopicStatus,+ type CreateTopicParams,+ type TopicQuerySortBy,+} from '@/types/topic';import { merge } from '@/utils/merge';import { setNamespace } from '@/utils/storeDebug';@@ -375,6 +380,7 @@ export class ChatTopicActionImpl {groupId,pageSize: customPageSize,isInbox,+ sortBy,withDetails,}: {agentId?: string;@@ -383,6 +389,7 @@ export class ChatTopicActionImpl {groupId?: string;isInbox?: boolean;pageSize?: number;+ sortBy?: TopicQuerySortBy;withDetails?: boolean;} = {},): SWRResponse<{ items: ChatTopic[]; total: number }> => {@@ -405,6 +412,7 @@ export class ChatTopicActionImpl {pageSize,...(effectiveExcludeTriggers ? { excludeTriggers: effectiveExcludeTriggers } : {}),...(effectiveExcludeStatuses ? { excludeStatuses: effectiveExcludeStatuses } : {}),+ ...(sortBy ? { sortBy } : {}),...(withDetails ? { withDetails: true } : {}),},]@@ -433,6 +441,7 @@ export class ChatTopicActionImpl {groupId,isInbox,pageSize,+ sortBy,withDetails,});diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.tsindex 2ad77e31562..6d53f43b1ca 100644--- a/src/store/chat/slices/topic/selectors.ts+++ b/src/store/chat/slices/topic/selectors.ts@@ -10,6 +10,7 @@ import {} from '@/types/topic';import {groupTopicsByProject,+ groupTopicsByStatus,groupTopicsByTime,groupTopicsByUpdatedTime,} from '@/utils/client/topic';@@ -117,9 +118,13 @@ const displayTopicsForSidebar =return [...sortTopics(favTopics, sortBy), ...sortTopics(rest, sortBy)].slice(0, pageSize);};-const getGroupFn = (groupMode: TopicGroupMode, sortBy: TopicSortBy) => {+const getGroupFn = (+ groupMode: TopicGroupMode,+ sortBy: TopicSortBy,+ loadingTopicIds?: ReadonlySet<string>,+) => {+ const field: 'createdAt' | 'updatedAt' = sortBy === 'createdAt' ? 'createdAt' : 'updatedAt';if (groupMode === 'byProject') {- const field: 'createdAt' | 'updatedAt' = sortBy === 'createdAt' ? 'createdAt' : 'updatedAt';return (topics: ChatTopic[]) =>groupTopicsByProject(topics, field).map((group) =>group.id === 'no-project'@@ -127,6 +132,13 @@ const getGroupFn = (groupMode: TopicGroupMode, sortBy: TopicSortBy) => {: group,);}+ if (groupMode === 'byStatus') {+ return (topics: ChatTopic[]) =>+ groupTopicsByStatus(topics, field, loadingTopicIds).map((group) => ({+ ...group,+ title: t(`groupTitle.byStatus.${group.id}` as any, { ns: 'topic' }),+ }));+ }return sortBy === 'updatedAt' ? groupTopicsByUpdatedTime : groupTopicsByTime;};@@ -165,7 +177,10 @@ const groupedTopicsForSidebar =(s: ChatStoreState): GroupedTopic[] => {const limitedTopics = displayTopicsForSidebar(pageSize, sortBy)(s);if (!limitedTopics) return [];- return buildGroupedTopics(limitedTopics, getGroupFn(groupMode, sortBy));+ // Topics actively streaming on this client surface under "running" even+ // though their persisted status is still active — see resolveStatusBucket.+ const loadingTopicIds = groupMode === 'byStatus' ? new Set(s.topicLoadingIds) : undefined;+ return buildGroupedTopics(limitedTopics, getGroupFn(groupMode, sortBy, loadingTopicIds));};const hasMoreTopics = (s: ChatStoreState): boolean => {