Skip to content

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

✨ feat(topics): add per-agent topic management page (#15207)

Arvin Xu5cd02b937b06
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index 58ae4586edb..9469a52f110 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -51,6 +51,77 @@
"inPopup.focus": "Focus Popup Window",
"inPopup.title": "Open in Popup Window",
"loadMore": "Load More",
+ "management.actions.newChat": "New chat",
+ "management.actions.select": "Select",
+ "management.actionsMenu.archiveStale.confirm": "Archive {{count}} topics that have been inactive for over 3 months? They will be marked as completed.",
+ "management.actionsMenu.archiveStale.confirmOk": "Archive",
+ "management.actionsMenu.archiveStale.done": "Archived {{count}} stale topics.",
+ "management.actionsMenu.archiveStale.label": "Archive topics inactive for 3+ months",
+ "management.actionsMenu.archiveStale.noneFound": "No stale topics found.",
+ "management.actionsMenu.archiveStale.title": "Archive stale topics?",
+ "management.actionsMenu.autoSummarize.comingSoon": "Auto-summarization is coming soon — track on the roadmap.",
+ "management.actionsMenu.autoSummarize.label": "Auto-generate summaries for topics without one",
+ "management.actionsMenu.title": "More actions",
+ "management.bulk.archive": "Archive",
+ "management.bulk.cancel": "Cancel",
+ "management.bulk.delete": "Delete",
+ "management.bulk.deleteConfirm": "You are about to delete {{count}} topics. This action cannot be undone.",
+ "management.bulk.deleteTitle": "Delete topics?",
+ "management.bulk.favorite": "Favorite",
+ "management.bulk.selectedCount_one": "{{count}} selected",
+ "management.bulk.selectedCount_other": "{{count}} selected",
+ "management.card.noPreview": "No preview available",
+ "management.columns.project": "Project",
+ "management.columns.status": "Status",
+ "management.columns.title": "Title",
+ "management.columns.trigger": "Trigger",
+ "management.columns.updated": "Updated",
+ "management.empty.filtered.action": "Clear filters",
+ "management.empty.filtered.desc": "Try adjusting filters or clearing them to see more topics.",
+ "management.empty.filtered.title": "No topics match these filters",
+ "management.empty.noTopics.action": "Start new chat",
+ "management.empty.noTopics.desc": "Start a conversation with this agent to create your first topic.",
+ "management.empty.noTopics.title": "No topics yet",
+ "management.filters.project.empty": "No projects",
+ "management.filters.project.label": "Project",
+ "management.filters.status.active": "Active",
+ "management.filters.status.all": "All",
+ "management.filters.status.archived": "Archived",
+ "management.filters.status.completed": "Completed",
+ "management.filters.status.favorite": "Favorites",
+ "management.filters.status.running": "Running",
+ "management.filters.time.all": "All time",
+ "management.filters.time.label": "Time",
+ "management.filters.time.month": "Past month",
+ "management.filters.time.today": "Today",
+ "management.filters.time.week": "Past week",
+ "management.filters.trigger.api": "API",
+ "management.filters.trigger.chat": "Chat",
+ "management.filters.trigger.eval": "Eval",
+ "management.filters.trigger.label": "Trigger",
+ "management.filters.trigger.task": "Task",
+ "management.group.byProject": "By project",
+ "management.group.byTime": "By time",
+ "management.group.label": "Group",
+ "management.group.noProject": "No project",
+ "management.group.none": "None",
+ "management.loadingMore": "Loading more topics…",
+ "management.searchPlaceholder": "Search this agent's topics…",
+ "management.sidebarEntry": "Topics",
+ "management.sort.createdAt": "Created time",
+ "management.sort.label": "Sort",
+ "management.sort.title": "Title",
+ "management.sort.updatedAt": "Updated time",
+ "management.status.active": "Active",
+ "management.status.archived": "Archived",
+ "management.status.completed": "Completed",
+ "management.status.failed": "Failed",
+ "management.status.paused": "Paused",
+ "management.status.running": "Running",
+ "management.status.waitingForHuman": "Awaiting input",
+ "management.title": "Topics",
+ "management.view.card": "Card",
+ "management.view.list": "List",
"newTopic": "New Topic",
"renameModal.description": "Keep it short and easy to recognize.",
"renameModal.title": "Rename Topic",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index 8afb5c7c68e..3eac5aaf8e4 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -51,6 +51,77 @@
"inPopup.focus": "聚焦独立窗口",
"inPopup.title": "已在独立窗口中打开",
"loadMore": "更多",
+ "management.actions.newChat": "新对话",
+ "management.actions.select": "选择",
+ "management.actionsMenu.archiveStale.confirm": "将 {{count}} 个超过 3 个月未活动的话题归档(标记为已完成)?",
+ "management.actionsMenu.archiveStale.confirmOk": "归档",
+ "management.actionsMenu.archiveStale.done": "已归档 {{count}} 个话题。",
+ "management.actionsMenu.archiveStale.label": "归档 3 个月未活动的话题",
+ "management.actionsMenu.archiveStale.noneFound": "没有需要归档的话题。",
+ "management.actionsMenu.archiveStale.title": "归档过时话题?",
+ "management.actionsMenu.autoSummarize.comingSoon": "自动生成摘要功能即将上线,敬请期待。",
+ "management.actionsMenu.autoSummarize.label": "为缺少摘要的话题自动生成",
+ "management.actionsMenu.title": "更多操作",
+ "management.bulk.archive": "归档",
+ "management.bulk.cancel": "取消",
+ "management.bulk.delete": "删除",
+ "management.bulk.deleteConfirm": "即将删除 {{count}} 个话题,此操作无法撤销。",
+ "management.bulk.deleteTitle": "删除话题?",
+ "management.bulk.favorite": "收藏",
+ "management.bulk.selectedCount_one": "已选 {{count}} 项",
+ "management.bulk.selectedCount_other": "已选 {{count}} 项",
+ "management.card.noPreview": "暂无预览内容",
+ "management.columns.project": "项目",
+ "management.columns.status": "状态",
+ "management.columns.title": "标题",
+ "management.columns.trigger": "来源",
+ "management.columns.updated": "更新时间",
+ "management.empty.filtered.action": "清空筛选",
+ "management.empty.filtered.desc": "试试调整或清空筛选条件,看更多话题。",
+ "management.empty.filtered.title": "没有符合条件的话题",
+ "management.empty.noTopics.action": "开始新对话",
+ "management.empty.noTopics.desc": "和这个助手聊聊,创建第一个话题。",
+ "management.empty.noTopics.title": "还没有话题",
+ "management.filters.project.empty": "暂无项目",
+ "management.filters.project.label": "项目",
+ "management.filters.status.active": "活跃",
+ "management.filters.status.all": "全部",
+ "management.filters.status.archived": "已归档",
+ "management.filters.status.completed": "已完成",
+ "management.filters.status.favorite": "已收藏",
+ "management.filters.status.running": "运行中",
+ "management.filters.time.all": "全部时间",
+ "management.filters.time.label": "时间",
+ "management.filters.time.month": "最近一月",
+ "management.filters.time.today": "今天",
+ "management.filters.time.week": "最近一周",
+ "management.filters.trigger.api": "API",
+ "management.filters.trigger.chat": "对话",
+ "management.filters.trigger.eval": "评测",
+ "management.filters.trigger.label": "来源",
+ "management.filters.trigger.task": "任务",
+ "management.group.byProject": "按项目",
+ "management.group.byTime": "按时间",
+ "management.group.label": "分组",
+ "management.group.noProject": "无项目",
+ "management.group.none": "不分组",
+ "management.loadingMore": "正在加载更多话题…",
+ "management.searchPlaceholder": "在当前助手的话题中搜索…",
+ "management.sidebarEntry": "话题",
+ "management.sort.createdAt": "按创建时间",
+ "management.sort.label": "排序",
+ "management.sort.title": "按标题",
+ "management.sort.updatedAt": "按更新时间",
+ "management.status.active": "活跃",
+ "management.status.archived": "已归档",
+ "management.status.completed": "已完成",
+ "management.status.failed": "已失败",
+ "management.status.paused": "已暂停",
+ "management.status.running": "运行中",
+ "management.status.waitingForHuman": "等待响应",
+ "management.title": "话题",
+ "management.view.card": "卡片",
+ "management.view.list": "列表",
"newTopic": "新话题",
"renameModal.description": "保持简短且易于识别。",
"renameModal.title": "重命名话题",
diff --git a/packages/database/src/models/__tests__/topics/topic.query.test.ts b/packages/database/src/models/__tests__/topics/topic.query.test.ts
index 0f0b2077a8d..e66c77e94cb 100644
--- a/packages/database/src/models/__tests__/topics/topic.query.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.query.test.ts
@@ -753,6 +753,281 @@ describe('TopicModel - Query', () => {
});
});
+ describe('query with withDetails option', () => {
+ const seedTopicWithMessages = async (
+ topicId: string,
+ userMessage: string,
+ messageCount: number,
+ description?: string,
+ trigger?: string,
+ ) => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(agents).values({ id: `agt-${topicId}`, userId, title: `Agent ${topicId}` });
+ await tx.insert(topics).values({
+ id: topicId,
+ userId,
+ agentId: `agt-${topicId}`,
+ description: description ?? null,
+ trigger: trigger ?? null,
+ updatedAt: new Date('2024-01-01'),
+ });
+
+ const rows = [
+ { id: `${topicId}-m0`, role: 'user', content: userMessage },
+ ...Array.from({ length: messageCount - 1 }, (_, i) => ({
+ id: `${topicId}-m${i + 1}`,
+ role: i % 2 === 0 ? 'assistant' : 'user',
+ content: `reply ${i + 1}`,
+ })),
+ ].map((m, idx) => ({
+ ...m,
+ topicId,
+ userId,
+ createdAt: new Date(`2024-01-01T00:00:0${idx}Z`),
+ }));
+ if (rows.length > 0) await tx.insert(messages).values(rows);
+ });
+ };
+
+ it('omits detail columns by default (withDetails not set)', async () => {
+ await seedTopicWithMessages('plain-topic', 'first user msg', 3, 'desc-text', 'chat');
+
+ const result = await topicModel.query({ agentId: 'agt-plain-topic' });
+
+ expect(result.items).toHaveLength(1);
+ const item = result.items[0] as Record<string, unknown>;
+ expect(item.id).toBe('plain-topic');
+ // Sidebar-shape: detail columns must not exist on the payload
+ expect(item).not.toHaveProperty('firstUserMessage');
+ expect(item).not.toHaveProperty('messageCount');
+ expect(item).not.toHaveProperty('description');
+ expect(item).not.toHaveProperty('trigger');
+ expect(item).not.toHaveProperty('cost');
+ expect(item).not.toHaveProperty('tokenUsage');
+ });
+
+ it('returns detail columns when withDetails is true', async () => {
+ await seedTopicWithMessages(
+ 'detailed-topic',
+ 'hello first user message',
+ 4,
+ 'a short description',
+ 'cron',
+ );
+
+ const result = await topicModel.query({
+ agentId: 'agt-detailed-topic',
+ withDetails: true,
+ });
+
+ expect(result.items).toHaveLength(1);
+ const item = result.items[0] as Record<string, unknown>;
+ expect(item.id).toBe('detailed-topic');
+ expect(item.firstUserMessage).toBe('hello first user message');
+ expect(item.messageCount).toBe(4);
+ expect(item.description).toBe('a short description');
+ expect(item.trigger).toBe('cron');
+ // cost / tokenUsage are not yet returned — waiting on a schema
+ // migration to add real columns before they come back.
+ expect(item).not.toHaveProperty('cost');
+ expect(item).not.toHaveProperty('tokenUsage');
+ });
+
+ it('returns null firstUserMessage when no user message exists', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(agents).values({ id: 'agt-no-user-msg', userId, title: 'No User Msg' });
+ await tx.insert(topics).values({
+ id: 'no-user-msg-topic',
+ userId,
+ agentId: 'agt-no-user-msg',
+ updatedAt: new Date('2024-01-01'),
+ });
+ // Only an assistant message — the `WHERE role = 'user'` subquery should
+ // skip it and return null.
+ await tx.insert(messages).values({
+ id: 'no-user-msg-topic-m0',
+ role: 'assistant',
+ content: 'assistant only reply',
+ topicId: 'no-user-msg-topic',
+ userId,
+ });
+ });
+
+ const result = await topicModel.query({
+ agentId: 'agt-no-user-msg',
+ withDetails: true,
+ });
+
+ expect(result.items).toHaveLength(1);
+ const item = result.items[0] as Record<string, unknown>;
+ expect(item.firstUserMessage).toBeNull();
+ expect(item.messageCount).toBe(1);
+ });
+
+ it('picks the earliest user message by createdAt for firstUserMessage', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(agents).values({ id: 'agt-order', userId, title: 'Order' });
+ await tx.insert(topics).values({
+ id: 'order-topic',
+ userId,
+ agentId: 'agt-order',
+ updatedAt: new Date('2024-01-01'),
+ });
+ // Insert in non-chronological order so we exercise the ORDER BY in
+ // the subquery rather than insertion order.
+ await tx.insert(messages).values([
+ {
+ id: 'order-topic-m2',
+ role: 'user',
+ content: 'second user message',
+ topicId: 'order-topic',
+ userId,
+ createdAt: new Date('2024-01-01T00:00:02Z'),
+ },
+ {
+ id: 'order-topic-m0',
+ role: 'user',
+ content: 'first user message',
+ topicId: 'order-topic',
+ userId,
+ createdAt: new Date('2024-01-01T00:00:00Z'),
+ },
+ {
+ id: 'order-topic-m1',
+ role: 'assistant',
+ content: 'an assistant reply in between',
+ topicId: 'order-topic',
+ userId,
+ createdAt: new Date('2024-01-01T00:00:01Z'),
+ },
+ ]);
+ });
+
+ const result = await topicModel.query({
+ agentId: 'agt-order',
+ withDetails: true,
+ });
+
+ const item = result.items[0] as Record<string, unknown>;
+ expect(item.firstUserMessage).toBe('first user message');
+ expect(item.messageCount).toBe(3);
+ });
+
+ it('also returns detail columns when querying via groupId', async () => {
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(chatGroups).values({ id: 'detail-group', title: 'Detail Group', userId });
+ await tx.insert(topics).values({
+ id: 'detail-group-topic',
+ userId,
+ groupId: 'detail-group',
+ description: 'group topic desc',
+ trigger: 'chat',
+ updatedAt: new Date('2024-01-01'),
+ });
+ await tx.insert(messages).values({
+ id: 'detail-group-topic-m0',
+ role: 'user',
+ content: 'group user message',
+ topicId: 'detail-group-topic',
+ userId,
+ });
+ });
+
+ const result = await topicModel.query({
+ groupId: 'detail-group',
+ withDetails: true,
+ });
+
+ const item = result.items[0] as Record<string, unknown>;
+ expect(item.firstUserMessage).toBe('group user message');
+ expect(item.messageCount).toBe(1);
+ expect(item.description).toBe('group topic desc');
+ expect(item.trigger).toBe('chat');
+ });
+
+ it('measures payload size delta between basic and withDetails queries', async () => {
+ // Realistic-ish seed: 20 topics, each with ~5 messages — a first user
+ // message big enough to dominate the row (~600 chars), a long-ish
+ // description (~200 chars), plus a handful of assistant replies that
+ // don't show up in either payload but affect the messageCount subquery.
+ const TOPIC_COUNT = 20;
+ const MESSAGES_PER_TOPIC = 5;
+ const firstUserText = 'u'.repeat(600);
+ const descriptionText = 'd'.repeat(200);
+
+ await serverDB.transaction(async (tx) => {
+ await tx.insert(agents).values({ id: 'agt-size-bench', userId, title: 'Size Bench' });
+ await tx.insert(topics).values(
+ Array.from({ length: TOPIC_COUNT }, (_, i) => ({
+ id: `size-topic-${i}`,
+ userId,
+ agentId: 'agt-size-bench',
+ description: descriptionText,
+ trigger: i % 2 === 0 ? 'chat' : 'cron',
+ updatedAt: new Date(`2024-01-${String(i + 1).padStart(2, '0')}`),
+ })),
+ );
+
+ const messageRows = [] as {
+ id: string;
+ role: string;
+ content: string;
+ topicId: string;
+ userId: string;
+ }[];
+ for (let i = 0; i < TOPIC_COUNT; i++) {
+ messageRows.push({
+ id: `size-topic-${i}-m0`,
+ role: 'user',
+ content: firstUserText,
+ topicId: `size-topic-${i}`,
+ userId,
+ });
+ for (let j = 1; j < MESSAGES_PER_TOPIC; j++) {
+ messageRows.push({
+ id: `size-topic-${i}-m${j}`,
+ role: j % 2 === 1 ? 'assistant' : 'user',
+ content: 'short reply',
+ topicId: `size-topic-${i}`,
+ userId,
+ });
+ }
+ }
+ await tx.insert(messages).values(messageRows);
+ });
+
+ const basic = await topicModel.query({
+ agentId: 'agt-size-bench',
+ pageSize: TOPIC_COUNT,
+ });
+ const detailed = await topicModel.query({
+ agentId: 'agt-size-bench',
+ pageSize: TOPIC_COUNT,
+ withDetails: true,
+ });
+
+ const basicBytes = Buffer.byteLength(JSON.stringify(basic.items), 'utf8');
+ const detailedBytes = Buffer.byteLength(JSON.stringify(detailed.items), 'utf8');
+ const ratio = detailedBytes / basicBytes;
+
+ // Print so the developer running the test gets a real-world number to
+ // reason about — the actual size depends on text length seeded above.
+
+ console.log(
+ `[topic.query withDetails size] basic=${basicBytes}B detailed=${detailedBytes}B ` +
+ `ratio=${ratio.toFixed(2)}x perRowDelta=${Math.round(
+ (detailedBytes - basicBytes) / TOPIC_COUNT,
+ )}B`,
+ );
+
+ // Detailed payload must be strictly larger and roughly proportional to
+ // the seeded user-message + description text — guard against the detail
+ // columns silently disappearing from the SELECT shape.
+ expect(detailedBytes).toBeGreaterThan(basicBytes);
+ expect(ratio).toBeGreaterThan(1.5);
+ });
+ });
+
describe('isInbox parameter', () => {
it('should query legacy inbox topics when isInbox is true', async () => {
await serverDB.transaction(async (trx) => {
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 24e095d8dea..54062b6406f 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -11,7 +11,22 @@ import {
runTimedSinkStage as runTimedStage,
} from '@lobechat/utils';
import type { SQL } from 'drizzle-orm';
-import { and, count, desc, eq, gt, gte, inArray, isNull, lte, ne, not, or, sql } from 'drizzle-orm';
+import {
+ and,
+ asc,
+ count,
+ desc,
+ eq,
+ gt,
+ gte,
+ inArray,
+ isNull,
+ lte,
+ ne,
+ not,
+ or,
+ sql,
+} from 'drizzle-orm';
import type { TopicItem } from '../schemas';
import { agents, agentsToSessions, messagePlugins, messages, topics } from '../schemas';
@@ -73,6 +88,15 @@ interface QueryTopicParams {
* Include only topics matching the given trigger types (positive filter)
*/
triggers?: string[];
+ /**
+ * When true, the SELECT also returns the heavier card-detail columns used
+ * by the per-agent Topics management page: `firstUserMessage` (subquery),
+ * `messageCount` (subquery), `description`, `trigger`. `cost` and
+ * `tokenUsage` are intentionally omitted until a dedicated schema migration
+ * adds real columns to back them. Defaults to false so sidebar paths stay
+ * cheap.
+ */
+ withDetails?: boolean;
}
export interface ModelTimingContext extends TimingSink {}
@@ -104,6 +128,7 @@ export class TopicModel {
isInbox,
timing,
triggers,
+ withDetails = false,
}: QueryTopicParams = {}) => {
const queryStartedAt = Date.now();
logTiming(timing, 'db.topic.query:start', {
@@ -113,8 +138,46 @@ export class TopicModel {
hasGroupId: !!groupId,
isInbox: !!isInbox,
pageSize,
+ withDetails,
});
const offset = current * pageSize;
+
+ // Heavier columns gated behind `withDetails` and used by the per-agent
+ // Topics management page: real aggregates from the `messages` table
+ // (firstUserMessage + messageCount), plus the `description` / `trigger`
+ // columns that sidebar paths don't consume. `cost` and `tokenUsage`
+ // intentionally stay undefined here — they need their own schema
+ // migration before they can be backed by real numbers.
+ //
+ // The two correlated subqueries are built with Drizzle's query builder
+ // (not a raw `sql` template) so the inner `eq(messages.topicId,
+ // topics.id)` renders as `"messages"."topic_id" = "topics"."id"` — both
+ // sides fully qualified. A bare `sql\`... ${topics.id} ...\`` template
+ // renders `topics.id` as an unqualified `"id"`, which PostgreSQL then
+ // resolves against the inner FROM (messages.id) and the WHERE silently
+ // matches nothing.
+ const firstUserMessageSubquery = this.db
+ .select({ value: messages.content })
+ .from(messages)
+ .where(and(eq(messages.topicId, topics.id), eq(messages.role, 'user')))
+ .orderBy(asc(messages.createdAt))
+ .limit(1);
+ const messageCountSubquery = this.db
+ .select({ value: sql<number>`count(*)::int` })
+ .from(messages)
+ .where(eq(messages.topicId, topics.id));
+
+ const detailColumns = withDetails
+ ? {
+ description: topics.description,
+ firstUserMessage: sql<string | null>`(${firstUserMessageSubquery})`.as(
+ 'first_user_message',
+ ),
+ messageCount: sql<number>`(${messageCountSubquery})`.as('message_count'),
+ trigger: topics.trigger,
+ }
+ : {};
+
const includeTriggerCondition =
includeTriggers && includeTriggers.length > 0
? inArray(topics.trigger, includeTriggers)
@@ -151,6 +214,10 @@ export class TopicModel {
'db.topic.query.group.items.select',
() =>
this.db
+ // Cast to `any` because Drizzle's `.select` infers a strict
+ // SelectedFields shape and the conditional `detailColumns` widens
+ // to a union; the runtime shape is correct and the client casts
+ // back to `ChatTopic[]` after TRPC serialization.
.select({
completedAt: topics.completedAt,
createdAt: topics.createdAt,
@@ -161,7 +228,8 @@ export class TopicModel {
status: topics.status,
title: topics.title,
updatedAt: topics.updatedAt,
- })
+ ...detailColumns,
+ } as any)
.from(topics)
.where(whereCondition)
.orderBy(desc(topics.favorite), desc(topics.updatedAt))
@@ -246,6 +314,7 @@ export class TopicModel {
'db.topic.query.agent.items.select',
() =>
this.db
+ // See note on the group-branch select above re: `as any` cast.
.select({
completedAt: topics.completedAt,
createdAt: topics.createdAt,
@@ -256,7 +325,8 @@ export class TopicModel {
status: topics.status,
title: topics.title,
updatedAt: topics.updatedAt,
- })
+ ...detailColumns,
+ } as any)
.from(topics)
.where(agentWhere)
.orderBy(desc(topics.favorite), desc(topics.updatedAt))
@@ -300,6 +370,7 @@ export class TopicModel {
'db.topic.query.container.items.select',
() =>
this.db
+ // See note on the group-branch select above re: `as any` cast.
.select({
agentId: topics.agentId,
completedAt: topics.completedAt,
@@ -312,7 +383,8 @@ export class TopicModel {
status: topics.status,
title: topics.title,
updatedAt: topics.updatedAt,
- })
+ ...detailColumns,
+ } as any)
.from(topics)
.where(whereCondition)
// In boolean sorting, false is considered "smaller" than true.
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 963eda1d1db..6092e795aa4 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -190,12 +190,21 @@ export type ChatTopicStatus =
export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {
completedAt?: Date | null;
+ /** Server-side mock until real cost aggregation lands. */
+ cost?: number | null;
+ description?: string | null;
favorite?: boolean;
+ /** First user message (sliced server-side, used as preview fallback). */
+ firstUserMessage?: string | null;
historySummary?: string;
+ /** Total message count for the topic. */
+ messageCount?: number | null;
metadata?: ChatTopicMetadata;
sessionId?: string;
status?: ChatTopicStatus | null;
title: string;
+ /** Server-side mock until real token aggregation lands. */
+ tokenUsage?: number | null;
trigger?: string | null;
}
@@ -275,6 +284,13 @@ export interface QueryTopicParams {
* Include only topics matching the given trigger types (positive filter)
*/
triggers?: string[];
+ /**
+ * When true, the response includes heavier card-detail fields
+ * (`firstUserMessage`, `messageCount`, `description`, `trigger`, plus mock
+ * `cost` / `tokenUsage`). Only the per-agent Topics management page opts
+ * in — sidebar paths stay lean.
+ */
+ withDetails?: boolean;
}
/**
diff --git a/src/features/AgentTopicManager/BulkActionBar.tsx b/src/features/AgentTopicManager/BulkActionBar.tsx
new file mode 100644
index 00000000000..e449a7c4354
--- /dev/null
+++ b/src/features/AgentTopicManager/BulkActionBar.tsx
@@ -0,0 +1,130 @@
+'use client';
+
+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';
+import { App } from 'antd';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { Archive, Star, Trash2, X } from 'lucide-react';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+
+import { useTopicsViewStore } from './store';
+
+const styles = createStaticStyles(({ css }) => ({
+ bar: css`
+ pointer-events: auto;
+
+ padding-block: 8px;
+ padding-inline: 16px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 999px;
+
+ background: ${cssVar.colorBgElevated};
+ box-shadow:
+ 0 12px 32px rgb(0 0 0 / 24%),
+ 0 2px 6px rgb(0 0 0 / 16%);
+ `,
+ divider: css`
+ width: 1px;
+ height: 16px;
+ margin-inline: 2px;
+ background: ${cssVar.colorBorderSecondary};
+ `,
+ overlay: css`
+ pointer-events: none;
+
+ position: fixed;
+ z-index: 1000;
+ inset-block-end: 24px;
+ inset-inline: 0;
+
+ display: flex;
+ justify-content: center;
+ `,
+}));
+
+const BulkActionBar = memo(() => {
+ const { t } = useTranslation('topic');
+ const { modal } = App.useApp();
+
+ const selectedIds = useTopicsViewStore((s) => s.selectedIds);
+ const exitSelectMode = useTopicsViewStore((s) => s.exitSelectMode);
+
+ const favoriteTopic = useChatStore((s) => s.favoriteTopic);
+ const updateTopicStatus = useChatStore((s) => s.updateTopicStatus);
+ const removeTopic = useChatStore((s) => s.removeTopic);
+
+ const handleBatchFavorite = useCallback(async () => {
+ await Promise.all(selectedIds.map((id) => favoriteTopic(id, true)));
+ exitSelectMode();
+ }, [selectedIds, favoriteTopic, exitSelectMode]);
+
+ const handleBatchArchive = useCallback(async () => {
+ // "Archive" in the UI is a friendlier name for marking topics as
+ // completed — the dedicated `archived` status isn't surfaced to users.
+ await Promise.all(
+ selectedIds.map((id) => updateTopicStatus({ status: 'completed', topicId: id })),
+ );
+ exitSelectMode();
+ }, [selectedIds, updateTopicStatus, exitSelectMode]);
+
+ const handleBatchDelete = useCallback(() => {
+ modal.confirm({
+ content: t('management.bulk.deleteConfirm', { count: selectedIds.length }),
+ okButtonProps: { danger: true },
+ okText: t('management.bulk.delete'),
+ onOk: async () => {
+ // Serial removal so each call's optimistic update + refetch resolves
+ // cleanly; parallel removeTopic causes cascading refetches.
+ for (const id of selectedIds) {
+ await removeTopic(id);
+ }
+ exitSelectMode();
+ },
+ title: t('management.bulk.deleteTitle'),
+ });
+ }, [selectedIds, modal, t, removeTopic, exitSelectMode]);
+
+ if (selectedIds.length === 0) return null;
+
+ return (
+ <div className={styles.overlay}>
+ <Flexbox horizontal align={'center'} className={styles.bar} gap={4}>
+ <Text style={{ marginInlineEnd: 8 }} weight={500}>
+ {t('management.bulk.selectedCount', { count: selectedIds.length })}
+ </Text>
+ <ActionIcon
+ icon={Star}
+ size={'small'}
+ title={t('management.bulk.favorite')}
+ onClick={handleBatchFavorite}
+ />
+ <ActionIcon
+ icon={Archive}
+ size={'small'}
+ title={t('management.bulk.archive')}
+ onClick={handleBatchArchive}
+ />
+ <ActionIcon
+ icon={Trash2}
+ size={'small'}
+ style={{ color: cssVar.colorError }}
+ title={t('management.bulk.delete')}
+ onClick={handleBatchDelete}
+ />
+ <span className={styles.divider} />
+ <ActionIcon
+ icon={X}
+ size={'small'}
+ title={t('management.bulk.cancel')}
+ onClick={exitSelectMode}
+ />
+ </Flexbox>
+ </div>
+ );
+});
+
+BulkActionBar.displayName = 'AgentTopicManagerBulkActionBar';
+
+export default BulkActionBar;
diff --git a/src/features/AgentTopicManager/EmptyState.tsx b/src/features/AgentTopicManager/EmptyState.tsx
new file mode 100644
index 00000000000..5c9fc661c89
--- /dev/null
+++ b/src/features/AgentTopicManager/EmptyState.tsx
@@ -0,0 +1,46 @@
+'use client';
+
+import { Button, Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { MessagesSquare } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+import { SESSION_CHAT_URL } from '@/const/url';
+
+interface EmptyStateProps {
+ agentId: string;
+ hasFilters: boolean;
+ onClearFilters: () => void;
+}
+
+const EmptyState = memo<EmptyStateProps>(({ agentId, hasFilters, onClearFilters }) => {
+ const { t } = useTranslation('topic');
+ const navigate = useNavigate();
+
+ return (
+ <Flexbox align={'center'} flex={1} gap={16} justify={'center'} paddingBlock={64}>
+ <Icon icon={MessagesSquare} size={48} style={{ color: cssVar.colorTextQuaternary }} />
+ <Flexbox align={'center'} gap={4}>
+ <Text fontSize={16} weight={600}>
+ {hasFilters ? t('management.empty.filtered.title') : t('management.empty.noTopics.title')}
+ </Text>
+ <Text fontSize={13} type={'secondary'}>
+ {hasFilters ? t('management.empty.filtered.desc') : t('management.empty.noTopics.desc')}
+ </Text>
+ </Flexbox>
+ {hasFilters ? (
+ <Button onClick={onClearFilters}>{t('management.empty.filtered.action')}</Button>
+ ) : (
+ <Button type={'primary'} onClick={() => navigate(SESSION_CHAT_URL(agentId))}>
+ {t('management.empty.noTopics.action')}
+ </Button>
+ )}
+ </Flexbox>
+ );
+});
+
+EmptyState.displayName = 'AgentTopicManagerEmptyState';
+
+export default EmptyState;
diff --git a/src/features/AgentTopicManager/Header.tsx b/src/features/AgentTopicManager/Header.tsx
new file mode 100644
index 00000000000..417978a6749
--- /dev/null
+++ b/src/features/AgentTopicManager/Header.tsx
@@ -0,0 +1,96 @@
+'use client';
+
+import { Flexbox, Icon, Input, Segmented, Text } from '@lobehub/ui';
+import { Breadcrumb as AntBreadcrumb } from 'antd';
+import { ChevronRight, LayoutGrid, List as ListIcon, Search } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link } from 'react-router-dom';
+import urlJoin from 'url-join';
+
+import NavHeader from '@/features/NavHeader';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+
+import { useTopicsViewStore } from './store';
+
+interface HeaderProps {
+ agentId: string;
+}
+
+const Header = memo<HeaderProps>(({ agentId }) => {
+ const { t } = useTranslation(['topic', 'chat', 'common']);
+ const agentTitle = useAgentStore(agentSelectors.currentAgentTitle);
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const displayTitle = isInbox
+ ? agentTitle || t('inbox.title', { ns: 'chat' })
+ : agentTitle || t('defaultSession', { ns: 'common' });
+ const viewMode = useTopicsViewStore((s) => s.viewMode);
+ const setViewMode = useTopicsViewStore((s) => s.setViewMode);
+ const search = useTopicsViewStore((s) => s.search);
+ const setSearch = useTopicsViewStore((s) => s.setSearch);
+
+ return (
+ <NavHeader
+ styles={{ center: { maxWidth: 560, paddingInline: 16 } }}
+ left={
+ <AntBreadcrumb
+ separator={<Icon icon={ChevronRight} size={14} />}
+ items={[
+ {
+ title: (
+ <Link to={urlJoin('/agent', agentId)}>
+ <Text ellipsis color={'inherit'} style={{ maxWidth: 200 }} weight={500}>
+ {displayTitle}
+ </Text>
+ </Link>
+ ),
+ },
+ {
+ title: (
+ <Text color={'inherit'} weight={500}>
+ {t('management.title')}
+ </Text>
+ ),
+ },
+ ]}
+ />
+ }
+ right={
+ <Flexbox horizontal align={'center'} gap={6}>
+ <Segmented
+ size={'small'}
+ value={viewMode}
+ variant={'borderless'}
+ options={[
+ {
+ icon: <Icon icon={LayoutGrid} />,
+ title: t('management.view.card'),
+ value: 'card',
+ },
+ {
+ icon: <Icon icon={ListIcon} />,
+ title: t('management.view.list'),
+ value: 'list',
+ },
+ ]}
+ onChange={(v) => setViewMode(v as 'card' | 'list')}
+ />
+ </Flexbox>
+ }
+ >
+ <Input
+ placeholder={t('management.searchPlaceholder')}
+ prefix={<Icon icon={Search} size={'small'} />}
+ size={'middle'}
+ value={search}
+ variant={'filled'}
+ onChange={(e) => setSearch(e.target.value)}
+ />
+ </NavHeader>
+ );
+});
+
+Header.displayName = 'AgentTopicManagerHeader';
+
+export default Header;
diff --git a/src/features/AgentTopicManager/StatusDot.tsx b/src/features/AgentTopicManager/StatusDot.tsx
new file mode 100644
index 00000000000..f19ab864c93
--- /dev/null
+++ b/src/features/AgentTopicManager/StatusDot.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { cssVar, useTheme } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import RingLoadingIcon from '@/components/RingLoading';
+
+const STATUS_COLOR: Record<string, string> = {
+ active: cssVar.colorSuccess,
+ archived: cssVar.colorWarning,
+ completed: cssVar.colorTextQuaternary,
+ failed: cssVar.colorError,
+ paused: cssVar.colorInfo,
+ running: cssVar.colorWarning,
+ waitingForHuman: cssVar.colorInfo,
+};
+
+interface StatusDotProps {
+ status: string;
+}
+
+const StatusDot = memo<StatusDotProps>(({ status }) => {
+ const { t } = useTranslation('topic');
+ const { isDarkMode } = useTheme();
+ const color = STATUS_COLOR[status] ?? cssVar.colorTextQuaternary;
+ const labelKey = `management.status.${status}` as const;
+
+ // Match the sidebar Topic row: running shows the same spinning ring icon
+ // (warning color) rather than a static dot, so users get a consistent
+ // visual signal for "this topic is currently running".
+ const isRunning = status === 'running';
+ const ringColor = isDarkMode
+ ? cssVar.colorWarningBorder
+ : `color-mix(in srgb, ${cssVar.colorWarning} 45%, transparent)`;
+
+ return (
+ <Flexbox horizontal align={'center'} gap={6}>
+ {isRunning ? (
+ <RingLoadingIcon ringColor={ringColor} size={10} style={{ color: cssVar.colorWarning }} />
+ ) : (
+ <span
+ style={{
+ background: color,
+ borderRadius: '50%',
+ flexShrink: 0,
+ height: 6,
+ width: 6,
+ }}
+ />
+ )}
+ <span style={{ color: cssVar.colorTextSecondary, fontSize: 11 }}>{t(labelKey as any)}</span>
+ </Flexbox>
+ );
+});
+
+StatusDot.displayName = 'AgentTopicManagerStatusDot';
+
+export default StatusDot;
diff --git a/src/features/AgentTopicManager/Toolbar.tsx b/src/features/AgentTopicManager/Toolbar.tsx
new file mode 100644
index 00000000000..4a4de992256
--- /dev/null
+++ b/src/features/AgentTopicManager/Toolbar.tsx
@@ -0,0 +1,251 @@
+'use client';
+
+import {
+ Button,
+ type DropdownItem,
+ DropdownMenu,
+ Flexbox,
+ Icon,
+ Segmented,
+ Text,
+} from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import {
+ ChevronDown,
+ ListTodoIcon,
+ type LucideIcon,
+ MessageCircle,
+ TestTubeIcon,
+ Webhook,
+} from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useTopicsViewStore } from './store';
+import ToolbarActions from './ToolbarActions';
+import type { GroupBy, SortBy, StatusFilter, TimeRangeFilter, TriggerFilter } from './types';
+
+const styles = createStaticStyles(({ css }) => ({
+ divider: css`
+ width: 1px;
+ height: 16px;
+ margin-inline: 4px;
+ background: ${cssVar.colorBorderSecondary};
+ `,
+}));
+
+const STATUS_OPTIONS: { key: StatusFilter; labelKey: string }[] = [
+ { key: 'all', labelKey: 'management.filters.status.all' },
+ { key: 'active', labelKey: 'management.filters.status.active' },
+ { key: 'running', labelKey: 'management.filters.status.running' },
+ { key: 'completed', labelKey: 'management.filters.status.completed' },
+];
+
+const TRIGGER_OPTIONS: TriggerFilter[] = ['chat', 'api', 'task', 'eval'];
+
+const TRIGGER_ICON: Record<TriggerFilter, LucideIcon> = {
+ api: Webhook,
+ chat: MessageCircle,
+ eval: TestTubeIcon,
+ task: ListTodoIcon,
+};
+
+const TIME_OPTIONS: TimeRangeFilter[] = ['all', 'today', 'week', 'month'];
+
+const SORT_OPTIONS: SortBy[] = ['updatedAt', 'createdAt', 'title'];
+
+const GROUP_OPTIONS: GroupBy[] = ['byTime', 'byProject', 'none'];
+
+interface ToolbarProps {
+ projects: { label: string; value: string }[];
+ statusCounts: Record<StatusFilter, number>;
+}
+
+const CheckMark = ({ visible }: { visible: boolean }) => (
+ <span style={{ display: 'inline-block', width: 12 }}>{visible ? '✓' : ''}</span>
+);
+
+const Toolbar = memo<ToolbarProps>(({ projects, statusCounts }) => {
+ const { t } = useTranslation('topic');
+
+ const status = useTopicsViewStore((s) => s.status);
+ const setStatus = useTopicsViewStore((s) => s.setStatus);
+ const groupIds = useTopicsViewStore((s) => s.groupIds);
+ const setGroupIds = useTopicsViewStore((s) => s.setGroupIds);
+ const triggers = useTopicsViewStore((s) => s.triggers);
+ const setTriggers = useTopicsViewStore((s) => s.setTriggers);
+ const timeRange = useTopicsViewStore((s) => s.timeRange);
+ const setTimeRange = useTopicsViewStore((s) => s.setTimeRange);
+ const sortBy = useTopicsViewStore((s) => s.sortBy);
+ const setSortBy = useTopicsViewStore((s) => s.setSortBy);
+ const groupBy = useTopicsViewStore((s) => s.groupBy);
+ const setGroupBy = useTopicsViewStore((s) => s.setGroupBy);
+
+ const projectMenu: DropdownItem[] = useMemo(() => {
+ if (projects.length === 0) {
+ return [{ disabled: true, key: 'empty', label: t('management.filters.project.empty') }];
+ }
+ return projects.map((p) => ({
+ icon: <CheckMark visible={groupIds.includes(p.value)} />,
+ key: p.value,
+ label: p.label,
+ onClick: () =>
+ setGroupIds(
+ groupIds.includes(p.value)
+ ? groupIds.filter((x) => x !== p.value)
+ : [...groupIds, p.value],
+ ),
+ }));
+ }, [projects, groupIds, t, setGroupIds]);
+
+ const triggerMenu: DropdownItem[] = useMemo(
+ () =>
+ TRIGGER_OPTIONS.map((tr) => ({
+ extra: <CheckMark visible={triggers.includes(tr)} />,
+ icon: <Icon icon={TRIGGER_ICON[tr]} size={14} />,
+ key: tr,
+ label: t(`management.filters.trigger.${tr}` as any) as string,
+ onClick: () =>
+ setTriggers(triggers.includes(tr) ? triggers.filter((x) => x !== tr) : [...triggers, tr]),
+ })),
+ [triggers, t, setTriggers],
+ );
+
+ const timeMenu: DropdownItem[] = useMemo(
+ () =>
+ TIME_OPTIONS.map((r) => ({
+ icon: <CheckMark visible={timeRange === r} />,
+ key: r,
+ label: t(`management.filters.time.${r}` as any) as string,
+ onClick: () => setTimeRange(r),
+ })),
+ [timeRange, t, setTimeRange],
+ );
+
+ const sortMenu: DropdownItem[] = useMemo(
+ () =>
+ SORT_OPTIONS.map((s) => ({
+ icon: <CheckMark visible={sortBy === s} />,
+ key: s,
+ label: t(`management.sort.${s}` as any) as string,
+ onClick: () => setSortBy(s),
+ })),
+ [sortBy, t, setSortBy],
+ );
+
+ const groupMenu: DropdownItem[] = useMemo(
+ () =>
+ GROUP_OPTIONS.map((g) => ({
+ icon: <CheckMark visible={groupBy === g} />,
+ key: g,
+ label: t(`management.group.${g}` as any) as string,
+ onClick: () => setGroupBy(g),
+ })),
+ [groupBy, t, setGroupBy],
+ );
+
+ const triggerLabel =
+ triggers.length === 0
+ ? (t('management.filters.trigger.label') as string)
+ : `${t('management.filters.trigger.label')} (${triggers.length})`;
+
+ const projectLabel =
+ groupIds.length === 0
+ ? (t('management.filters.project.label') as string)
+ : `${t('management.filters.project.label')} (${groupIds.length})`;
+
+ const timeLabel =
+ timeRange === 'all'
+ ? (t('management.filters.time.label') as string)
+ : (t(`management.filters.time.${timeRange}` as any) as string);
+
+ const sortLabel = `${t('management.sort.label')}: ${t(`management.sort.${sortBy}` as any)}`;
+ const groupLabel = `${t('management.group.label')}: ${t(`management.group.${groupBy}` as any)}`;
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox horizontal align={'center'} gap={6} wrap={'wrap'}>
+ <Segmented
+ value={status}
+ options={STATUS_OPTIONS.map((opt) => {
+ const count = statusCounts[opt.key] ?? 0;
+ return {
+ label: (
+ <Flexbox horizontal align={'center'} gap={6}>
+ <span>{t(opt.labelKey as any) as string}</span>
+ <Text
+ style={{
+ color: status === opt.key ? 'inherit' : cssVar.colorTextTertiary,
+ fontSize: 12,
+ fontVariantNumeric: 'tabular-nums',
+ opacity: status === opt.key ? 0.7 : 1,
+ }}
+ >
+ {count}
+ </Text>
+ </Flexbox>
+ ),
+ value: opt.key,
+ };
+ })}
+ onChange={(v) => setStatus(v as StatusFilter)}
+ />
+
+ <span className={styles.divider} />
+
+ <DropdownMenu items={projectMenu}>
+ <Button variant={'filled'}>
+ <Flexbox horizontal align={'center'} gap={4}>
+ {projectLabel}
+ <Icon icon={ChevronDown} size={11} />
+ </Flexbox>
+ </Button>
+ </DropdownMenu>
+
+ <DropdownMenu items={triggerMenu}>
+ <Button variant={'filled'}>
+ <Flexbox horizontal align={'center'} gap={4}>
+ {triggerLabel}
+ <Icon icon={ChevronDown} size={11} />
+ </Flexbox>
+ </Button>
+ </DropdownMenu>
+
+ <DropdownMenu items={timeMenu}>
+ <Button variant={'filled'}>
+ <Flexbox horizontal align={'center'} gap={4}>
+ {timeLabel}
+ <Icon icon={ChevronDown} size={11} />
+ </Flexbox>
+ </Button>
+ </DropdownMenu>
+
+ <Flexbox flex={1} />
+
+ <DropdownMenu items={groupMenu}>
+ <Button variant={'filled'}>
+ <Flexbox horizontal align={'center'} gap={4}>
+ {groupLabel}
+ <Icon icon={ChevronDown} size={11} />
+ </Flexbox>
+ </Button>
+ </DropdownMenu>
+
+ <DropdownMenu items={sortMenu}>
+ <Button variant={'filled'}>
+ <Flexbox horizontal align={'center'} gap={4}>
+ {sortLabel}
+ <Icon icon={ChevronDown} size={11} />
+ </Flexbox>
+ </Button>
+ </DropdownMenu>
+
+ <ToolbarActions />
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+Toolbar.displayName = 'AgentTopicManagerToolbar';
+
+export default Toolbar;
diff --git a/src/features/AgentTopicManager/ToolbarActions.tsx b/src/features/AgentTopicManager/ToolbarActions.tsx
new file mode 100644
index 00000000000..fbc4e8b58c0
--- /dev/null
+++ b/src/features/AgentTopicManager/ToolbarActions.tsx
@@ -0,0 +1,73 @@
+'use client';
+
+import { ActionIcon, type DropdownItem, DropdownMenu } from '@lobehub/ui';
+import { App } from 'antd';
+import { Archive, MoreHorizontal } from 'lucide-react';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+const THREE_MONTHS_MS = 90 * 24 * 60 * 60 * 1000;
+
+const ToolbarActions = memo(() => {
+ const { t } = useTranslation('topic');
+ const { modal, message } = App.useApp();
+
+ // Operate on the management page's own bucket — not the sidebar's — since
+ // the management view is the one the user is acting on here.
+ const topics = useChatStore(topicSelectors.agentTopicsViewTopics);
+ const updateTopicStatus = useChatStore((s) => s.updateTopicStatus);
+
+ const handleArchiveStale = useCallback(() => {
+ const cutoff = Date.now() - THREE_MONTHS_MS;
+ const stale = (topics ?? []).filter((t) => {
+ if (t.status === 'completed') return false;
+ const updated =
+ typeof t.updatedAt === 'number' ? t.updatedAt : new Date(t.updatedAt).getTime();
+ return updated < cutoff;
+ });
+
+ if (stale.length === 0) {
+ message.info(t('management.actionsMenu.archiveStale.noneFound'));
+ return;
+ }
+
+ modal.confirm({
+ content: t('management.actionsMenu.archiveStale.confirm', { count: stale.length }),
+ okText: t('management.actionsMenu.archiveStale.confirmOk'),
+ onOk: async () => {
+ for (const topic of stale) {
+ // 'archived' isn't surfaced in the UI, so we mark stale topics as
+ // 'completed' — matches what the user means by "archive" here.
+ await updateTopicStatus({ status: 'completed', topicId: topic.id });
+ }
+ message.success(t('management.actionsMenu.archiveStale.done', { count: stale.length }));
+ },
+ title: t('management.actionsMenu.archiveStale.title'),
+ });
+ }, [topics, updateTopicStatus, modal, message, t]);
+
+ const items: DropdownItem[] = useMemo(
+ () => [
+ {
+ icon: <Archive size={14} />,
+ key: 'archive-stale',
+ label: t('management.actionsMenu.archiveStale.label'),
+ onClick: handleArchiveStale,
+ },
+ ],
+ [t, handleArchiveStale],
+ );
+
+ return (
+ <DropdownMenu items={items}>
+ <ActionIcon icon={MoreHorizontal} title={t('management.actionsMenu.title')} />
+ </DropdownMenu>
+ );
+});
+
+ToolbarActions.displayName = 'AgentTopicManagerToolbarActions';
+
+export default ToolbarActions;
diff --git a/src/features/AgentTopicManager/TopicCard.tsx b/src/features/AgentTopicManager/TopicCard.tsx
new file mode 100644
index 00000000000..b5c25ef9ccd
--- /dev/null
+++ b/src/features/AgentTopicManager/TopicCard.tsx
@@ -0,0 +1,197 @@
+'use client';
+
+import { formatPrice, formatTokenNumber } from '@lobechat/utils/format';
+import { Block, Checkbox, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { CircleDollarSign, FolderIcon, MessageSquare, Star, Zap } from 'lucide-react';
+import { memo, type MouseEvent, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
+import { useActivityTime } from '@/hooks/useActivityTime';
+import type { ChatTopic } from '@/types/topic';
+
+import StatusDot from './StatusDot';
+import { useTopicsViewStore } from './store';
+import { getProjectLabel } from './utils';
+
+const styles = createStaticStyles(({ css }) => ({
+ card: css`
+ cursor: pointer;
+
+ position: relative;
+
+ display: flex;
+ flex-direction: column;
+
+ /* min-height keeps short cards consistent without forcing tall empty
+ whitespace — preview + footer can still grow the card naturally. */
+ min-height: 140px;
+ padding: 14px;
+
+ transition:
+ transform 0.18s,
+ box-shadow 0.18s,
+ border-color 0.18s;
+
+ &:hover {
+ transform: translateY(-1px);
+ box-shadow: 0 4px 12px rgb(0 0 0 / 6%);
+ }
+ `,
+ cardSelected: css`
+ border-color: ${cssVar.colorPrimary};
+ box-shadow: 0 0 0 1px ${cssVar.colorPrimary};
+ `,
+ checkbox: css`
+ position: absolute;
+ z-index: 1;
+ inset-block-start: 10px;
+ inset-inline-end: 10px;
+ `,
+ checkboxBox: css`
+ border-color: ${cssVar.colorBorder};
+ `,
+ description: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+ `,
+ footer: css`
+ /* push to bottom so cards with short content keep the stats row anchored */
+ margin-block-start: auto;
+ padding-block-start: 10px;
+ border-block-start: 1px solid ${cssVar.colorSplit};
+ `,
+ title: css`
+ overflow: hidden;
+ display: -webkit-box;
+ flex: 1;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 1;
+ `,
+}));
+
+interface TopicCardProps {
+ agentId: string;
+ topic: ChatTopic;
+}
+
+const TopicCard = memo<TopicCardProps>(({ topic, agentId }) => {
+ const { t } = useTranslation('topic');
+ const navigate = useNavigate();
+
+ const selectMode = useTopicsViewStore((s) => s.selectMode);
+ const selected = useTopicsViewStore((s) => s.selectedIds.includes(topic.id));
+ const toggleSelected = useTopicsViewStore((s) => s.toggleSelected);
+ const toggleSelectMode = useTopicsViewStore((s) => s.toggleSelectMode);
+
+ const handleClick = useCallback(
+ (e: MouseEvent) => {
+ if (selectMode || e.metaKey || e.ctrlKey) {
+ e.preventDefault();
+ toggleSelected(topic.id);
+ return;
+ }
+ navigate(SESSION_CHAT_TOPIC_URL(agentId, topic.id));
+ },
+ [selectMode, topic.id, agentId, toggleSelected, navigate],
+ );
+
+ const handleCheckboxChange = useCallback(() => {
+ if (!selectMode) toggleSelectMode();
+ toggleSelected(topic.id);
+ }, [selectMode, topic.id, toggleSelected, toggleSelectMode]);
+
+ const stopPropagation = useCallback((e: MouseEvent) => {
+ e.stopPropagation();
+ }, []);
+
+ const projectLabel = getProjectLabel(topic);
+ const status = topic.status ?? 'active';
+ // Preview priority: user-written description → AI history summary → first user
+ // message (sliced server-side when neither richer field exists).
+ const preview =
+ topic.description?.trim() || topic.historySummary?.trim() || topic.firstUserMessage?.trim();
+ const updatedAt = useActivityTime(topic.updatedAt);
+ // Postgres `numeric` / `int` round-trip through TRPC/JSON as strings in
+ // some shapes, so coerce defensively before any `.toFixed` / format call.
+ const messageCount = Number(topic.messageCount ?? 0);
+ const tokenUsage = Number(topic.tokenUsage ?? 0);
+ const cost = Number(topic.cost ?? 0);
+
+ return (
+ <Block
+ className={[styles.card, selected && styles.cardSelected].filter(Boolean).join(' ')}
+ gap={8}
+ variant={'outlined'}
+ onClick={handleClick}
+ >
+ <div className={styles.checkbox} onClick={stopPropagation}>
+ <Checkbox
+ checked={selected}
+ classNames={{ checkbox: styles.checkboxBox }}
+ size={18}
+ onChange={handleCheckboxChange}
+ />
+ </div>
+
+ <Flexbox horizontal align={'center'} gap={6}>
+ {topic.favorite && (
+ <Icon icon={Star} size={13} style={{ color: cssVar.colorWarning, flexShrink: 0 }} />
+ )}
+ <Text className={styles.title} fontSize={14} weight={600}>
+ {topic.title || t('defaultTitle')}
+ </Text>
+ </Flexbox>
+
+ {preview && (
+ <Text className={styles.description} fontSize={12} type={'secondary'}>
+ {preview}
+ </Text>
+ )}
+
+ {projectLabel && (
+ <Tag bordered={false} icon={<Icon icon={FolderIcon} size={11} />} size={'small'}>
+ {projectLabel}
+ </Tag>
+ )}
+
+ <Flexbox horizontal align={'center'} className={styles.footer} justify={'space-between'}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={10}
+ style={{ color: cssVar.colorTextQuaternary, fontSize: 11 }}
+ >
+ {messageCount > 0 && (
+ <Flexbox horizontal align={'center'} gap={3}>
+ <Icon icon={MessageSquare} size={11} />
+ {messageCount}
+ </Flexbox>
+ )}
+ {tokenUsage > 0 && (
+ <Flexbox horizontal align={'center'} gap={3} title={`${tokenUsage} tokens`}>
+ <Icon icon={Zap} size={11} />
+ {formatTokenNumber(tokenUsage)}
+ </Flexbox>
+ )}
+ {cost > 0 && (
+ <Flexbox horizontal align={'center'} gap={3} title={`$${cost.toFixed(4)}`}>
+ <Icon icon={CircleDollarSign} size={11} />
+ {formatPrice(cost, 2)}
+ </Flexbox>
+ )}
+ <span title={updatedAt.title}>{updatedAt.text}</span>
+ </Flexbox>
+ <StatusDot status={status} />
+ </Flexbox>
+ </Block>
+ );
+});
+
+TopicCard.displayName = 'AgentTopicCard';
+
+export default TopicCard;
diff --git a/src/features/AgentTopicManager/TopicGrid.tsx b/src/features/AgentTopicManager/TopicGrid.tsx
new file mode 100644
index 00000000000..f4a1d8df2dc
--- /dev/null
+++ b/src/features/AgentTopicManager/TopicGrid.tsx
@@ -0,0 +1,81 @@
+'use client';
+
+import type { GroupedTopic } from '@lobechat/types';
+import { Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar, responsive } from 'antd-style';
+import { Fragment, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import TopicCard from './TopicCard';
+import type { GroupBy } from './types';
+import { getProjectGroupTitle, getTimeGroupTitle } from './utils';
+
+const styles = createStaticStyles(({ css }) => ({
+ grid: css`
+ display: grid;
+
+ /*
+ min(280px, 100%) lets columns shrink below 280px when the available
+ width itself is narrower (e.g. agent sidebar expanded), so the layout
+ keeps wrapping instead of overflowing horizontally.
+ */
+ grid-template-columns: repeat(auto-fill, minmax(min(280px, 100%), 1fr));
+ gap: 12px;
+
+ width: 100%;
+ min-width: 0;
+
+ ${responsive.md} {
+ grid-template-columns: repeat(auto-fill, minmax(min(240px, 100%), 1fr));
+ }
+ `,
+ groupTitle: css`
+ margin-block-start: 8px;
+ padding-block-end: 4px;
+
+ font-size: 13px;
+ font-weight: 500;
+ color: ${cssVar.colorTextSecondary};
+ `,
+}));
+
+interface TopicGridProps {
+ agentId: string;
+ groupBy: GroupBy;
+ groups: GroupedTopic[];
+ showGroupTitles: boolean;
+}
+
+const TopicGrid = memo<TopicGridProps>(({ groups, agentId, showGroupTitles, groupBy }) => {
+ const { t } = useTranslation('topic');
+
+ return (
+ <Flexbox gap={12}>
+ {groups.map((group) => {
+ if (group.children.length === 0) return null;
+ const title =
+ groupBy === 'byProject'
+ ? getProjectGroupTitle(group.id, group.title, t)
+ : group.title || getTimeGroupTitle(group.id, t);
+ return (
+ <Fragment key={group.id}>
+ {showGroupTitles && (
+ <Text as={'div'} className={styles.groupTitle}>
+ {title}
+ </Text>
+ )}
+ <div className={styles.grid}>
+ {group.children.map((topic) => (
+ <TopicCard agentId={agentId} key={topic.id} topic={topic} />
+ ))}
+ </div>
+ </Fragment>
+ );
+ })}
+ </Flexbox>
+ );
+});
+
+TopicGrid.displayName = 'AgentTopicManagerGrid';
+
+export default TopicGrid;
diff --git a/src/features/AgentTopicManager/TopicListView.tsx b/src/features/AgentTopicManager/TopicListView.tsx
new file mode 100644
index 00000000000..223e35f1454
--- /dev/null
+++ b/src/features/AgentTopicManager/TopicListView.tsx
@@ -0,0 +1,307 @@
+'use client';
+
+import type { GroupedTopic } from '@lobechat/types';
+import { ActionIcon, Checkbox, DropdownMenu, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { FolderIcon, MoreHorizontal, Star } from 'lucide-react';
+import { Fragment, memo, type MouseEvent, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+
+import { SESSION_CHAT_TOPIC_URL } from '@/const/url';
+import { useActivityTime } from '@/hooks/useActivityTime';
+import { useTopicItemDropdownMenu } from '@/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu';
+import type { ChatTopic } from '@/types/topic';
+
+import StatusDot from './StatusDot';
+import { useTopicsViewStore } from './store';
+import type { GroupBy, TriggerFilter } from './types';
+import { getProjectGroupTitle, getProjectLabel, getTimeGroupTitle } from './utils';
+
+const KNOWN_TRIGGERS: readonly TriggerFilter[] = ['chat', 'api', 'task', 'eval'];
+
+const styles = createStaticStyles(({ css }) => ({
+ cell: css`
+ overflow: hidden;
+ min-width: 0;
+ `,
+ checkboxBox: css`
+ border-color: ${cssVar.colorBorder};
+ `,
+ groupBar: css`
+ display: flex;
+ gap: 6px;
+ align-items: baseline;
+
+ padding-block: 8px;
+ padding-inline: 16px;
+ border-block-end: 1px solid ${cssVar.colorSplit};
+
+ font-size: 12px;
+ font-weight: 500;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ groupCount: css`
+ font-size: 11px;
+ font-weight: 400;
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ header: css`
+ position: sticky;
+ z-index: 2;
+ inset-block-start: 0;
+
+ display: grid;
+ grid-template-columns: 24px minmax(0, 1fr) 120px 100px 80px 100px 32px;
+ gap: 12px;
+ align-items: center;
+
+ padding-block: 10px;
+ padding-inline: 16px;
+ border-block-end: 1px solid ${cssVar.colorSplit};
+
+ font-size: 12px;
+ font-weight: 500;
+ color: ${cssVar.colorTextSecondary};
+
+ /* opaque so scrolled rows don't bleed through */
+ background: ${cssVar.colorBgElevated};
+ `,
+ headerCellEnd: css`
+ text-align: end;
+ `,
+ list: css`
+ position: relative;
+
+ overflow: hidden;
+
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 12px;
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ row: css`
+ cursor: pointer;
+
+ display: grid;
+ grid-template-columns: 24px minmax(0, 1fr) 120px 100px 80px 100px 32px;
+ gap: 12px;
+ align-items: center;
+
+ padding-block: 10px;
+ padding-inline: 16px;
+ border-block-end: 1px solid ${cssVar.colorSplit};
+
+ transition: background 0.12s;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+
+ &:last-child {
+ border-block-end: none;
+ }
+ `,
+ rowSelected: css`
+ background: ${cssVar.colorPrimaryBg};
+
+ &:hover {
+ background: ${cssVar.colorPrimaryBgHover};
+ }
+ `,
+ sub: css`
+ overflow: hidden;
+ margin-block-start: 2px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ title: css`
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+interface TopicListViewProps {
+ agentId: string;
+ groupBy: GroupBy;
+ groups: GroupedTopic[];
+ showGroupTitles: boolean;
+}
+
+interface RowProps {
+ agentId: string;
+ topic: ChatTopic;
+}
+
+const Row = memo<RowProps>(({ topic, agentId }) => {
+ const { t } = useTranslation('topic');
+ const navigate = useNavigate();
+
+ const selectMode = useTopicsViewStore((s) => s.selectMode);
+ const selected = useTopicsViewStore((s) => s.selectedIds.includes(topic.id));
+ const toggleSelected = useTopicsViewStore((s) => s.toggleSelected);
+ const toggleSelectMode = useTopicsViewStore((s) => s.toggleSelectMode);
+
+ const { dropdownMenu } = useTopicItemDropdownMenu({
+ fav: topic.favorite,
+ id: topic.id,
+ status: topic.status,
+ title: topic.title,
+ });
+
+ const handleClick = useCallback(
+ (e: MouseEvent) => {
+ if (selectMode || e.metaKey || e.ctrlKey) {
+ e.preventDefault();
+ toggleSelected(topic.id);
+ return;
+ }
+ navigate(SESSION_CHAT_TOPIC_URL(agentId, topic.id));
+ },
+ [selectMode, topic.id, agentId, toggleSelected, navigate],
+ );
+
+ const handleCheckboxChange = useCallback(() => {
+ if (!selectMode) toggleSelectMode();
+ toggleSelected(topic.id);
+ }, [selectMode, topic.id, toggleSelected, toggleSelectMode]);
+
+ const status = topic.status ?? 'active';
+ const projectLabel = getProjectLabel(topic);
+ const updatedAt = useActivityTime(topic.updatedAt);
+ const rawTrigger = topic.trigger ?? 'chat';
+ const triggerKey: TriggerFilter = (KNOWN_TRIGGERS as readonly string[]).includes(rawTrigger)
+ ? (rawTrigger as TriggerFilter)
+ : 'chat';
+ const triggerLabel = t(`management.filters.trigger.${triggerKey}` as any) as string;
+
+ return (
+ <div
+ className={[styles.row, selected && styles.rowSelected].filter(Boolean).join(' ')}
+ onClick={handleClick}
+ >
+ <div onClick={(e) => e.stopPropagation()}>
+ <Checkbox
+ checked={selected}
+ classNames={{ checkbox: styles.checkboxBox }}
+ size={18}
+ onChange={handleCheckboxChange}
+ />
+ </div>
+ <div className={styles.cell}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ {topic.favorite && (
+ <Icon icon={Star} size={12} style={{ color: cssVar.colorWarning, flexShrink: 0 }} />
+ )}
+ <Text className={styles.title} fontSize={13} weight={500}>
+ {topic.title || t('defaultTitle')}
+ </Text>
+ </Flexbox>
+ {topic.historySummary && (
+ <Text className={styles.sub} fontSize={11} type={'secondary'}>
+ {topic.historySummary}
+ </Text>
+ )}
+ </div>
+ <div className={styles.cell}>
+ {projectLabel ? (
+ <Tag bordered={false} icon={<Icon icon={FolderIcon} size={11} />} size={'small'}>
+ {projectLabel}
+ </Tag>
+ ) : (
+ <Text fontSize={12} type={'secondary'}>
+ —
+ </Text>
+ )}
+ </div>
+ <StatusDot status={status} />
+ <Text fontSize={12} type={'secondary'}>
+ {triggerLabel}
+ </Text>
+ <Text
+ fontSize={12}
+ style={{ color: cssVar.colorTextQuaternary, textAlign: 'end' }}
+ title={updatedAt.title}
+ >
+ {updatedAt.text}
+ </Text>
+ <DropdownMenu items={dropdownMenu}>
+ <ActionIcon icon={MoreHorizontal} size={'small'} onClick={(e) => e.stopPropagation()} />
+ </DropdownMenu>
+ </div>
+ );
+});
+
+Row.displayName = 'AgentTopicManagerRow';
+
+const TopicListView = memo<TopicListViewProps>(({ groups, agentId, showGroupTitles, groupBy }) => {
+ const { t } = useTranslation('topic');
+
+ const selectedIds = useTopicsViewStore((s) => s.selectedIds);
+ const selectMode = useTopicsViewStore((s) => s.selectMode);
+ const selectAll = useTopicsViewStore((s) => s.selectAll);
+ const clearSelected = useTopicsViewStore((s) => s.clearSelected);
+ const toggleSelectMode = useTopicsViewStore((s) => s.toggleSelectMode);
+
+ const allIds = groups.flatMap((g) => g.children.map((c) => c.id));
+ const selectedSet = new Set(selectedIds);
+ const selectedInListCount = allIds.reduce((acc, id) => acc + (selectedSet.has(id) ? 1 : 0), 0);
+ const allSelected = allIds.length > 0 && selectedInListCount === allIds.length;
+ const someSelected = selectedInListCount > 0 && !allSelected;
+
+ const handleSelectAll = () => {
+ if (allSelected) {
+ clearSelected();
+ } else {
+ if (!selectMode) toggleSelectMode();
+ selectAll(allIds);
+ }
+ };
+
+ return (
+ <div className={styles.list}>
+ <div className={styles.header}>
+ <Checkbox
+ checked={allSelected}
+ classNames={{ checkbox: styles.checkboxBox }}
+ indeterminate={someSelected}
+ size={18}
+ onChange={handleSelectAll}
+ />
+ <span>{t('management.columns.title')}</span>
+ <span>{t('management.columns.project')}</span>
+ <span>{t('management.columns.status')}</span>
+ <span>{t('management.columns.trigger')}</span>
+ <span className={styles.headerCellEnd}>{t('management.columns.updated')}</span>
+ <span />
+ </div>
+ {groups.map((group) => {
+ if (group.children.length === 0) return null;
+ const title =
+ groupBy === 'byProject'
+ ? getProjectGroupTitle(group.id, group.title, t)
+ : group.title || getTimeGroupTitle(group.id, t);
+ return (
+ <Fragment key={group.id}>
+ {showGroupTitles && (
+ <div className={styles.groupBar}>
+ <span>{title}</span>
+ <span className={styles.groupCount}>{group.children.length}</span>
+ </div>
+ )}
+ {group.children.map((topic) => (
+ <Row agentId={agentId} key={topic.id} topic={topic} />
+ ))}
+ </Fragment>
+ );
+ })}
+ </div>
+ );
+});
+
+TopicListView.displayName = 'AgentTopicManagerListView';
+
+export default TopicListView;
diff --git a/src/features/AgentTopicManager/index.tsx b/src/features/AgentTopicManager/index.tsx
new file mode 100644
index 00000000000..e0e9584c67d
--- /dev/null
+++ b/src/features/AgentTopicManager/index.tsx
@@ -0,0 +1,268 @@
+'use client';
+
+import { groupTopicsByProject, groupTopicsByUpdatedTime } from '@lobechat/utils/client/topic';
+import { Flexbox, Skeleton } from '@lobehub/ui';
+import { memo, useEffect, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { shinyTextStyles } from '@/styles/loading';
+import type { ChatTopic } from '@/types/topic';
+
+import BulkActionBar from './BulkActionBar';
+import EmptyState from './EmptyState';
+import Header from './Header';
+import { useTopicsViewStore } from './store';
+import Toolbar from './Toolbar';
+import TopicGrid from './TopicGrid';
+import TopicListView from './TopicListView';
+import {
+ getProjectLabel,
+ matchesGroup,
+ matchesStatus,
+ matchesTimeRange,
+ matchesTrigger,
+ sortTopics,
+} from './utils';
+
+// Start small so users see infinite scroll kick in; each scroll-to-bottom
+// triggers `loadMoreTopics` which appends another page into `topicDataMap`.
+const PAGE_SIZE = 30;
+
+const AgentTopicManager = memo(() => {
+ const { t } = useTranslation('topic');
+ const activeAgentId = useChatStore((s) => s.activeAgentId);
+ // Use the management page's dedicated SWR pipeline so the heavier
+ // `withDetails` fetch doesn't share a bucket with the sidebar's cheap
+ // fetch (the shared bucket let whichever response landed last clobber the
+ // other).
+ const useFetchAgentTopicsView = useChatStore((s) => s.useFetchAgentTopicsView);
+ const useSearchTopics = useChatStore((s) => s.useSearchTopics);
+ const loadMoreAgentTopicsView = useChatStore((s) => s.loadMoreAgentTopicsView);
+
+ // Read directly from the view's topic map so `loadMore` appends are visible
+ // here without waiting for SWR revalidation.
+ const allTopics = useChatStore(topicSelectors.agentTopicsViewTopics);
+ const hasMore = useChatStore(topicSelectors.agentTopicsViewHasMore);
+ const isLoadingMore = useChatStore(topicSelectors.agentTopicsViewIsLoadingMore);
+
+ const reset = useTopicsViewStore((s) => s.reset);
+ const search = useTopicsViewStore((s) => s.search);
+ const status = useTopicsViewStore((s) => s.status);
+ const groupIds = useTopicsViewStore((s) => s.groupIds);
+ const triggers = useTopicsViewStore((s) => s.triggers);
+ const timeRange = useTopicsViewStore((s) => s.timeRange);
+ const sortBy = useTopicsViewStore((s) => s.sortBy);
+ const groupBy = useTopicsViewStore((s) => s.groupBy);
+ const viewMode = useTopicsViewStore((s) => s.viewMode);
+ const setStatus = useTopicsViewStore((s) => s.setStatus);
+ const setGroupIds = useTopicsViewStore((s) => s.setGroupIds);
+ const setTriggers = useTopicsViewStore((s) => s.setTriggers);
+ const setTimeRange = useTopicsViewStore((s) => s.setTimeRange);
+ const setSearch = useTopicsViewStore((s) => s.setSearch);
+
+ // Reset whenever the agent context switches AND on unmount. The route
+ // `/agent/:aid/topics` reuses the same component instance across agent
+ // navigations, so an unmount-only cleanup would let `selectedIds` (and
+ // other view state) from the previous agent persist into the next one —
+ // which would mean a bulk Delete/Archive/Favorite click silently targets
+ // stale IDs from another agent.
+ useEffect(() => {
+ reset();
+ }, [activeAgentId, reset]);
+
+ const { isLoading } = useFetchAgentTopicsView(true, {
+ agentId: activeAgentId,
+ pageSize: PAGE_SIZE,
+ // Opt into the heavier card-detail columns (firstUserMessage,
+ // messageCount, cost, tokenUsage, description, trigger). Sidebar paths
+ // omit this so their query stays cheap.
+ withDetails: true,
+ });
+
+ const trimmedSearch = search.trim();
+ const { data: searchResults } = useSearchTopics(
+ trimmedSearch.length > 0 ? trimmedSearch : undefined,
+ { agentId: activeAgentId },
+ );
+
+ const baseTopics: ChatTopic[] = useMemo(() => {
+ if (trimmedSearch.length > 0) return searchResults ?? [];
+ return allTopics ?? [];
+ }, [trimmedSearch, searchResults, allTopics]);
+
+ // Pool with every filter EXCEPT status applied. Reused for the final
+ // filtered list AND for the per-status count badges so each tab shows
+ // "what you'd see if you switched here with the same other filters".
+ const preStatusPool = useMemo(
+ () =>
+ baseTopics.filter(
+ (t) =>
+ matchesGroup(t, groupIds) &&
+ matchesTrigger(t, triggers) &&
+ matchesTimeRange(t, timeRange),
+ ),
+ [baseTopics, groupIds, triggers, timeRange],
+ );
+
+ const filtered = useMemo(() => {
+ const out = preStatusPool.filter((t) => matchesStatus(t, status));
+ return sortTopics(out, sortBy);
+ }, [preStatusPool, status, sortBy]);
+
+ const statusCounts = useMemo(
+ () => ({
+ active: preStatusPool.filter((t) => matchesStatus(t, 'active')).length,
+ all: preStatusPool.length,
+ // 'archived' has no visible tab today, but StatusFilter still includes it
+ // — count it so the Record satisfies the type for any future tab.
+ archived: preStatusPool.filter((t) => matchesStatus(t, 'archived')).length,
+ completed: preStatusPool.filter((t) => matchesStatus(t, 'completed')).length,
+ running: preStatusPool.filter((t) => matchesStatus(t, 'running')).length,
+ }),
+ [preStatusPool],
+ );
+
+ // Search results are flat — grouping by time confuses the relevance order
+ // returned by the BM25 keyword search.
+ const isSearchMode = trimmedSearch.length > 0;
+ const useGroups = groupBy !== 'none' && !isSearchMode;
+
+ const renderGroups = useMemo(() => {
+ if (!useGroups) return [{ children: filtered, id: 'all' }];
+ if (groupBy === 'byProject') {
+ const field: 'createdAt' | 'updatedAt' = sortBy === 'createdAt' ? 'createdAt' : 'updatedAt';
+ return groupTopicsByProject(filtered, field);
+ }
+ return groupTopicsByUpdatedTime(filtered);
+ }, [filtered, useGroups, groupBy, sortBy]);
+
+ const projects = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const t of baseTopics) {
+ const wd = t.metadata?.workingDirectory;
+ if (wd && !map.has(wd)) {
+ map.set(wd, getProjectLabel(t) ?? wd);
+ }
+ }
+ return Array.from(map, ([value, label]) => ({ label, value }));
+ }, [baseTopics]);
+
+ const totalAfterFilter = filtered.length;
+ // 'active' is the default tab, so it doesn't count as a user-applied filter
+ const hasActiveFilters =
+ (status !== 'active' && status !== 'all') ||
+ groupIds.length > 0 ||
+ triggers.length > 0 ||
+ timeRange !== 'all' ||
+ trimmedSearch.length > 0;
+
+ const clearFilters = () => {
+ // "Clear filters" jumps to All so users can confirm there really is no
+ // matching topic in the entire dataset; the default Active landing is
+ // only for first visits.
+ setStatus('all');
+ setGroupIds([]);
+ setTriggers([]);
+ setTimeRange('all');
+ setSearch('');
+ };
+
+ // Infinite scroll — observe a sentinel near the end of the list. We pass
+ // the scroll container as the IntersectionObserver `root` so detection is
+ // tied to the in-page scroll position, not the window viewport (otherwise
+ // a tall window can leave the sentinel "always intersecting" or never
+ // intersecting, depending on layout).
+ const scrollContainerRef = useRef<HTMLDivElement>(null);
+ const sentinelRef = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ if (isSearchMode) return;
+ const root = scrollContainerRef.current;
+ const sentinel = sentinelRef.current;
+ if (!root || !sentinel) return;
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ if (entry.isIntersecting && hasMore && !isLoadingMore) {
+ void loadMoreAgentTopicsView();
+ }
+ },
+ { root, rootMargin: '300px' },
+ );
+ observer.observe(sentinel);
+ return () => observer.disconnect();
+ }, [hasMore, isLoadingMore, isSearchMode, loadMoreAgentTopicsView]);
+
+ if (!activeAgentId) return <Loading debugId="AgentTopicManager" />;
+
+ return (
+ <Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
+ <Header agentId={activeAgentId} />
+ <div
+ ref={scrollContainerRef}
+ style={{
+ display: 'flex',
+ flex: 1,
+ flexDirection: 'column',
+ minWidth: 0,
+ overflowY: 'auto',
+ padding: '20px 24px',
+ }}
+ >
+ <Flexbox
+ gap={16}
+ style={{
+ marginInline: 'auto',
+ maxWidth: 1440,
+ width: '100%',
+ }}
+ >
+ <Toolbar projects={projects} statusCounts={statusCounts} />
+ <BulkActionBar />
+ {isLoading && baseTopics.length === 0 ? (
+ <Skeleton active paragraph={{ rows: 6 }} title={false} />
+ ) : totalAfterFilter === 0 ? (
+ <EmptyState
+ agentId={activeAgentId}
+ hasFilters={hasActiveFilters}
+ onClearFilters={clearFilters}
+ />
+ ) : (
+ <>
+ {viewMode === 'card' ? (
+ <TopicGrid
+ agentId={activeAgentId}
+ groupBy={groupBy}
+ groups={renderGroups}
+ showGroupTitles={useGroups}
+ />
+ ) : (
+ <TopicListView
+ agentId={activeAgentId}
+ groupBy={groupBy}
+ groups={renderGroups}
+ showGroupTitles={useGroups}
+ />
+ )}
+ {!isSearchMode && hasMore && (
+ <div aria-hidden ref={sentinelRef} style={{ height: 1 }} />
+ )}
+ {!isSearchMode && isLoadingMore && (
+ <Flexbox align={'center'} paddingBlock={12}>
+ <span className={shinyTextStyles.shinyText} style={{ fontSize: 12 }}>
+ {t('management.loadingMore')}
+ </span>
+ </Flexbox>
+ )}
+ </>
+ )}
+ </Flexbox>
+ </div>
+ </Flexbox>
+ );
+});
+
+AgentTopicManager.displayName = 'AgentTopicManager';
+
+export default AgentTopicManager;
diff --git a/src/features/AgentTopicManager/store.ts b/src/features/AgentTopicManager/store.ts
new file mode 100644
index 00000000000..78cbd8d857a
--- /dev/null
+++ b/src/features/AgentTopicManager/store.ts
@@ -0,0 +1,77 @@
+import { create } from 'zustand';
+
+import type {
+ GroupBy,
+ SortBy,
+ StatusFilter,
+ TimeRangeFilter,
+ TriggerFilter,
+ ViewMode,
+} from './types';
+
+interface TopicsViewState {
+ groupBy: GroupBy;
+ groupIds: string[];
+ search: string;
+ selectedIds: string[];
+ selectMode: boolean;
+ sortBy: SortBy;
+ status: StatusFilter;
+ timeRange: TimeRangeFilter;
+ triggers: TriggerFilter[];
+ viewMode: ViewMode;
+}
+
+interface TopicsViewActions {
+ clearSelected: () => void;
+ exitSelectMode: () => void;
+ reset: () => void;
+ selectAll: (ids: string[]) => void;
+ setGroupBy: (groupBy: GroupBy) => void;
+ setGroupIds: (groupIds: string[]) => void;
+ setSearch: (search: string) => void;
+ setSortBy: (sortBy: SortBy) => void;
+ setStatus: (status: StatusFilter) => void;
+ setTimeRange: (range: TimeRangeFilter) => void;
+ setTriggers: (triggers: TriggerFilter[]) => void;
+ setViewMode: (mode: ViewMode) => void;
+ toggleSelected: (id: string) => void;
+ toggleSelectMode: () => void;
+}
+
+const initialState: TopicsViewState = {
+ groupBy: 'byTime',
+ groupIds: [],
+ search: '',
+ selectMode: false,
+ selectedIds: [],
+ sortBy: 'updatedAt',
+ status: 'active',
+ timeRange: 'all',
+ triggers: ['chat'],
+ viewMode: 'card',
+};
+
+export const useTopicsViewStore = create<TopicsViewState & TopicsViewActions>((set) => ({
+ ...initialState,
+ clearSelected: () => set({ selectedIds: [] }),
+ exitSelectMode: () => set({ selectMode: false, selectedIds: [] }),
+ reset: () => set(initialState),
+ selectAll: (ids) => set({ selectedIds: ids }),
+ setGroupBy: (groupBy) => set({ groupBy }),
+ setGroupIds: (groupIds) => set({ groupIds }),
+ setSearch: (search) => set({ search }),
+ setSortBy: (sortBy) => set({ sortBy }),
+ setStatus: (status) => set({ status }),
+ setTimeRange: (timeRange) => set({ timeRange }),
+ setTriggers: (triggers) => set({ triggers }),
+ setViewMode: (viewMode) => set({ viewMode }),
+ toggleSelectMode: () =>
+ set((s) => ({ selectMode: !s.selectMode, selectedIds: s.selectMode ? [] : s.selectedIds })),
+ toggleSelected: (id) =>
+ set((s) => ({
+ selectedIds: s.selectedIds.includes(id)
+ ? s.selectedIds.filter((x) => x !== id)
+ : [...s.selectedIds, id],
+ })),
+}));
diff --git a/src/features/AgentTopicManager/types.ts b/src/features/AgentTopicManager/types.ts
new file mode 100644
index 00000000000..c7de4fa691b
--- /dev/null
+++ b/src/features/AgentTopicManager/types.ts
@@ -0,0 +1,11 @@
+export type ViewMode = 'card' | 'list';
+
+export type StatusFilter = 'all' | 'active' | 'running' | 'completed' | 'archived';
+
+export type TriggerFilter = 'chat' | 'api' | 'task' | 'eval';
+
+export type TimeRangeFilter = 'all' | 'today' | 'week' | 'month';
+
+export type SortBy = 'updatedAt' | 'createdAt' | 'title';
+
+export type GroupBy = 'byProject' | 'byTime' | 'none';
diff --git a/src/features/AgentTopicManager/utils.ts b/src/features/AgentTopicManager/utils.ts
new file mode 100644
index 00000000000..aaab8ce77f1
--- /dev/null
+++ b/src/features/AgentTopicManager/utils.ts
@@ -0,0 +1,129 @@
+import dayjs from 'dayjs';
+
+import type { ChatTopic } from '@/types/topic';
+
+import type { SortBy, StatusFilter, TimeRangeFilter, TriggerFilter } from './types';
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+export const matchesStatus = (topic: ChatTopic, status: StatusFilter): boolean => {
+ switch (status) {
+ case 'all': {
+ return true;
+ }
+ case 'archived': {
+ return topic.status === 'archived';
+ }
+ case 'completed': {
+ return topic.status === 'completed';
+ }
+ case 'running': {
+ return topic.status === 'running';
+ }
+ case 'active': {
+ return !topic.status || topic.status === 'active';
+ }
+ default: {
+ return true;
+ }
+ }
+};
+
+export const matchesGroup = (topic: ChatTopic, groupIds: string[]): boolean => {
+ if (groupIds.length === 0) return true;
+ // ChatTopic doesn't surface groupId on the client type; fall back to metadata.workingDirectory
+ // as the project bucket key (matches sidebar ByProjectMode).
+ const project = topic.metadata?.workingDirectory ?? '';
+ return groupIds.includes(project);
+};
+
+export const matchesTrigger = (topic: ChatTopic, triggers: TriggerFilter[]): boolean => {
+ if (triggers.length === 0) return true;
+ const effective: TriggerFilter = (topic.trigger as TriggerFilter | null | undefined) ?? 'chat';
+ return triggers.includes(effective);
+};
+
+export const matchesTimeRange = (topic: ChatTopic, range: TimeRangeFilter): boolean => {
+ if (range === 'all') return true;
+ const updated = topic.updatedAt ? new Date(topic.updatedAt).getTime() : 0;
+ if (!updated) return false;
+ const now = Date.now();
+ const diff = now - updated;
+ switch (range) {
+ case 'today': {
+ return diff < DAY_MS;
+ }
+ case 'week': {
+ return diff < 7 * DAY_MS;
+ }
+ case 'month': {
+ return diff < 30 * DAY_MS;
+ }
+ default: {
+ return true;
+ }
+ }
+};
+
+export const sortTopics = (topics: ChatTopic[], sortBy: SortBy): ChatTopic[] => {
+ const sorted = [...topics];
+ switch (sortBy) {
+ case 'updatedAt': {
+ sorted.sort(
+ (a, b) => new Date(b.updatedAt ?? 0).getTime() - new Date(a.updatedAt ?? 0).getTime(),
+ );
+ break;
+ }
+ case 'createdAt': {
+ sorted.sort(
+ (a, b) => new Date(b.createdAt ?? 0).getTime() - new Date(a.createdAt ?? 0).getTime(),
+ );
+ break;
+ }
+ case 'title': {
+ sorted.sort((a, b) => (a.title ?? '').localeCompare(b.title ?? ''));
+ break;
+ }
+ }
+ return sorted;
+};
+
+export const getProjectLabel = (topic: ChatTopic): string | undefined => {
+ const wd = topic.metadata?.workingDirectory;
+ if (!wd) return undefined;
+ // Show last segment of path for readability
+ const parts = wd.split('/').filter(Boolean);
+ return parts.at(-1) ?? wd;
+};
+
+/**
+ * Resolve the human-readable title for a time-bucket group ID produced by
+ * `groupTopicsByUpdatedTime` (today / yesterday / week / month) or a dynamic
+ * year-month / year segment (e.g. `2025-04`, `2024`).
+ */
+// Accept any react-i18next TFunction shape — overloads make the strict type
+// finicky and we only need string → string here.
+type LooseT = (key: any) => any;
+
+export const getTimeGroupTitle = (id: string, t: LooseT): string => {
+ // Year-month like "2025-04" → localized month name; year-only like "2025" → as-is.
+ if (/^\d{4}/.test(id)) {
+ return id.includes('-') ? dayjs(id).format('MMMM') : id;
+ }
+ return t(`groupTitle.byTime.${id}`);
+};
+
+/**
+ * Resolve the human-readable title for a project-bucket group ID produced by
+ * `groupTopicsByProject` (`project:<workingDirectory>` or `no-project`).
+ */
+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:/, '');
+};
diff --git a/src/locales/default/topic.ts b/src/locales/default/topic.ts
index 7878fdc1d27..795bd423278 100644
--- a/src/locales/default/topic.ts
+++ b/src/locales/default/topic.ts
@@ -54,6 +54,81 @@ export default {
'inPopup.focus': 'Focus Popup Window',
'inPopup.title': 'Open in Popup Window',
'loadMore': 'Load More',
+ 'management.actions.newChat': 'New chat',
+ 'management.actions.select': 'Select',
+ 'management.actionsMenu.archiveStale.confirm':
+ 'Archive {{count}} topics that have been inactive for over 3 months? They will be marked as completed.',
+ 'management.actionsMenu.archiveStale.confirmOk': 'Archive',
+ 'management.actionsMenu.archiveStale.done': 'Archived {{count}} stale topics.',
+ 'management.actionsMenu.archiveStale.label': 'Archive topics inactive for 3+ months',
+ 'management.actionsMenu.archiveStale.noneFound': 'No stale topics found.',
+ 'management.actionsMenu.archiveStale.title': 'Archive stale topics?',
+ 'management.actionsMenu.autoSummarize.comingSoon':
+ 'Auto-summarization is coming soon — track on the roadmap.',
+ 'management.actionsMenu.autoSummarize.label': 'Auto-generate summaries for topics without one',
+ 'management.actionsMenu.title': 'More actions',
+ 'management.bulk.archive': 'Archive',
+ 'management.bulk.cancel': 'Cancel',
+ 'management.bulk.delete': 'Delete',
+ 'management.bulk.deleteConfirm':
+ 'You are about to delete {{count}} topics. This action cannot be undone.',
+ 'management.bulk.deleteTitle': 'Delete topics?',
+ 'management.bulk.favorite': 'Favorite',
+ 'management.bulk.selectedCount_one': '{{count}} selected',
+ 'management.bulk.selectedCount_other': '{{count}} selected',
+ 'management.card.noPreview': 'No preview available',
+ 'management.columns.project': 'Project',
+ 'management.columns.status': 'Status',
+ 'management.columns.title': 'Title',
+ 'management.columns.trigger': 'Trigger',
+ 'management.columns.updated': 'Updated',
+ 'management.empty.filtered.action': 'Clear filters',
+ 'management.empty.filtered.desc': 'Try adjusting filters or clearing them to see more topics.',
+ 'management.empty.filtered.title': 'No topics match these filters',
+ 'management.empty.noTopics.action': 'Start new chat',
+ 'management.empty.noTopics.desc':
+ 'Start a conversation with this agent to create your first topic.',
+ 'management.empty.noTopics.title': 'No topics yet',
+ 'management.filters.project.empty': 'No projects',
+ 'management.filters.project.label': 'Project',
+ 'management.filters.status.active': 'Active',
+ 'management.filters.status.all': 'All',
+ 'management.filters.status.archived': 'Archived',
+ 'management.filters.status.completed': 'Completed',
+ 'management.filters.status.running': 'Running',
+ 'management.filters.status.favorite': 'Favorites',
+ 'management.filters.time.all': 'All time',
+ 'management.filters.time.label': 'Time',
+ 'management.filters.time.month': 'Past month',
+ 'management.filters.time.today': 'Today',
+ 'management.filters.time.week': 'Past week',
+ 'management.filters.trigger.api': 'API',
+ 'management.filters.trigger.chat': 'Chat',
+ 'management.filters.trigger.eval': 'Eval',
+ 'management.filters.trigger.label': 'Trigger',
+ 'management.filters.trigger.task': 'Task',
+ 'management.group.byProject': 'By project',
+ 'management.group.byTime': 'By time',
+ 'management.group.label': 'Group',
+ 'management.group.none': 'None',
+ 'management.group.noProject': 'No project',
+ 'management.loadingMore': 'Loading more topics…',
+ 'management.searchPlaceholder': "Search this agent's topics…",
+ 'management.sidebarEntry': 'Topics',
+ 'management.sort.createdAt': 'Created time',
+ 'management.sort.label': 'Sort',
+ 'management.sort.title': 'Title',
+ 'management.sort.updatedAt': 'Updated time',
+ 'management.status.active': 'Active',
+ 'management.status.archived': 'Archived',
+ 'management.status.completed': 'Completed',
+ 'management.status.failed': 'Failed',
+ 'management.status.paused': 'Paused',
+ 'management.status.running': 'Running',
+ 'management.status.waitingForHuman': 'Awaiting input',
+ 'management.title': 'Topics',
+ 'management.view.card': 'Card',
+ 'management.view.list': 'List',
'newTopic': 'New Topic',
'renameModal.description': 'Keep it short and easy to recognize.',
'renameModal.title': 'Rename Topic',
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
index 6a181002a59..abe91e9b1c5 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
@@ -27,6 +27,7 @@ vi.mock('@lobehub/ui/icons', () => ({
vi.mock('lucide-react', () => ({
MessageSquarePlusIcon: () => null,
+ MessagesSquareIcon: () => null,
RadioTowerIcon: () => null,
SearchIcon: () => null,
}));
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
index 43c8cdf0fc9..5cf40e7bc12 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
@@ -2,7 +2,12 @@
import { Flexbox } from '@lobehub/ui';
import { BotPromptIcon } from '@lobehub/ui/icons';
-import { MessageSquarePlusIcon, RadioTowerIcon, SearchIcon } from 'lucide-react';
+import {
+ MessageSquarePlusIcon,
+ MessagesSquareIcon,
+ RadioTowerIcon,
+ SearchIcon,
+} from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
@@ -26,6 +31,9 @@ const Nav = memo(() => {
const pathname = usePathname();
const isProfileActive = pathname.includes('/profile');
const isChannelActive = pathname.includes('/channel');
+ // Topic IDs are prefixed `topics_`, so /agent/:aid/topics_abc would also match
+ // pathname.includes('/topics') — anchor to end to avoid that false positive.
+ const isTopicsActive = pathname.endsWith('/topics');
const router = useQueryRoute();
const { isAgentEditable } = useServerConfigStore(featureFlagsSelectors);
const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
@@ -75,6 +83,15 @@ const Nav = memo(() => {
}}
/>
)}
+ <NavItem
+ active={isTopicsActive}
+ icon={MessagesSquareIcon}
+ title={tTopic('management.sidebarEntry')}
+ onClick={() => {
+ switchTopic(null, { skipRefreshMessage: true });
+ router.push(urlJoin('/agent', agentId!, 'topics'));
+ }}
+ />
{!hideChannel && (
<NavItem
active={isChannelActive}
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx
index 0667fe8eda7..54083e9e08a 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx
@@ -5,6 +5,8 @@ import isEqual from 'fast-deep-equal';
import { MoreHorizontal } from 'lucide-react';
import React, { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import urlJoin from 'url-join';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
@@ -19,17 +21,19 @@ import TopicItem from '../../List/Item';
const FlatMode = memo(() => {
const { t } = useTranslation('topic');
+ const navigate = useNavigate();
const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
const topicSortBy = useUserStore(preferenceSelectors.topicSortBy);
- const [activeTopicId, activeThreadId, hasMore, isExpandingPageSize, openAllTopicsDrawer] =
- useChatStore((s) => [
+ const [activeTopicId, activeThreadId, hasMore, isExpandingPageSize, activeAgentId] = useChatStore(
+ (s) => [
s.activeTopicId,
s.activeThreadId,
topicSelectors.hasMoreTopicsForSidebar(s),
topicSelectors.isExpandingPageSize(s),
- s.openAllTopicsDrawer,
- ]);
+ s.activeAgentId,
+ ],
+ );
const activeTopicList = useChatStore(
topicSelectors.displayTopicsForSidebar(topicPageSize, topicSortBy),
@@ -51,8 +55,12 @@ const FlatMode = memo(() => {
/>
))}
{isExpandingPageSize && <SkeletonList rows={3} />}
- {hasMore && !isExpandingPageSize && (
- <NavItem icon={MoreHorizontal} title={t('loadMore')} onClick={openAllTopicsDrawer} />
+ {hasMore && !isExpandingPageSize && activeAgentId && (
+ <NavItem
+ icon={MoreHorizontal}
+ title={t('loadMore')}
+ onClick={() => navigate(urlJoin('/agent', activeAgentId, 'topics'))}
+ />
)}
</Flexbox>
);
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/GroupedAccordion.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/GroupedAccordion.tsx
index 517fd539597..d9e0b70b4a3 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/GroupedAccordion.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/GroupedAccordion.tsx
@@ -5,6 +5,8 @@ import isEqual from 'fast-deep-equal';
import { MoreHorizontal } from 'lucide-react';
import { type ComponentType, memo, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useNavigate } from 'react-router-dom';
+import urlJoin from 'url-join';
import NavItem from '@/features/NavPanel/components/NavItem';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
@@ -30,14 +32,15 @@ interface GroupedAccordionProps {
const GroupedAccordion = memo<GroupedAccordionProps>(({ GroupItem }) => {
const { t } = useTranslation('topic');
+ const navigate = useNavigate();
const topicPageSize = useGlobalStore(systemStatusSelectors.topicPageSize);
const topicSortBy = useUserStore(preferenceSelectors.topicSortBy);
const { topicGroupMode } = useAgentTopicGroupMode();
- const [hasMore, isExpandingPageSize, openAllTopicsDrawer] = useChatStore((s) => [
+ const [hasMore, isExpandingPageSize, activeAgentId] = useChatStore((s) => [
topicSelectors.hasMoreTopicsForSidebar(s),
topicSelectors.isExpandingPageSize(s),
- s.openAllTopicsDrawer,
+ s.activeAgentId,
]);
const [activeTopicId, activeThreadId] = useChatStore((s) => [s.activeTopicId, s.activeThreadId]);
@@ -78,8 +81,12 @@ const GroupedAccordion = memo<GroupedAccordionProps>(({ GroupItem }) => {
))}
</Accordion>
{isExpandingPageSize && <SkeletonList rows={3} />}
- {hasMore && !isExpandingPageSize && (
- <NavItem icon={MoreHorizontal} title={t('loadMore')} onClick={openAllTopicsDrawer} />
+ {hasMore && !isExpandingPageSize && activeAgentId && (
+ <NavItem
+ icon={MoreHorizontal}
+ title={t('loadMore')}
+ onClick={() => navigate(urlJoin('/agent', activeAgentId, 'topics'))}
+ />
)}
</Flexbox>
);
diff --git a/src/routes/(main)/agent/topics/index.tsx b/src/routes/(main)/agent/topics/index.tsx
new file mode 100644
index 00000000000..cb2da97b907
--- /dev/null
+++ b/src/routes/(main)/agent/topics/index.tsx
@@ -0,0 +1,14 @@
+'use client';
+
+import { memo, Suspense } from 'react';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import AgentTopicManager from '@/features/AgentTopicManager';
+
+const AgentTopicsPage = memo(() => (
+ <Suspense fallback={<Loading debugId="AgentTopicManager" />}>
+ <AgentTopicManager />
+ </Suspense>
+));
+
+export default AgentTopicsPage;
diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
index 711a4bc4163..bda2384a787 100644
--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx
@@ -7,7 +7,7 @@ import { Loader2, PinIcon } from 'lucide-react';
import { type CSSProperties, type DragEvent } from 'react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router-dom';
+import { Link, useLocation } from 'react-router-dom';
import NavItem from '@/features/NavPanel/components/NavItem';
import { usePrefetchAgent } from '@/hooks/usePrefetchAgent';
@@ -21,6 +21,10 @@ import Actions from '../Item/Actions';
import Avatar from './Avatar';
import { useAgentDropdownMenu } from './useDropdownMenu';
+// Sub-routes that are agent-scoped views (not tied to a specific topic/task id),
+// safe to carry over when switching between agents from the sidebar switcher.
+const PRESERVED_AGENT_SUB_PATHS = new Set(['topics', 'profile', 'channel']);
+
const styles = createStaticStyles(({ css, cssVar }) => ({
badge: css`
pointer-events: none;
@@ -115,8 +119,19 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate })
displayTitle
);
- // Get URL for this agent
- const agentUrl = SESSION_CHAT_URL(id, false);
+ // Get URL for this agent — when switching from within an agent's sub-view
+ // (e.g. /agent/A/topics), preserve the sub-route on the new agent so users
+ // don't lose their place. Only safe for agent-scoped views; topic/task ids
+ // belong to the previous agent and must not be carried over.
+ const { pathname } = useLocation();
+ const agentUrl = useMemo(() => {
+ const match = pathname.match(/^\/agent\/[^/]+\/([^/]+)\/?$/);
+ const subPath = match?.[1];
+ if (subPath && PRESERVED_AGENT_SUB_PATHS.has(subPath)) {
+ return `/agent/${id}/${subPath}`;
+ }
+ return SESSION_CHAT_URL(id, false);
+ }, [id, pathname]);
// Memoize event handlers
const handleMouseEnter = useCallback(() => {
diff --git a/src/server/routers/lambda/topic.ts b/src/server/routers/lambda/topic.ts
index c5f5f96cbd8..fe58e234809 100644
--- a/src/server/routers/lambda/topic.ts
+++ b/src/server/routers/lambda/topic.ts
@@ -237,6 +237,12 @@ export const topicRouter = router({
pageSize: z.number().max(100).optional(),
sessionId: z.string().nullable().optional(),
triggers: z.array(z.string()).optional(),
+ /**
+ * When true, returns extra card-detail columns (firstUserMessage,
+ * messageCount, cost, tokenUsage, description, trigger). Default false
+ * so the sidebar list stays cheap — only the management page opts in.
+ */
+ withDetails: z.boolean().optional(),
}),
)
.query(async ({ input, ctx }) => {
diff --git a/src/services/topic/index.ts b/src/services/topic/index.ts
index c6455de4f39..cd896d59a7b 100644
--- a/src/services/topic/index.ts
+++ b/src/services/topic/index.ts
@@ -51,6 +51,7 @@ export class TopicService {
isInbox: params.isInbox,
pageSize: params.pageSize,
triggers: params.triggers,
+ withDetails: params.withDetails,
}) as any;
};
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index 2f58dec9252..c7ebd120728 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -37,6 +37,7 @@ import { agentTopicPageRouteMeta } from '@/routes/(main)/agent/features/topicPag
import AgentPageRedirectPage from '@/routes/(main)/agent/page';
import AgentProfilePage from '@/routes/(main)/agent/profile';
import AgentTaskDetailRoute from '@/routes/(main)/agent/task/[taskId]';
+import AgentTopicsPage from '@/routes/(main)/agent/topics';
import CommunityLayout from '@/routes/(main)/community/_layout';
import CommunityDetailLayout from '@/routes/(main)/community/(detail)/_layout';
import CommunityDetailAgentPage from '@/routes/(main)/community/(detail)/agent';
@@ -159,6 +160,10 @@ export const desktopRoutes: RouteObject[] = [
element: <AgentChannelPage />,
path: 'channel',
},
+ {
+ element: <AgentTopicsPage />,
+ path: 'topics',
+ },
{
element: <AgentTaskDetailRoute />,
handle: { meta: taskRouteMeta },
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index dbdc6b5adf5..1c63f862e55 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -104,6 +104,13 @@ export const desktopRoutes: RouteObject[] = [
),
path: 'channel',
},
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/topics'),
+ 'Desktop > Chat > Topics',
+ ),
+ path: 'topics',
+ },
{
element: dynamicElement(
() => import('@/routes/(main)/agent/task/[taskId]'),
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index d99549edce4..f59138a8ef8 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -33,6 +33,7 @@ import { topicSelectors } from './selectors';
const n = setNamespace('t');
const SWR_USE_FETCH_TOPIC = 'SWR_USE_FETCH_TOPIC';
+const SWR_USE_FETCH_AGENT_TOPICS_VIEW = 'SWR_USE_FETCH_AGENT_TOPICS_VIEW';
const SWR_USE_SEARCH_TOPIC = 'SWR_USE_SEARCH_TOPIC';
type CronTopicsGroupWithJobInfo = {
cronJob: unknown;
@@ -374,6 +375,7 @@ export class ChatTopicActionImpl {
groupId,
pageSize: customPageSize,
isInbox,
+ withDetails,
}: {
agentId?: string;
excludeStatuses?: string[];
@@ -381,6 +383,7 @@ export class ChatTopicActionImpl {
groupId?: string;
isInbox?: boolean;
pageSize?: number;
+ withDetails?: boolean;
} = {},
): SWRResponse<{ items: ChatTopic[]; total: number }> => {
const pageSize = customPageSize || 20;
@@ -402,6 +405,7 @@ export class ChatTopicActionImpl {
pageSize,
...(effectiveExcludeTriggers ? { excludeTriggers: effectiveExcludeTriggers } : {}),
...(effectiveExcludeStatuses ? { excludeStatuses: effectiveExcludeStatuses } : {}),
+ ...(withDetails ? { withDetails: true } : {}),
},
]
: null,
@@ -429,6 +433,7 @@ export class ChatTopicActionImpl {
groupId,
isInbox,
pageSize,
+ withDetails,
});
// Reset expanding state after fetch completes
@@ -495,6 +500,7 @@ export class ChatTopicActionImpl {
items: nextItems,
pageSize,
total: totalCount,
+ withDetails,
},
},
},
@@ -506,6 +512,179 @@ export class ChatTopicActionImpl {
);
};
+ /**
+ * Topic fetch dedicated to the Agent Topics management page.
+ * Lives in its own SWR key + state bucket so the heavier `withDetails`
+ * payload doesn't collide with the sidebar's cheap fetch — sharing one
+ * bucket meant whichever response landed last clobbered the other.
+ */
+ useFetchAgentTopicsView = (
+ enable: boolean,
+ {
+ agentId,
+ pageSize: customPageSize,
+ withDetails,
+ }: {
+ agentId?: string;
+ pageSize?: number;
+ withDetails?: boolean;
+ } = {},
+ ): SWRResponse<{ items: ChatTopic[]; total: number }> => {
+ const pageSize = customPageSize || 30;
+ const containerKey = topicMapKey({ agentId });
+ const hasValidAgent = !!agentId;
+
+ return useClientDataSWRWithSync<{ items: ChatTopic[]; total: number }>(
+ enable && hasValidAgent
+ ? [
+ SWR_USE_FETCH_AGENT_TOPICS_VIEW,
+ containerKey,
+ { pageSize, ...(withDetails ? { withDetails: true } : {}) },
+ ]
+ : null,
+ async () => {
+ if (!agentId) return { items: [], total: 0 };
+
+ return topicService.getTopics({
+ agentId,
+ current: 0,
+ pageSize,
+ withDetails,
+ });
+ },
+ {
+ onData: (result) => {
+ if (!hasValidAgent) return;
+ const { items: topics, total: totalCount } = result;
+
+ const currentData = this.#get().agentTopicsViewMap[containerKey];
+
+ // Preserve appended pages on refresh — same convention as
+ // `useFetchTopics` so the user keeps their scroll position after
+ // an SWR revalidation.
+ const isRefreshingExpandedList =
+ !!currentData && currentData.currentPage > 0 && currentData.pageSize === pageSize;
+
+ const nextItems = isRefreshingExpandedList
+ ? (() => {
+ const visibleCount = Math.min(currentData.items.length, totalCount);
+ const topicIds = new Set(topics.map((item) => item.id));
+ return [
+ ...topics,
+ ...currentData.items.filter((topic) => !topicIds.has(topic.id)),
+ ].slice(0, visibleCount);
+ })()
+ : topics;
+
+ const hasMore = totalCount > nextItems.length;
+
+ if (
+ currentData &&
+ isEqual(nextItems, currentData.items) &&
+ currentData.total === totalCount
+ ) {
+ return;
+ }
+
+ this.#set(
+ {
+ agentTopicsViewMap: {
+ ...this.#get().agentTopicsViewMap,
+ [containerKey]: {
+ currentPage: isRefreshingExpandedList ? currentData.currentPage : 0,
+ hasMore,
+ isExpandingPageSize: false,
+ isLoadingMore: false,
+ items: nextItems,
+ pageSize,
+ total: totalCount,
+ withDetails,
+ },
+ },
+ },
+ false,
+ n('useFetchAgentTopicsView(onData)', { containerKey }),
+ );
+ },
+ },
+ );
+ };
+
+ loadMoreAgentTopicsView = async (): Promise<void> => {
+ const { activeAgentId, agentTopicsViewMap } = this.#get();
+ if (!activeAgentId) return;
+
+ const key = topicMapKey({ agentId: activeAgentId });
+ const currentData = agentTopicsViewMap[key];
+ if (!currentData || currentData.isLoadingMore) return;
+
+ const nextPage = (currentData.currentPage || 0) + 1;
+ const pageSize = currentData.pageSize;
+ const withDetails = currentData.withDetails;
+
+ this.#set(
+ {
+ agentTopicsViewMap: {
+ ...agentTopicsViewMap,
+ [key]: { ...currentData, isLoadingMore: true },
+ },
+ },
+ false,
+ n('loadMoreAgentTopicsView(start)'),
+ );
+
+ try {
+ const result = await topicService.getTopics({
+ agentId: activeAgentId,
+ current: nextPage,
+ pageSize,
+ withDetails,
+ });
+
+ const nextItems = [...currentData.items, ...result.items];
+ const hasMore = result.total > nextItems.length;
+
+ this.#set(
+ {
+ agentTopicsViewMap: {
+ ...this.#get().agentTopicsViewMap,
+ [key]: {
+ ...currentData,
+ currentPage: nextPage,
+ hasMore,
+ isLoadingMore: false,
+ items: nextItems,
+ total: result.total,
+ },
+ },
+ },
+ false,
+ n('loadMoreAgentTopicsView(success)'),
+ );
+ } catch {
+ this.#set(
+ {
+ agentTopicsViewMap: {
+ ...this.#get().agentTopicsViewMap,
+ [key]: { ...this.#get().agentTopicsViewMap[key]!, isLoadingMore: false },
+ },
+ },
+ false,
+ n('loadMoreAgentTopicsView(error)'),
+ );
+ }
+ };
+
+ refreshAgentTopicsView = async (): Promise<void> => {
+ const { activeAgentId } = this.#get();
+ if (!activeAgentId) return;
+ const containerKey = topicMapKey({ agentId: activeAgentId });
+ await mutate(
+ (key) =>
+ Array.isArray(key) && key[0] === SWR_USE_FETCH_AGENT_TOPICS_VIEW && key[1] === containerKey,
+ );
+ };
+
loadMoreTopics = async (): Promise<void> => {
const { activeAgentId, activeGroupId, topicDataMap } = this.#get();
const key = topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });
@@ -531,6 +710,10 @@ export class ChatTopicActionImpl {
const pageSize = useGlobalStore.getState().status.topicPageSize || 20;
const excludeTriggers = currentData?.excludeTriggers;
const excludeStatuses = currentData?.excludeStatuses;
+ // Carry `withDetails` from the initial fetch so subsequent pages have
+ // the same column shape — otherwise the management page would mix
+ // detail-rich rows with bare rows after scrolling.
+ const withDetails = currentData?.withDetails;
const result = await topicService.getTopics({
agentId: activeAgentId,
current: nextPage,
@@ -538,6 +721,7 @@ export class ChatTopicActionImpl {
excludeTriggers,
groupId: activeGroupId,
pageSize,
+ withDetails,
});
const currentTopics = currentData?.items || [];
@@ -558,6 +742,7 @@ export class ChatTopicActionImpl {
items: nextItems,
pageSize,
total: result.total,
+ withDetails,
},
},
},
@@ -744,12 +929,16 @@ export class ChatTopicActionImpl {
// Use topicMapKey to generate the same key used in useFetchTopics
// Key format: [SWR_USE_FETCH_TOPIC, containerKey, { isInbox, pageSize }]
const containerKey = topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });
+ const agentViewKey = activeAgentId ? topicMapKey({ agentId: activeAgentId }) : null;
await mutate(
(key) =>
Array.isArray(key) &&
- key[0] === SWR_USE_FETCH_TOPIC &&
- typeof key[1] === 'string' &&
- key[1] === containerKey,
+ ((key[0] === SWR_USE_FETCH_TOPIC &&
+ typeof key[1] === 'string' &&
+ key[1] === containerKey) ||
+ (key[0] === SWR_USE_FETCH_AGENT_TOPICS_VIEW &&
+ agentViewKey !== null &&
+ key[1] === agentViewKey)),
);
};
@@ -808,8 +997,18 @@ export class ChatTopicActionImpl {
const currentData = this.#get().topicDataMap[key];
const nextItems = topicReducer(currentData?.items, payload);
- // no need to update if is the same
- if (isEqual(nextItems, currentData?.items)) return;
+ // Mirror the optimistic update into the Agent Topics management page's
+ // bucket if it has been populated for the same key. Without this mirror,
+ // bulk actions (favorite/status/delete) on the management page would
+ // appear to do nothing until the SWR revalidation finished.
+ const viewMap = this.#get().agentTopicsViewMap;
+ const viewData = viewMap[key];
+ const nextViewItems = viewData ? topicReducer(viewData.items, payload) : undefined;
+ const viewChanged = viewData ? !isEqual(nextViewItems, viewData.items) : false;
+
+ // no need to update if both maps are unchanged
+ const mainChanged = !isEqual(nextItems, currentData?.items);
+ if (!mainChanged && !viewChanged) return;
const currentTotal = currentData?.total ?? currentData?.items?.length ?? 0;
const total =
@@ -819,23 +1018,42 @@ export class ChatTopicActionImpl {
? Math.max(nextItems.length, currentTotal - 1)
: currentTotal;
- this.#set(
- {
- topicDataMap: {
- ...this.#get().topicDataMap,
- [key]: {
- ...currentData,
- currentPage: currentData?.currentPage ?? 0,
- hasMore: total > nextItems.length,
- isInbox: currentData?.isInbox,
- items: nextItems,
- total,
- },
+ const nextState: Record<string, unknown> = {};
+
+ if (mainChanged) {
+ nextState.topicDataMap = {
+ ...this.#get().topicDataMap,
+ [key]: {
+ ...currentData,
+ currentPage: currentData?.currentPage ?? 0,
+ hasMore: total > nextItems.length,
+ isInbox: currentData?.isInbox,
+ items: nextItems,
+ total,
},
- },
- false,
- action ?? n(`dispatchTopic/${payload.type}`),
- );
+ };
+ }
+
+ if (viewChanged && viewData && nextViewItems) {
+ const viewTotal = viewData.total ?? viewData.items?.length ?? 0;
+ const viewNextTotal =
+ payload.type === 'addTopic'
+ ? viewTotal + 1
+ : payload.type === 'deleteTopic'
+ ? Math.max(nextViewItems.length, viewTotal - 1)
+ : viewTotal;
+ nextState.agentTopicsViewMap = {
+ ...viewMap,
+ [key]: {
+ ...viewData,
+ hasMore: viewNextTotal > nextViewItems.length,
+ items: nextViewItems,
+ total: viewNextTotal,
+ },
+ };
+ }
+
+ this.#set(nextState, false, action ?? n(`dispatchTopic/${payload.type}`));
};
internal_updateTopics = (
diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.ts
index d53e94729bc..19519060123 100644
--- a/src/store/chat/slices/topic/initialState.ts
+++ b/src/store/chat/slices/topic/initialState.ts
@@ -19,11 +19,25 @@ export interface TopicData {
*/
pageSize: number;
total: number;
+ /**
+ * Tracks whether the first fetch for this container asked the server for
+ * the heavier card-detail columns. `loadMoreTopics` reads it back so
+ * subsequent pages stay shape-consistent with the initial fetch.
+ */
+ withDetails?: boolean;
}
export interface ChatTopicState {
// TODO: need to add the null to the type
activeTopicId?: string;
+ /**
+ * Topic data map dedicated to the Agent Topics management page
+ * (`/agent/:aid/topics`). Kept separate from `topicDataMap` because the page
+ * fetches with `withDetails: true` and a larger page size, and otherwise it
+ * would share a bucket with the sidebar's cheap fetch — whichever response
+ * lands last wins, tangling both views.
+ */
+ agentTopicsViewMap: Record<string, TopicData>;
/**
* whether all topics drawer is open
*/
@@ -44,6 +58,7 @@ export interface ChatTopicState {
export const initialTopicState: ChatTopicState = {
activeTopicId: null as any,
+ agentTopicsViewMap: {},
allTopicsDrawerOpen: false,
creatingTopic: false,
isSearchingTopic: false,
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index ea72e709c7b..2ad77e31562 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -188,7 +188,26 @@ const isLoadingMoreTopics = (s: ChatStoreState): boolean =>
const isExpandingPageSize = (s: ChatStoreState): boolean =>
currentTopicData(s)?.isExpandingPageSize ?? false;
+// Selectors for the Agent Topics management page's dedicated bucket.
+// Always agent-scoped (no group), keyed by `agentId` via `topicMapKey`.
+const agentTopicsViewData = (s: ChatStoreState): TopicData | undefined => {
+ if (!s.activeAgentId) return undefined;
+ return s.agentTopicsViewMap[topicMapKey({ agentId: s.activeAgentId })];
+};
+
+const agentTopicsViewTopics = (s: ChatStoreState): ChatTopic[] =>
+ agentTopicsViewData(s)?.items ?? [];
+
+const agentTopicsViewHasMore = (s: ChatStoreState): boolean =>
+ agentTopicsViewData(s)?.hasMore ?? false;
+
+const agentTopicsViewIsLoadingMore = (s: ChatStoreState): boolean =>
+ agentTopicsViewData(s)?.isLoadingMore ?? false;
+
export const topicSelectors = {
+ agentTopicsViewHasMore,
+ agentTopicsViewIsLoadingMore,
+ agentTopicsViewTopics,
currentActiveTopic,
currentActiveTopicSummary,
currentTopicCount,