π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(topic): persist topic unread as a backend status (#16056)
Arvin Xuef09457e6327
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex b4e5b3ee389..51a101e2d61 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -1,4 +1,5 @@import {+ chatTopicStatusSchema,type RecentTopic,type RecentTopicGroup,type RecentTopicGroupMember,@@ -614,18 +615,7 @@ export const topicRouter = router({}).optional(),sessionId: z.string().optional(),- status: z- .enum([- 'active',- 'running',- 'paused',- 'waitingForHuman',- 'failed',- 'completed',- 'archived',- ])- .nullable()- .optional(),+ status: chatTopicStatusSchema.nullable().optional(),title: z.string().optional(),}),}),diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsnew file mode 100644index 00000000000..06dac89a9e6--- /dev/null+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -0,0 +1,641 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { agents, chatGroups, messages, sessions, topics, users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { TopicModel } from '../topic';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'topic-model-test-user';+const otherUserId = 'topic-model-test-other-user';++const topicModel = new TopicModel(serverDB, userId);++const now = () => new Date();+const minutesAgo = (n: number) => new Date(Date.now() - n * 60 * 1000);++describe('TopicModel', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ describe('create', () => {+ it('creates a topic owned by the calling user with null owner columns by default', async () => {+ const topic = await topicModel.create({ title: 'Hello' });++ expect(topic.title).toBe('Hello');+ expect(topic.userId).toBe(userId);+ expect(topic.agentId).toBeNull();+ expect(topic.sessionId).toBeNull();+ expect(topic.groupId).toBeNull();+ // personal mode β workspaceId stays null+ expect(topic.workspaceId).toBeNull();+ });++ it('coerces falsy owner ids to null', async () => {+ const topic = await topicModel.create({+ agentId: '',+ groupId: '',+ sessionId: '',+ title: 'falsy owners',+ });++ expect(topic.agentId).toBeNull();+ expect(topic.groupId).toBeNull();+ expect(topic.sessionId).toBeNull();+ });++ it('attaches given messages to the new topic in a transaction', async () => {+ await serverDB.insert(messages).values([+ { content: 'm1', id: 'msg-1', role: 'user', userId },+ { content: 'm2', id: 'msg-2', role: 'assistant', userId },+ ]);++ const topic = await topicModel.create({ messages: ['msg-1', 'msg-2'], title: 'with msgs' });++ const linked = await serverDB+ .select({ id: messages.id, topicId: messages.topicId })+ .from(messages)+ .where(eq(messages.topicId, topic.id));++ expect(linked.map((m) => m.id).sort()).toEqual(['msg-1', 'msg-2']);+ });+ });++ describe('batchCreate', () => {+ it('keeps a session topic session-scoped and a group topic group-scoped', async () => {+ await serverDB.insert(agents).values({ id: 'agent-b', userId });+ await serverDB.insert(sessions).values({ id: 'session-x', userId });+ await serverDB.insert(chatGroups).values({ id: 'group-b', userId });++ const created = await topicModel.batchCreate([+ { agentId: 'agent-b', sessionId: 'session-x', title: 'session topic' },+ { groupId: 'group-b', title: 'group topic' },+ ]);++ const bySession = created.find((t) => t.title === 'session topic')!;+ const byGroup = created.find((t) => t.title === 'group topic')!;++ // sessionId given (no groupId) β sessionId kept, groupId stays null+ expect(bySession.sessionId).toBe('session-x');+ expect(bySession.groupId).toBeNull();++ // groupId given (no sessionId) β groupId kept, sessionId stays null+ expect(byGroup.groupId).toBe('group-b');+ expect(byGroup.sessionId).toBeNull();+ });++ it('drops both owner ids when sessionId and groupId are passed together', async () => {+ await serverDB.insert(sessions).values({ id: 'session-both', userId });+ await serverDB.insert(chatGroups).values({ id: 'group-both', userId });++ // Each field is nulled based on the *other* being present, so passing both+ // detaches the topic from both β callers must pick exactly one.+ const [created] = await topicModel.batchCreate([+ { groupId: 'group-both', sessionId: 'session-both', title: 'ambiguous' },+ ]);++ expect(created.sessionId).toBeNull();+ expect(created.groupId).toBeNull();+ });+ });++ describe('findById', () => {+ it('returns the topic for the owner', async () => {+ const topic = await topicModel.create({ title: 'findable' });+ const found = await topicModel.findById(topic.id);+ expect(found?.id).toBe(topic.id);+ });++ it('does not return a topic owned by another user', async () => {+ await serverDB+ .insert(topics)+ .values({ id: 'topic-foreign', title: 'nope', userId: otherUserId });++ const found = await topicModel.findById('topic-foreign');+ expect(found).toBeUndefined();+ });+ });++ describe('query', () => {+ it('orders favorites first then by recent activity', async () => {+ await serverDB.insert(agents).values({ id: 'agent-q', userId });+ await serverDB.insert(topics).values([+ {+ agentId: 'agent-q',+ id: 't-fav',+ title: 'fav',+ favorite: true,+ updatedAt: minutesAgo(60),+ userId,+ },+ { agentId: 'agent-q', id: 't-new', title: 'new', updatedAt: minutesAgo(1), userId },+ { agentId: 'agent-q', id: 't-old', title: 'old', updatedAt: minutesAgo(30), userId },+ ]);++ const { items, total } = await topicModel.query({ agentId: 'agent-q' });++ expect(total).toBe(3);+ expect(items.map((t) => t.id)).toEqual(['t-fav', 't-new', 't-old']);+ });++ it('adopts orphan rows for the inbox agent only', async () => {+ await serverDB.insert(agents).values({ id: 'agent-inbox', slug: 'inbox', userId });+ await serverDB.insert(topics).values([+ { agentId: 'agent-inbox', id: 't-direct', title: 'direct', userId },+ // legacy orphan: every owner column null+ { id: 't-orphan', title: 'orphan', userId },+ ]);++ const inbox = await topicModel.query({ agentId: 'agent-inbox', isInbox: true });+ expect(inbox.items.map((t) => t.id).sort()).toEqual(['t-direct', 't-orphan']);++ const nonInbox = await topicModel.query({ agentId: 'agent-inbox' });+ expect(nonInbox.items.map((t) => t.id)).toEqual(['t-direct']);+ });++ it('filters by groupId directly', async () => {+ await serverDB.insert(chatGroups).values({ id: 'group-q', userId });+ await serverDB.insert(topics).values([+ { groupId: 'group-q', id: 't-g1', title: 'g1', userId },+ { id: 't-no-group', title: 'no group', userId },+ ]);++ const { items } = await topicModel.query({ groupId: 'group-q' });+ expect(items.map((t) => t.id)).toEqual(['t-g1']);+ });++ describe('status filtering & ordering', () => {+ it('excludes topics whose status is in excludeStatuses but keeps null status', async () => {+ await serverDB.insert(agents).values({ id: 'agent-s', userId });+ await serverDB.insert(topics).values([+ { agentId: 'agent-s', id: 't-active', status: 'active', title: 'active', userId },+ { agentId: 'agent-s', id: 't-done', status: 'completed', title: 'done', userId },+ { agentId: 'agent-s', id: 't-null', title: 'null status', userId },+ ]);++ const { items } = await topicModel.query({+ agentId: 'agent-s',+ excludeStatuses: ['completed'],+ });++ expect(items.map((t) => t.id).sort()).toEqual(['t-active', 't-null']);+ });++ it('orders by status priority floating unread above active/completed', async () => {+ await serverDB.insert(agents).values({ id: 'agent-rank', userId });+ // all share the same activity time so only the status rank decides order+ const at = minutesAgo(5);+ await serverDB.insert(topics).values([+ {+ agentId: 'agent-rank',+ id: 't-completed',+ status: 'completed',+ title: 'c',+ updatedAt: at,+ userId,+ },+ {+ agentId: 'agent-rank',+ id: 't-active',+ status: 'active',+ title: 'a',+ updatedAt: at,+ userId,+ },+ {+ agentId: 'agent-rank',+ id: 't-unread',+ status: 'unread',+ title: 'u',+ updatedAt: at,+ userId,+ },+ {+ agentId: 'agent-rank',+ id: 't-waiting',+ status: 'waitingForHuman',+ title: 'w',+ updatedAt: at,+ userId,+ },+ ]);++ const { items } = await topicModel.query({ agentId: 'agent-rank', sortBy: 'status' });++ // waitingForHuman(0) < unread(2) < active(4) < completed(6)+ expect(items.map((t) => t.id)).toEqual([+ 't-waiting',+ 't-unread',+ 't-active',+ 't-completed',+ ]);+ });+ });++ describe('trigger filtering', () => {+ beforeEach(async () => {+ await serverDB.insert(agents).values({ id: 'agent-trig', userId });+ await serverDB.insert(topics).values([+ { agentId: 'agent-trig', id: 't-chat', title: 'chat', trigger: 'chat', userId },+ { agentId: 'agent-trig', id: 't-cron', title: 'cron', trigger: 'cron', userId },+ { agentId: 'agent-trig', id: 't-none', title: 'none', userId },+ ]);+ });++ it('keeps only the requested triggers when `triggers` is set', async () => {+ const { items } = await topicModel.query({ agentId: 'agent-trig', triggers: ['cron'] });+ expect(items.map((t) => t.id)).toEqual(['t-cron']);+ });++ it('drops excluded triggers but keeps null-trigger topics', async () => {+ const { items } = await topicModel.query({+ agentId: 'agent-trig',+ excludeTriggers: ['cron'],+ });+ expect(items.map((t) => t.id).sort()).toEqual(['t-chat', 't-none']);+ });++ it('includeTriggers takes precedence over excludeTriggers', async () => {+ const { items } = await topicModel.query({+ agentId: 'agent-trig',+ excludeTriggers: ['cron'],+ includeTriggers: ['cron'],+ });+ expect(items.map((t) => t.id)).toEqual(['t-cron']);+ });+ });++ it('returns card-detail columns only when withDetails is set', async () => {+ await serverDB.insert(agents).values({ id: 'agent-d', userId });+ await serverDB.insert(topics).values({+ agentId: 'agent-d',+ description: 'desc',+ id: 't-detail',+ title: 'detail',+ trigger: 'chat',+ userId,+ });+ await serverDB.insert(messages).values([+ { content: 'first user message', id: 'dm-1', role: 'user', topicId: 't-detail', userId },+ { content: 'assistant reply', id: 'dm-2', role: 'assistant', topicId: 't-detail', userId },+ ]);++ const lean = await topicModel.query({ agentId: 'agent-d' });+ expect(lean.items[0]).not.toHaveProperty('firstUserMessage');+ expect(lean.items[0]).not.toHaveProperty('messageCount');++ const detailed = await topicModel.query({ agentId: 'agent-d', withDetails: true });+ expect(detailed.items[0]).toMatchObject({+ description: 'desc',+ firstUserMessage: 'first user message',+ messageCount: 2,+ trigger: 'chat',+ });+ });+ });++ describe('queryTopics', () => {+ it('filters by the given statuses and is scoped to the owner', async () => {+ await serverDB.insert(topics).values([+ { id: 't-running', status: 'running', title: 'r', userId },+ { id: 't-active', status: 'active', title: 'a', userId },+ { id: 't-running-other', status: 'running', title: 'ro', userId: otherUserId },+ ]);++ const result = await topicModel.queryTopics({ statuses: ['running'] });+ expect(result.map((t) => t.id)).toEqual(['t-running']);+ });++ it('returns all owned topics when no statuses filter is given', async () => {+ await serverDB.insert(topics).values([+ { id: 't1', status: 'running', title: '1', userId },+ { id: 't2', status: 'active', title: '2', userId },+ ]);++ const result = await topicModel.queryTopics();+ expect(result.map((t) => t.id).sort()).toEqual(['t1', 't2']);+ });+ });++ describe('count', () => {+ it('counts all owned topics and can scope to an agent', async () => {+ await serverDB.insert(agents).values({ id: 'agent-c', userId });+ await serverDB.insert(topics).values([+ { agentId: 'agent-c', id: 'c1', title: '1', userId },+ { id: 'c2', title: '2', userId },+ { id: 'c-other', title: 'x', userId: otherUserId },+ ]);++ expect(await topicModel.count()).toBe(2);+ expect(await topicModel.count({ agentId: 'agent-c' })).toBe(1);+ });+ });++ describe('update', () => {+ it('updates status and bumps updatedAt', async () => {+ const topic = await topicModel.create({ title: 'to update' });+ const before = topic.updatedAt.getTime();++ const [updated] = await topicModel.update(topic.id, { status: 'unread' });+ expect(updated.status).toBe('unread');+ expect(updated.updatedAt.getTime()).toBeGreaterThanOrEqual(before);++ const [cleared] = await topicModel.update(topic.id, { status: 'active' });+ expect(cleared.status).toBe('active');+ });++ it('does not update a topic owned by another user', async () => {+ await serverDB+ .insert(topics)+ .values({ id: 't-foreign-upd', status: 'active', title: 'foreign', userId: otherUserId });++ const result = await topicModel.update('t-foreign-upd', { status: 'unread' });+ expect(result).toHaveLength(0);++ const [row] = await serverDB.select().from(topics).where(eq(topics.id, 't-foreign-upd'));+ expect(row.status).toBe('active');+ });+ });++ describe('updateMetadata', () => {+ it('merges new metadata into existing metadata', async () => {+ const topic = await topicModel.create({+ metadata: { model: 'gpt-4', provider: 'openai' },+ title: 'meta',+ });++ const [updated] = await topicModel.updateMetadata(topic.id, { workingDirectory: '/tmp' });++ expect(updated.metadata).toMatchObject({+ model: 'gpt-4',+ provider: 'openai',+ workingDirectory: '/tmp',+ });+ });++ it('deep-merges the onboardingSession sub-object', async () => {+ const topic = await topicModel.create({+ metadata: {+ onboardingSession: {+ lastActiveAt: '2026-01-01',+ phase: 'discovery',+ startedAt: '2026-01-01',+ version: 1,+ },+ },+ title: 'onboarding',+ });++ const [updated] = await topicModel.updateMetadata(topic.id, {+ onboardingSession: { phase: 'summary' },+ });++ expect(updated.metadata?.onboardingSession).toMatchObject({+ lastActiveAt: '2026-01-01',+ phase: 'summary',+ startedAt: '2026-01-01',+ version: 1,+ });+ });+ });++ describe('delete', () => {+ it('deletes a single owned topic', async () => {+ const topic = await topicModel.create({ title: 'del' });+ await topicModel.delete(topic.id);+ expect(await topicModel.findById(topic.id)).toBeUndefined();+ });++ it('batch deletes only the given ids', async () => {+ await serverDB.insert(topics).values([+ { id: 'b1', title: '1', userId },+ { id: 'b2', title: '2', userId },+ { id: 'b3', title: '3', userId },+ ]);++ await topicModel.batchDelete(['b1', 'b2']);++ const remaining = await topicModel.queryTopics();+ expect(remaining.map((t) => t.id)).toEqual(['b3']);+ });++ it('deleteAll removes only the calling user rows', async () => {+ await serverDB.insert(topics).values([+ { id: 'mine-1', title: '1', userId },+ { id: 'theirs-1', title: '2', userId: otherUserId },+ ]);++ await topicModel.deleteAll();++ expect(await topicModel.queryTopics()).toHaveLength(0);+ const theirs = await serverDB.select().from(topics).where(eq(topics.id, 'theirs-1'));+ expect(theirs).toHaveLength(1);+ });++ it('batchDeleteByAgentId removes all topics under one agent', async () => {+ await serverDB.insert(agents).values([+ { id: 'agent-del', userId },+ { id: 'agent-keep', userId },+ ]);+ await serverDB.insert(topics).values([+ { agentId: 'agent-del', id: 'd1', title: '1', userId },+ { agentId: 'agent-del', id: 'd2', title: '2', userId },+ { agentId: 'agent-keep', id: 'k1', title: '3', userId },+ ]);++ await topicModel.batchDeleteByAgentId('agent-del');++ const remaining = await topicModel.queryTopics();+ expect(remaining.map((t) => t.id)).toEqual(['k1']);+ });+ });++ describe('duplicate', () => {+ it('copies the topic and its messages under a new id', async () => {+ const topic = await topicModel.create({ title: 'original' });+ await serverDB.insert(messages).values([+ { content: 'hi', id: 'dup-m1', role: 'user', topicId: topic.id, userId },+ { content: 'yo', id: 'dup-m2', role: 'assistant', topicId: topic.id, userId },+ ]);++ const { topic: cloned, messages: clonedMessages } = await topicModel.duplicate(+ topic.id,+ 'copy',+ );++ expect(cloned.id).not.toBe(topic.id);+ expect(cloned.title).toBe('copy');+ expect(clonedMessages).toHaveLength(2);+ expect(clonedMessages.every((m) => m.topicId === cloned.id)).toBe(true);+ expect(clonedMessages.map((m) => m.id)).not.toContain('dup-m1');+ });++ it('throws when the source topic does not exist', async () => {+ await expect(topicModel.duplicate('nope')).rejects.toThrow('not found');+ });+ });++ describe('batchMoveToAgent', () => {+ it('reassigns agentId, clears sessionId, and moves child messages', async () => {+ await serverDB.insert(agents).values([+ { id: 'agent-src', userId },+ { id: 'agent-dst', userId },+ ]);+ await serverDB.insert(topics).values({+ agentId: 'agent-src',+ id: 'move-1',+ sessionId: null,+ title: 'movable',+ userId,+ });+ await serverDB.insert(messages).values({+ agentId: 'agent-src',+ content: 'm',+ id: 'move-msg',+ role: 'user',+ topicId: 'move-1',+ userId,+ });++ await topicModel.batchMoveToAgent(['move-1'], 'agent-dst');++ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'move-1'));+ expect(topic.agentId).toBe('agent-dst');+ expect(topic.sessionId).toBeNull();++ const [msg] = await serverDB.select().from(messages).where(eq(messages.id, 'move-msg'));+ expect(msg.agentId).toBe('agent-dst');+ });++ it('throws when the target agent is not accessible', async () => {+ await serverDB.insert(agents).values({ id: 'agent-foreign', userId: otherUserId });+ await serverDB.insert(topics).values({ id: 'move-x', title: 'x', userId });++ await expect(topicModel.batchMoveToAgent(['move-x'], 'agent-foreign')).rejects.toThrow(+ 'not found or not accessible',+ );+ });++ it('is a no-op for an empty id list', async () => {+ await expect(topicModel.batchMoveToAgent([], 'whatever')).resolves.toBeUndefined();+ });+ });++ describe('getCronTopicsGroupedByCronJob', () => {+ it('groups cron-triggered topics by their cronJobId and skips topics without one', async () => {+ await serverDB.insert(agents).values({ id: 'agent-cron', userId });+ await serverDB.insert(topics).values([+ {+ agentId: 'agent-cron',+ id: 'cron-a1',+ metadata: { cronJobId: 'job-a' },+ title: 'a1',+ trigger: 'cron',+ userId,+ },+ {+ agentId: 'agent-cron',+ id: 'cron-a2',+ metadata: { cronJobId: 'job-a' },+ title: 'a2',+ trigger: 'cron',+ userId,+ },+ {+ agentId: 'agent-cron',+ id: 'cron-b1',+ metadata: { cronJobId: 'job-b' },+ title: 'b1',+ trigger: 'cron',+ userId,+ },+ // cron trigger but no cronJobId β excluded by the SQL filter+ {+ agentId: 'agent-cron',+ id: 'cron-nojob',+ metadata: {},+ title: 'nojob',+ trigger: 'cron',+ userId,+ },+ ]);++ const grouped = await topicModel.getCronTopicsGroupedByCronJob('agent-cron');+ const byJob = Object.fromEntries(grouped.map((g) => [g.cronJobId, g.topics.length]));++ expect(byJob).toEqual({ 'job-a': 2, 'job-b': 1 });+ });+ });++ describe('queryRecent', () => {+ it('orders recent topics by latest activity and tags type', async () => {+ await serverDB.insert(agents).values({ id: 'agent-recent', slug: 'inbox', userId });+ await serverDB.insert(chatGroups).values({ id: 'group-recent', userId });+ await serverDB.insert(topics).values([+ {+ agentId: 'agent-recent',+ id: 'r-agent',+ title: 'agent',+ updatedAt: minutesAgo(10),+ userId,+ },+ {+ groupId: 'group-recent',+ id: 'r-group',+ title: 'group',+ updatedAt: minutesAgo(1),+ userId,+ },+ ]);++ const result = await topicModel.queryRecent();+ expect(result.map((t) => t.id)).toEqual(['r-group', 'r-agent']);+ expect(result.find((t) => t.id === 'r-group')?.type).toBe('group');+ expect(result.find((t) => t.id === 'r-agent')?.type).toBe('agent');+ });+ });++ describe('listTopicsForMemoryExtractor', () => {+ it('omits topics already marked completed unless ignoreExtracted is set', async () => {+ await serverDB.insert(topics).values([+ { createdAt: minutesAgo(2), id: 'mem-pending', title: 'pending', userId },+ {+ createdAt: minutesAgo(1),+ id: 'mem-done',+ metadata: { userMemoryExtractStatus: 'completed' },+ title: 'done',+ userId,+ },+ ]);++ const pendingOnly = await topicModel.listTopicsForMemoryExtractor();+ expect(pendingOnly.map((t) => t.id)).toEqual(['mem-pending']);++ const all = await topicModel.listTopicsForMemoryExtractor({ ignoreExtracted: true });+ expect(all.map((t) => t.id).sort()).toEqual(['mem-done', 'mem-pending']);+ });++ it('countTopicsForMemoryExtractor matches the list length', async () => {+ await serverDB.insert(topics).values([+ { id: 'mem-1', title: '1', userId },+ {+ id: 'mem-2',+ metadata: { userMemoryExtractStatus: 'completed' },+ title: '2',+ userId,+ },+ ]);++ expect(await topicModel.countTopicsForMemoryExtractor()).toBe(1);+ });+ });+});diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 2f6793a8bd5..6263275c28f 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -135,18 +135,20 @@ export interface ListTopicsForMemoryExtractorCursor {// higher in the list. A NULL / unknown status falls through to `active` (3),// matching the client which treats a missing status as active. Keep this in// sync with `STATUS_GROUP_ORDER` / `resolveStatusBucket` in `@lobechat/utils`-// (client-side bucketing): `waitingForHuman` and `failed` both collapse into the-// top `pending` bucket, so they must float to the top here too β otherwise a-// failed topic could fall off the first page and vanish from the pending group.+// (client-side bucketing): `waitingForHuman`, `failed` and `unread` all collapse+// into the top `pending` bucket, so they must float to the top here too β+// otherwise such a topic could fall off the first page and vanish from the+// pending group.const STATUS_SORT_RANK = sql`CASE ${topics.status}WHEN 'waitingForHuman' THEN 0WHEN 'failed' THEN 1- WHEN 'running' THEN 2- WHEN 'active' THEN 3- WHEN 'paused' THEN 4- WHEN 'completed' THEN 5- WHEN 'archived' THEN 6- ELSE 3 END`;+ WHEN 'unread' THEN 2+ WHEN 'running' THEN 3+ WHEN 'active' THEN 4+ WHEN 'paused' THEN 5+ WHEN 'completed' THEN 6+ WHEN 'archived' THEN 7+ ELSE 4 END`;// Favorites always float to the top; the rest are ordered by the requested// strategy. `status` adds the priority bucket before the recency tiebreaker.diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.tsindex e5c64bfffb9..95d76e5ff6f 100644--- a/packages/database/src/repositories/home/index.ts+++ b/packages/database/src/repositories/home/index.ts@@ -4,10 +4,17 @@ import {type SidebarGroup,} from '@lobechat/types';import { cleanObject } from '@lobechat/utils';-import { and, desc, eq, not, sql } from 'drizzle-orm';+import { and, count, desc, eq, not, sql } from 'drizzle-orm';import { ChatGroupModel } from '../../models/chatGroup';-import { agents, agentsToSessions, chatGroups, sessionGroups, sessions } from '../../schemas';+import {+ agents,+ agentsToSessions,+ chatGroups,+ sessionGroups,+ sessions,+ topics,+} from '../../schemas';import { type LobeChatDatabase } from '../../type';import { sanitizeBm25Query } from '../../utils/bm25';import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';@@ -85,6 +92,12 @@ export class HomeRepository {// 2.1 Query member avatars for each chat groupconst memberAvatarsMap = await this.getChatGroupMemberAvatars(chatGroupList.map((g) => g.id));+ // 2.2 Unread completion counts per agent / group, derived from persisted+ // `topics.status === 'unread'`. The list query covers all agents, so this is+ // the source of truth for the sidebar badge even on agents the client hasn't+ // loaded topics for.+ const { agentUnread, groupUnread } = await this.getUnreadCounts();+// 3. Query all sessionGroups (user-defined folders)const groupList = await this.db.select({@@ -97,7 +110,58 @@ export class HomeRepository {.orderBy(sessionGroups.sort);// 4. Process and categorize- return this.processAgentList(agentList, chatGroupList, groupList, memberAvatarsMap);+ return this.processAgentList(+ agentList,+ chatGroupList,+ groupList,+ memberAvatarsMap,+ agentUnread,+ groupUnread,+ );+ }++ /**+ * Count topics with an unread completed generation, grouped by agent and by+ * group. Returns plain maps keyed by agentId / groupId.+ */+ private async getUnreadCounts(): Promise<{+ agentUnread: Map<string, number>;+ groupUnread: Map<string, number>;+ }> {+ const isUnread = eq(topics.status, 'unread');++ const [byAgent, byGroup] = await Promise.all([+ this.db+ .select({ id: topics.agentId, value: count() })+ .from(topics)+ .where(+ and(+ buildWorkspaceWhere(this.scope, topics),+ isUnread,+ sql`${topics.agentId} is not null`,+ ),+ )+ .groupBy(topics.agentId),+ this.db+ .select({ id: topics.groupId, value: count() })+ .from(topics)+ .where(+ and(+ buildWorkspaceWhere(this.scope, topics),+ isUnread,+ sql`${topics.groupId} is not null`,+ ),+ )+ .groupBy(topics.groupId),+ ]);++ const agentUnread = new Map<string, number>();+ for (const row of byAgent) if (row.id) agentUnread.set(row.id, row.value);++ const groupUnread = new Map<string, number>();+ for (const row of byGroup) if (row.id) groupUnread.set(row.id, row.value);++ return { agentUnread, groupUnread };}private processAgentList(@@ -132,6 +196,8 @@ export class HomeRepository {sort: number | null;}>,memberAvatarsMap: Map<string, Array<{ avatar: string; background?: string }>>,+ agentUnread: Map<string, number> = new Map(),+ groupUnread: Map<string, number> = new Map(),): SidebarAgentListResponse {// Convert to unified format// For pinned status: agents.pinned takes priority, fallback to sessions.pinned for backward compatibility@@ -154,6 +220,7 @@ export class HomeRepository {sessionId: a.sessionId,title: meta.title,type: 'agent' as const,+ unreadCount: agentUnread.get(a.id) ?? 0,updatedAt: a.updatedAt,};}),@@ -169,6 +236,7 @@ export class HomeRepository {sessionId: null,title: g.title,type: 'group' as const,+ unreadCount: groupUnread.get(g.id) ?? 0,updatedAt: g.updatedAt,})),];diff --git a/packages/database/src/schemas/topic.ts b/packages/database/src/schemas/topic.tsindex c4a63b84714..a51fd5adada 100644--- a/packages/database/src/schemas/topic.ts+++ b/packages/database/src/schemas/topic.ts@@ -44,7 +44,16 @@ export const topics = pgTable(trigger: text('trigger'), // 'cron' | 'chat' | 'api' | 'eval' | 'share' - topic creation trigger sourcemode: text('mode'), // 'temp' | 'test' | 'default' - topic usage scenariostatus: text('status', {- enum: ['active', 'running', 'paused', 'waitingForHuman', 'failed', 'completed', 'archived'],+ enum: [+ 'active',+ 'running',+ 'paused',+ 'waitingForHuman',+ 'failed',+ 'completed',+ 'archived',+ 'unread',+ ],}),completedAt: timestamptz('completed_at'),diff --git a/packages/types/src/home.ts b/packages/types/src/home.tsindex 239ad3dc92a..7bfa67faf18 100644--- a/packages/types/src/home.ts+++ b/packages/types/src/home.ts@@ -44,6 +44,13 @@ export interface SidebarAgentItem {sessionId?: string | null;title: string | null;type: SidebarItemType;+ /**+ * Number of topics with an unread completed generation under this agent/group.+ * Derived server-side from `topics.status === 'unread'` so the sidebar badge+ * stays accurate across agents the client hasn't loaded topics for. Absent /+ * 0 means no unread.+ */+ unreadCount?: number;updatedAt: Date;}diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex e8f604591d0..fed57fd974f 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -1,3 +1,5 @@+import { z } from 'zod';+import type { BaseDataModel } from '../meta';// Type definitions@@ -190,14 +192,30 @@ export interface ChatTopicSummary {provider: string;}-export type ChatTopicStatus =- | 'active'- | 'running'- | 'paused'- | 'waitingForHuman'- | 'failed'- | 'completed'- | 'archived';+/**+ * Canonical, ordered list of topic statuses. Single source of truth for both+ * the {@link ChatTopicStatus} type and the {@link chatTopicStatusSchema} zod+ * validator (consumed by the topic TRPC router). Add new statuses here.+ *+ * - `unread`: a completed generation the user hasn't read yet. Persisted so the+ * unread indicator survives reload and syncs across devices; cleared back to+ * `active` when the user opens the topic. See operation slice unread actions.+ */+export const TOPIC_STATUSES = [+ 'active',+ 'running',+ 'paused',+ 'waitingForHuman',+ 'failed',+ 'completed',+ 'archived',+ 'unread',+] as const;++/** Zod validator for {@link ChatTopicStatus}, derived from {@link TOPIC_STATUSES}. */+export const chatTopicStatusSchema = z.enum(TOPIC_STATUSES);++export type ChatTopicStatus = z.infer<typeof chatTopicStatusSchema>;export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {completedAt?: Date | null;diff --git a/packages/utils/src/client/topic.test.ts b/packages/utils/src/client/topic.test.tsindex 27c4deda26c..041941cce9f 100644--- a/packages/utils/src/client/topic.test.ts+++ b/packages/utils/src/client/topic.test.ts@@ -258,9 +258,9 @@ describe('groupTopicsByStatus', () => {});it('should bucket an unread completion as pending while read completions stay completed', () => {- const topics = [createTopic('unread', 'completed'), createTopic('read', 'completed')];+ const topics = [createTopic('unread', 'unread'), createTopic('read', 'completed')];- const result = groupTopicsByStatus(topics, 'updatedAt', undefined, new Set(['unread']));+ const result = groupTopicsByStatus(topics, 'updatedAt');expect(result.map((g) => g.id)).toEqual(['pending', 'completed']);expect(result[0].children.map((t) => t.id)).toEqual(['unread']);diff --git a/packages/utils/src/client/topic.ts b/packages/utils/src/client/topic.tsindex 5f484c51ec1..7889859bf94 100644--- a/packages/utils/src/client/topic.ts+++ b/packages/utils/src/client/topic.ts@@ -170,10 +170,10 @@ export type TopicStatusBucket =//// The server orders the query by the underlying status priority (see// `STATUS_SORT_RANK` in `@lobechat/database` topic model) so the right page is-// fetched; this only re-buckets that already-ordered page for display. The-// client-only nuances are `loadingTopicIds` (a topic streaming right now) and-// `unreadTopicIds` (a completion not yet read), which the server can't know-// about β see `resolveStatusBucket`.+// fetched; this only re-buckets that already-ordered page for display. The one+// client-only nuance is `loadingTopicIds` (a topic streaming right now), which+// the server can't know about β see `resolveStatusBucket`. The unread state is+// now a persisted `topics.status === 'unread'`, so it needs no client overlay.export const STATUS_GROUP_ORDER: TopicStatusBucket[] = ['pending','running',@@ -186,18 +186,17 @@ export const STATUS_GROUP_ORDER: TopicStatusBucket[] = [/*** Resolve the bucket a topic belongs to. Mirrors the icon precedence in the* sidebar `TopicItem`: anything needing attention (`waitingForHuman`, `failed`,- * or an unread completion in `unreadTopicIds`) lands in `pending`; then a topic- * actively streaming on this client (`loadingTopicIds`, a transient client-only- * state the server can't see) or persisted as `running` lands in `running`; then- * the persisted status, defaulting to `active`.+ * or an unread completion `unread`) lands in `pending`; then a topic actively+ * streaming on this client (`loadingTopicIds`, a transient client-only state the+ * server can't see) or persisted as `running` lands in `running`; then the+ * persisted status, defaulting to `active`.*/const resolveStatusBucket = (topic: ChatTopic,loadingTopicIds?: ReadonlySet<string>,- unreadTopicIds?: ReadonlySet<string>,): TopicStatusBucket => {- if (topic.status === 'waitingForHuman' || topic.status === 'failed') return 'pending';- if (unreadTopicIds?.has(topic.id)) return 'pending';+ if (topic.status === 'waitingForHuman' || topic.status === 'failed' || topic.status === 'unread')+ return 'pending';if (loadingTopicIds?.has(topic.id) || topic.status === 'running') return 'running';const status: ChatTopicStatus = topic.status ?? 'active';if (status === 'paused' || status === 'completed' || status === 'archived') return status;@@ -208,14 +207,13 @@ export const groupTopicsByStatus = (topics: ChatTopic[],field: 'createdAt' | 'updatedAt',loadingTopicIds?: ReadonlySet<string>,- unreadTopicIds?: ReadonlySet<string>,): GroupedTopic[] => {if (!topics.length) return [];const groupsMap = new Map<TopicStatusBucket, ChatTopic[]>();for (const topic of topics) {- const id = resolveStatusBucket(topic, loadingTopicIds, unreadTopicIds);+ const id = resolveStatusBucket(topic, loadingTopicIds);const existing = groupsMap.get(id);if (existing) {existing.push(topic);diff --git a/src/features/Conversation/hooks/index.ts b/src/features/Conversation/hooks/index.tsindex 6e431d016a5..35bb3dcbbeb 100644--- a/src/features/Conversation/hooks/index.ts+++ b/src/features/Conversation/hooks/index.ts@@ -1,2 +1,3 @@export { useAgentMeta, useIsBuiltinAgent } from './useAgentMeta';+export { useClearActiveTopicUnread } from './useClearActiveTopicUnread';export { useDoubleClickEdit } from './useDoubleClickEdit';diff --git a/src/features/Conversation/hooks/useClearActiveTopicUnread.test.ts b/src/features/Conversation/hooks/useClearActiveTopicUnread.test.tsnew file mode 100644index 00000000000..b4ee1c915b8--- /dev/null+++ b/src/features/Conversation/hooks/useClearActiveTopicUnread.test.ts@@ -0,0 +1,73 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useChatStore } from '@/store/chat';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';++import { useClearActiveTopicUnread } from './useClearActiveTopicUnread';++const AGENT_ID = 'agent-1';+const TOPIC_ID = 'topic-1';++const seed = (status: 'unread' | 'active', activeTopicId: string | null = TOPIC_ID) => {+ useChatStore.setState({+ activeAgentId: AGENT_ID,+ activeGroupId: undefined,+ activeTopicId: activeTopicId as any,+ topicDataMap: {+ [topicMapKey({ agentId: AGENT_ID })]: {+ hasMore: false,+ items: [{ id: TOPIC_ID, status, title: 't' } as any],+ } as any,+ },+ });+};++describe('useClearActiveTopicUnread', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ useChatStore.setState({ topicDataMap: {}, activeTopicId: null as any });+ });++ it('marks the active topic read when it hydrates as unread', () => {+ const markTopicRead = vi.fn();+ useChatStore.setState({ markTopicRead });+ seed('unread');++ renderHook(() => useClearActiveTopicUnread());++ expect(markTopicRead).toHaveBeenCalledWith({ topicId: TOPIC_ID });+ });++ it('does nothing when the active topic is already read', () => {+ const markTopicRead = vi.fn();+ useChatStore.setState({ markTopicRead });+ seed('active');++ renderHook(() => useClearActiveTopicUnread());++ expect(markTopicRead).not.toHaveBeenCalled();+ });++ it('clears once the topic list loads the unread topic after hydration', () => {+ const markTopicRead = vi.fn();+ // activeTopicId set first (route hydration), topic not loaded yet.+ useChatStore.setState({+ activeAgentId: AGENT_ID,+ activeTopicId: TOPIC_ID as any,+ markTopicRead,+ topicDataMap: {},+ });++ const { rerender } = renderHook(() => useClearActiveTopicUnread());+ expect(markTopicRead).not.toHaveBeenCalled();++ // Topic list arrives with the topic persisted as unread.+ act(() => {+ seed('unread');+ });+ rerender();++ expect(markTopicRead).toHaveBeenCalledWith({ topicId: TOPIC_ID });+ });+});diff --git a/src/features/Conversation/hooks/useClearActiveTopicUnread.ts b/src/features/Conversation/hooks/useClearActiveTopicUnread.tsnew file mode 100644index 00000000000..cac80bcd2bc--- /dev/null+++ b/src/features/Conversation/hooks/useClearActiveTopicUnread.ts@@ -0,0 +1,31 @@+import { useEffect } from 'react';++import { useChatStore } from '@/store/chat';+import { operationSelectors } from '@/store/chat/slices/operation/selectors';++/**+ * Clear a topic's persisted `unread` status once the user is actually reading it.+ *+ * `switchTopic` already clears unread for in-app navigation. This covers the+ * other entry points β reload, deep link, notification β where `ChatHydration`+ * sets `activeTopicId` directly (bypassing `switchTopic`) and the topic list may+ * not be loaded yet. We wait for the active topic to appear in a loaded bucket+ * as `unread`, then mark it read so the sidebar / home badge doesn't linger+ * while the user is already viewing it.+ *+ * `markTopicRead` is a no-op when the topic isn't unread, so it's safe to fire+ * whenever the derived unread state flips; it won't stomp a running / paused /+ * completed status, and clearing the status flips the trigger back to false so+ * the effect doesn't re-fire.+ */+export const useClearActiveTopicUnread = () => {+ const activeTopicId = useChatStore((s) => s.activeTopicId);+ const isActiveTopicUnread = useChatStore((s) =>+ activeTopicId ? operationSelectors.isTopicUnreadCompleted(activeTopicId)(s) : false,+ );+ const markTopicRead = useChatStore((s) => s.markTopicRead);++ useEffect(() => {+ if (activeTopicId && isActiveTopicUnread) markTopicRead({ topicId: activeTopicId });+ }, [activeTopicId, isActiveTopicUnread, markTopicRead]);+};diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsxindex 842a29feb36..9b35861ff4a 100644--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx@@ -4,6 +4,7 @@ import { memo, useLayoutEffect, useRef } from 'react';import { useLocation, useParams, useSearchParams } from 'react-router';import { SESSION_CHAT_TOPIC_URL, SESSION_CHAT_URL } from '@/const/url';+import { useClearActiveTopicUnread } from '@/features/Conversation/hooks';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useQueryState } from '@/hooks/useQueryParam';import { useChatStore } from '@/store/chat';@@ -24,6 +25,10 @@ const ChatHydration = memo(() => {const [thread, setThread] = useQueryState('thread', { history: 'replace', throttleMs: 500 });const routeTopicId = params.topicId;+ // Route hydration sets activeTopicId directly (below) instead of going through+ // switchTopic, so clear any lingering persisted unread once the topic loads.+ useClearActiveTopicUnread();+useLayoutEffect(() => {const target = routeTopicId ?? null;if (useChatStore.getState().activeTopicId !== target) {diff --git a/src/routes/(main)/group/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/group/features/Conversation/ChatHydration/index.tsxindex 002e1b4cc94..0b455e33a07 100644--- a/src/routes/(main)/group/features/Conversation/ChatHydration/index.tsx+++ b/src/routes/(main)/group/features/Conversation/ChatHydration/index.tsx@@ -3,6 +3,7 @@import { memo, useLayoutEffect } from 'react';import { createStoreUpdater } from 'zustand-utils';+import { useClearActiveTopicUnread } from '@/features/Conversation/hooks';import { useQueryState } from '@/hooks/useQueryParam';import { useChatStore } from '@/store/chat';@@ -16,6 +17,10 @@ const ChatHydration = memo(() => {useStoreUpdater('activeTopicId', topic!);useStoreUpdater('activeThreadId', thread!);+ // Hydration sets activeTopicId directly (not via switchTopic), so clear any+ // lingering persisted unread once the topic loads.+ useClearActiveTopicUnread();+useLayoutEffect(() => {const unsubscribeTopic = useChatStore.subscribe((s) => s.activeTopicId,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.tsxindex 069d7f8090b..40d4fe1fc37 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@@ -81,6 +81,10 @@ interface AgentItemProps {const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate }) => {const { id, avatar, backgroundColor, title, pinned, heterogeneousType } = item;+ // Unread count is server-computed (topics.status === 'unread') and carried on+ // the sidebar list item, so it stays accurate across agents whose topics+ // aren't loaded into the chat store on this client.+ const unreadCount = item.unreadCount ?? 0;const { t } = useTranslation('chat');const { openCreateGroupModal } = useAgentModal();const [anchor, setAnchor] = useState<HTMLElement | null>(null);@@ -91,7 +95,6 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className, onNavigate })// Separate loading state from chat store - only show loading for this specific agentconst isLoading = useChatStore(operationSelectors.isAgentRunning(id));- const unreadCount = useChatStore(operationSelectors.agentUnreadCount(id));// Get display title with fallbackconst displayTitle = title || t('untitledAgent');diff --git a/src/store/chat/slices/aiAgent/actions/groupOrchestration.ts b/src/store/chat/slices/aiAgent/actions/groupOrchestration.tsindex e80202f9f98..842324913a8 100644--- a/src/store/chat/slices/aiAgent/actions/groupOrchestration.ts+++ b/src/store/chat/slices/aiAgent/actions/groupOrchestration.ts@@ -350,7 +350,11 @@ export class GroupOrchestrationActionImpl {// Mark unread completion for background conversationsconst completedOp = this.#get().operations[operationId];if (completedOp?.context.agentId) {- this.#get().markUnreadCompleted(completedOp.context.agentId, completedOp.context.topicId);+ this.#get().markTopicUnread({+ agentId: completedOp.context.agentId,+ groupId: completedOp.context.groupId,+ topicId: completedOp.context.topicId,+ });}log('[internal_execGroupOrchestration] Operation completed successfully');diff --git a/src/store/chat/slices/aiAgent/actions/runAgent.ts b/src/store/chat/slices/aiAgent/actions/runAgent.tsindex 78eb6a29410..19ce2e939cf 100644--- a/src/store/chat/slices/aiAgent/actions/runAgent.ts+++ b/src/store/chat/slices/aiAgent/actions/runAgent.ts@@ -280,7 +280,11 @@ export class AgentActionImpl {// Mark unread completion for background agentsconst op = this.#get().operations[operationId];if (op?.context.agentId) {- this.#get().markUnreadCompleted(op.context.agentId, op.context.topicId);+ this.#get().markTopicUnread({+ agentId: op.context.agentId,+ groupId: op.context.groupId,+ topicId: op.context.topicId,+ });}break;}diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.tsindex 14a28b53e9a..c4e24209579 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/gatewayEventHandler.test.ts@@ -35,7 +35,7 @@ function createMockStore() {internal_dispatchMessage: vi.fn(),internal_executeClientTool: vi.fn().mockResolvedValue(undefined),internal_toggleToolCallingStreaming: vi.fn(),- markUnreadCompleted: vi.fn(),+ markTopicUnread: vi.fn(),operations: {'op-1': {context: { agentId: 'agent-1', scope: 'session', topicId: 'topic-1' },@@ -1078,13 +1078,13 @@ describe('createGatewayEventHandler', () => {describe('gateway terminal characterization (lifecycle refactor regression net)', () => {// CURRENT BEHAVIOR (gatewayEventHandler.ts ~622-624): the `error` event// handler completes the operation but, UNLIKE `agent_runtime_end`- // (~552-557 which calls markUnreadCompleted when the operation has a- // context.agentId), the error path NEVER calls markUnreadCompleted.+ // (~552-557 which calls markTopicUnread when the operation has a+ // context.agentId), the error path NEVER calls markTopicUnread.// This is an intentional asymmetry to lock: an errored run does not get// marked as an unread "completed" agent run. If a future refactor unifies// the terminal paths, revisit whether errors SHOULD mark unread β// changing this assertion is the signal that the contract moved.- it('error event completes the operation but does NOT call markUnreadCompleted (asymmetry vs agent_runtime_end)', async () => {+ it('error event completes the operation but does NOT call markTopicUnread (asymmetry vs agent_runtime_end)', async () => {const store = createMockStore();const handler = createHandler(store);@@ -1093,9 +1093,9 @@ describe('createGatewayEventHandler', () => {// completeOperation IS called on error.expect(store.completeOperation).toHaveBeenCalledWith('op-1');- // markUnreadCompleted is NOT β even though operations['op-1'] has a+ // markTopicUnread is NOT β even though operations['op-1'] has a// context.agentId (which WOULD trigger it on agent_runtime_end).- expect(store.markUnreadCompleted).not.toHaveBeenCalled();+ expect(store.markTopicUnread).not.toHaveBeenCalled();});it('error event preserves runtime payload errorType and budget context', async () => {@@ -1162,7 +1162,7 @@ describe('createGatewayEventHandler', () => {// Contrast probe: agent_runtime_end on the SAME operation (which has a// context.agentId) DOES mark unread completed β proving the negative// assertion above is the error path's own behavior, not a missing agentId.- it('agent_runtime_end (same op, has context.agentId) DOES call markUnreadCompleted', async () => {+ it('agent_runtime_end (same op, has context.agentId) DOES call markTopicUnread', async () => {const store = createMockStore();const handler = createHandler(store);@@ -1170,9 +1170,25 @@ describe('createGatewayEventHandler', () => {await flush();expect(store.completeOperation).toHaveBeenCalledWith('op-1');- expect(store.markUnreadCompleted).toHaveBeenCalledWith('agent-1', 'topic-1');+ expect(store.markTopicUnread).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', topicId: 'topic-1' }),+ );});+ it.each(['interrupted', 'waiting_for_async_tool'])(+ 'agent_runtime_end with reason "%s" completes the op but does NOT mark unread (cancel/park)',+ async (reason) => {+ const store = createMockStore();+ const handler = createHandler(store);++ handler(makeEvent('agent_runtime_end', { reason }));+ await flush();++ expect(store.completeOperation).toHaveBeenCalledWith('op-1');+ expect(store.markTopicUnread).not.toHaveBeenCalled();+ },+ );+// CURRENT BEHAVIOR: completeOperation runs once in the agent_runtime_end// handler (gatewayEventHandler.ts:552) and again in gateway.ts// onSessionComplete (gateway.ts:532) for the same operationId. The@@ -1391,18 +1407,12 @@ describe('createGatewayEventHandler', () => {expect(messageService.getMessages).not.toHaveBeenCalled();});- // (4) Operation lifecycle on the parked terminal. CURRENT BEHAVIOR- // (gatewayEventHandler.ts:550-557): `agent_runtime_end` ALWAYS runs the- // same terminal sequence regardless of `reason` β it does NOT short-circuit- // for `waiting_for_async_tool`. So a parked run still:- // - completes the operation (completeOperation), AND- // - marks the agent's unread state completed (markUnreadCompleted),- // because operations['op-1'].context.agentId is present. This is arguably- // surprising for a PAUSE (the run isn't truly finished β it's parked- // waiting for an async tool), but it is the behavior as written. Locking it- // here so the lifecycle refactor surfaces any change to whether a parked- // run is treated as a completed/unread run.- it('completes the operation AND marks unread completed on a waiting_for_async_tool park (does NOT short-circuit for the pause)', async () => {+ // (4) Operation lifecycle on the parked terminal. A `waiting_for_async_tool`+ // park still completes the operation and tears down tool-calling streaming,+ // but it must NOT mark the topic unread β a park is not a finished+ // generation, and persisting it as `unread` would leave a stale badge on a+ // run that's only paused waiting for an async tool. (See `isCompletedRuntimeEnd`.)+ it('completes the operation but does NOT mark unread on a waiting_for_async_tool park', async () => {const store = createMockStore();const handler = createHandler(store);@@ -1413,23 +1423,20 @@ describe('createGatewayEventHandler', () => {handler(makeEvent('agent_runtime_end', { reason: 'waiting_for_async_tool' }));await flush();- // The parked terminal runs the full agent_runtime_end sequence:+ // The parked terminal still completes the op + tears down tool streaming,expect(store.completeOperation).toHaveBeenCalledWith('op-1');- expect(store.markUnreadCompleted).toHaveBeenCalledWith('agent-1', 'topic-1');- // It also tears down tool-calling streaming for the current assistant.expect(store.internal_toggleToolCallingStreaming).toHaveBeenCalledWith('msg-server',undefined,);+ // β¦but does NOT surface an unread badge for the pause.+ expect(store.markTopicUnread).not.toHaveBeenCalled();});- // (5) Contrast probe (mirrors the interrupted symmetry): a parked terminal- // with NO streamed content still marks unread completed β the- // markUnreadCompleted call is unconditional on `reason`/`hasStreamedContent`,- // it depends ONLY on the completed op having a context.agentId. This proves- // assertion (4) is the reason-agnostic terminal contract, not a side effect- // of the streamed-content path.- it('marks unread completed on a waiting_for_async_tool park even with NO streamed content', async () => {+ // (5) Contrast probe: the no-mark behavior is driven by the park `reason`,+ // not by whether content streamed β a parked terminal with NO streamed+ // content also skips the unread mark.+ it('does NOT mark unread on a waiting_for_async_tool park even with NO streamed content', async () => {const store = createMockStore();const handler = createHandler(store);@@ -1437,7 +1444,7 @@ describe('createGatewayEventHandler', () => {await flush();expect(store.completeOperation).toHaveBeenCalledWith('op-1');- expect(store.markUnreadCompleted).toHaveBeenCalledWith('agent-1', 'topic-1');+ expect(store.markTopicUnread).not.toHaveBeenCalled();});});});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 9d01fba62c1..002eee987ab 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -195,7 +195,7 @@ function createMockStore(overrides: Record<string, any> = {}) {drainQueuedMessages: vi.fn(() => []),internal_dispatchMessage: vi.fn(),internal_toggleToolCallingStreaming: vi.fn(),- markUnreadCompleted: vi.fn(),+ markTopicUnread: vi.fn(),operations: {'op-1': {context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },@@ -3917,8 +3917,10 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(store.drainQueuedMessages).toHaveBeenCalled();expect(store.completeOperation).toHaveBeenCalledWith('op-1');- // op-1 context carries agentId/topicId β markUnreadCompleted fires.- expect(store.markUnreadCompleted).toHaveBeenCalledWith('agent-1', 'topic-1');+ // op-1 context carries agentId/topicId β markTopicUnread fires.+ expect(store.markTopicUnread).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', topicId: 'topic-1' }),+ );// The merged follow-up is dispatched via the setTimeout(100) sendMessage.expect(realSendMessage).toHaveBeenCalledTimes(1);@@ -3987,6 +3989,10 @@ describe('heterogeneousAgentExecutor DB persistence', () => {const abortController = new AbortController();abortController.abort();const store = createMockStore({+ // The user is viewing this topic, so the clean stream end clears the+ // running state back to 'active' (a background completion would instead+ // be left to markTopicUnread β status 'unread').+ activeTopicId: 'topic-1',drainQueuedMessages: vi.fn(() => [{ content: 'queued', id: 'q1' }]),operations: {'op-1': {@@ -4005,8 +4011,9 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(store.drainQueuedMessages).not.toHaveBeenCalled();// Characterize the actual behavior: onComplete's non-error branch still- // writes 'active' (the abort gate only guards the notification + drain,- // not the writeTopicStatus('active') call on a clean stream end).+ // writes 'active' while the user is viewing (the abort gate only guards+ // the notification + drain, not the writeTopicStatus('active') call on a+ // clean stream end).expect(updateTopicStatus).toHaveBeenCalledWith(expect.objectContaining({status: 'active',diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.tsindex bc21e377f87..070b1bce777 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts@@ -2513,13 +2513,13 @@ describe('StreamingExecutor actions', () => {topicId: TEST_IDS.TOPIC_ID,});const drainQueuedMessages = vi.fn(() => []);- const markUnreadCompleted = vi.fn();+ const markTopicUnread = vi.fn();restoreExecutor();act(() => {useChatStore.setState({drainQueuedMessages,- markUnreadCompleted,+ markTopicUnread,queuedMessages: {[contextKey]: [{ content: 'queued', createdAt: Date.now(), id: 'q1', interruptMode: 'soft' },@@ -2540,16 +2540,16 @@ describe('StreamingExecutor actions', () => {await runExecutor(result, operationId);expect(drainQueuedMessages).not.toHaveBeenCalled();- expect(markUnreadCompleted).not.toHaveBeenCalled();+ expect(markTopicUnread).not.toHaveBeenCalled();});it('marks unread on a successful (done) terminal with an empty queue', async () => {const { result } = renderHook(() => useChatStore());- const markUnreadCompleted = vi.fn();+ const markTopicUnread = vi.fn();restoreExecutor();act(() => {- useChatStore.setState({ markUnreadCompleted });+ useChatStore.setState({ markTopicUnread });});let operationId!: string;@@ -2563,7 +2563,9 @@ describe('StreamingExecutor actions', () => {driveTerminal(operationId, 'done');await runExecutor(result, operationId);- expect(markUnreadCompleted).toHaveBeenCalledWith(TEST_IDS.SESSION_ID, TEST_IDS.TOPIC_ID);+ expect(markTopicUnread).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID }),+ );expect(result.current.operations[operationId].status).toBe('completed');});@@ -2614,10 +2616,10 @@ describe('StreamingExecutor actions', () => {it('on waiting_for_human (parked): completes the op for the UI but does NOT drain queue or mark unread', async () => {const { result } = renderHook(() => useChatStore());const drainQueuedMessages = vi.fn(() => []);- const markUnreadCompleted = vi.fn();+ const markTopicUnread = vi.fn();restoreExecutor();act(() => {- useChatStore.setState({ drainQueuedMessages, markUnreadCompleted });+ useChatStore.setState({ drainQueuedMessages, markTopicUnread });});let operationId!: string;@@ -2637,7 +2639,7 @@ describe('StreamingExecutor actions', () => {// new operation runs them when the user approves/rejects.expect(result.current.operations[operationId].status).toBe('completed');expect(drainQueuedMessages).not.toHaveBeenCalled();- expect(markUnreadCompleted).not.toHaveBeenCalled();+ expect(markTopicUnread).not.toHaveBeenCalled();});describe('desktop notification gating', () => {diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.tsindex 7d5d925c3ff..b96371092fb 100644--- a/src/store/chat/slices/aiChat/actions/gateway.ts+++ b/src/store/chat/slices/aiChat/actions/gateway.ts@@ -20,7 +20,7 @@ import type { StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import { settingsSelectors } from '@/store/user/selectors';-import { createGatewayEventHandler } from './gatewayEventHandler';+import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEventHandler';/*** When the agent runs against the local machine, resolve this desktop's@@ -88,9 +88,13 @@ export interface ConnectGatewayParams {*/onEvent?: (event: AgentStreamEvent) => void;/**- * Called when the session completes (agent_runtime_end or session_complete)+ * Called when the session completes (agent_runtime_end or session_complete).+ * `succeeded` is true only for a clean `agent_runtime_end`; callers use it to+ * avoid stomping the `unread` status a background completion writes (the+ * completion's `markTopicUnread` and this terminal `active` write+ * partition the cases by `succeeded && !viewing`).*/- onSessionComplete?: () => void;+ onSessionComplete?: (info: { succeeded: boolean }) => void;/*** The operation ID returned by execAgent*/@@ -171,11 +175,12 @@ export class GatewayActionImpl {// so we can fire onSessionComplete from the subsequent disconnect.// session_complete is handled separately as an explicit server signal.let receivedTerminalEvent = false;+ let terminalSucceeded = false;let sessionCompleted = false;const fireSessionComplete = () => {if (sessionCompleted) return;sessionCompleted = true;- onSessionComplete?.();+ onSessionComplete?.({ succeeded: terminalSucceeded });};// Forward agent events to caller, and track terminal events@@ -183,6 +188,16 @@ export class GatewayActionImpl {if (event.type === 'agent_runtime_end' || event.type === 'error') {receivedTerminalEvent = true;}+ // Only a clean completion counts as success β a cancel ('interrupted') or+ // deferred-tool park ('waiting_for_async_tool') must take the non-success+ // branch so onSessionComplete clears the run back to 'active' instead of+ // leaving the topic persisted as an unread completion.+ if (+ event.type === 'agent_runtime_end' &&+ isCompletedRuntimeEnd((event.data as { reason?: string } | undefined)?.reason)+ ) {+ terminalSucceeded = true;+ }onEvent?.(event);});@@ -542,16 +557,23 @@ export class GatewayActionImpl {this.#get().connectToGateway({gatewayUrl: agentGatewayUrl,onEvent: eventHandler,- onSessionComplete: () => {+ onSessionComplete: ({ succeeded }) => {this.#get().completeOperation(gatewayOpId);if (result.topicId) {this.#get().internal_updateTopicLoading(result.topicId, false);- void this.#get().updateTopicStatus?.({- agentId: execContext.agentId,- groupId: execContext.groupId,- status: 'active',- topicId: result.topicId,- });+ // A clean completion the user isn't watching is owned by+ // `markTopicUnread` (status: 'unread'); skip the 'active' write so+ // the two never race over the status field. Every other case (viewing,+ // error, abort) clears the running state back to 'active' as before.+ const viewing = this.#get().activeTopicId === result.topicId;+ if (viewing || !succeeded) {+ void this.#get().updateTopicStatus?.({+ agentId: execContext.agentId,+ groupId: execContext.groupId,+ status: 'active',+ topicId: result.topicId,+ });+ }// Clear running operation from topic metadata (best-effort from frontend;// if browser was closed, reconnect logic will handle stale entries)topicService@@ -672,14 +694,19 @@ export class GatewayActionImpl {this.#get().connectToGateway({gatewayUrl: agentGatewayUrl,onEvent: eventHandler,- onSessionComplete: () => {+ onSessionComplete: ({ succeeded }) => {this.#get().completeOperation(gatewayOpId);this.#get().internal_updateTopicLoading(topicId, false);- void this.#get().updateTopicStatus?.({- agentId: context.agentId,- status: 'active',- topicId,- });+ // See executeGatewayAgent's onSessionComplete: a clean background+ // completion is left to markTopicUnread (status: 'unread').+ const viewing = this.#get().activeTopicId === topicId;+ if (viewing || !succeeded) {+ void this.#get().updateTopicStatus?.({+ agentId: context.agentId,+ status: 'active',+ topicId,+ });+ }topicService.updateTopicMetadata(topicId, { runningOperation: null }).catch(() => {});},operationId,diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.tsindex f50ce3cf8e1..f7f4694371f 100644--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts@@ -21,6 +21,20 @@ import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actimport type { ChatStore } from '@/store/chat/store';import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';+// `agent_runtime_end` reasons that are NOT a clean completion: a mid-stream+// cancel and a deferred-tool park. These must NOT mark the topic unread, and+// must take the non-success branch in `onSessionComplete` so the run clears+// back to 'active' rather than persisting as an unread completion.+const NON_COMPLETION_RUNTIME_END_REASONS = new Set(['interrupted', 'waiting_for_async_tool']);++/**+ * Whether an `agent_runtime_end` event represents a clean completion (vs. a+ * cancel / park). A clean completion is the only ending that should surface an+ * unread badge.+ */+export const isCompletedRuntimeEnd = (reason?: string | null): boolean =>+ !NON_COMPLETION_RUNTIME_END_REASONS.has(reason ?? '');+// Lazy-loaded to break the import cycle:// gateway.ts β gatewayEventHandler.ts β executors/index.ts (which pulls in// tool client barrels that import `@/store/chat/store`) β chat store@@ -634,9 +648,16 @@ export const createGatewayEventHandler = (endReasoningIfNeeded();get().completeOperation(operationId);+ // Only a clean completion surfaces an unread badge β a mid-stream+ // cancel ('interrupted') or deferred-tool park ('waiting_for_async_tool')+ // must not. Those endings clear back to 'active' in onSessionComplete.const completedOp = get().operations[operationId];- if (completedOp?.context.agentId) {- get().markUnreadCompleted(completedOp.context.agentId, completedOp.context.topicId);+ if (completedOp?.context.agentId && isCompletedRuntimeEnd(data?.reason)) {+ get().markTopicUnread({+ agentId: completedOp.context.agentId,+ groupId: completedOp.context.groupId,+ topicId: completedOp.context.topicId,+ });}// Terminal step has no later step_start to carry SoT β serverdiff --git a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.tsindex 4de68a94e4e..6fdf65b708d 100644--- a/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/heterogeneousAgentExecutor.ts@@ -1355,7 +1355,10 @@ export const executeHeterogeneousAgent = async (pendingSubagentFlush.clear();if (!isErrorTerminal) {- writeTopicStatus('active');+ // A clean completion the user isn't watching is owned by the gateway+ // handler's markTopicUnread (status: 'unread'); only clear back to+ // 'active' when the user is viewing so the two writes don't race.+ if (get().activeTopicId === context.topicId) writeTopicStatus('active');// NOW forward the deferred terminal event β handler will// fetchAndReplaceMessages and pick up the final persisted state.eventHandler(terminalEvent);@@ -1465,7 +1468,11 @@ export const executeHeterogeneousAgent = async (get().completeOperation(operationId);const completedOp = get().operations?.[operationId];if (completedOp?.context.agentId) {- get().markUnreadCompleted?.(completedOp.context.agentId, completedOp.context.topicId);+ get().markTopicUnread?.({+ agentId: completedOp.context.agentId,+ groupId: completedOp.context.groupId,+ topicId: completedOp.context.topicId,+ });}const merged = mergeQueuedMessages(remainingQueued);diff --git a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.tsindex 57bfb4e3e19..24d146a9020 100644--- a/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/runLifecycle/buildRunLifecycle.ts@@ -198,7 +198,11 @@ export const buildRunLifecycle = (const completedOp = get().operations[operationId];if (completedOp?.context.agentId) {- get().markUnreadCompleted(completedOp.context.agentId, completedOp.context.topicId);+ get().markTopicUnread({+ agentId: completedOp.context.agentId,+ groupId: completedOp.context.groupId,+ topicId: completedOp.context.topicId,+ });}emitComplete(operationId, runtimeStatus);@@ -238,7 +242,11 @@ export const buildRunLifecycle = (get().completeOperation(operationId);const completedOp = get().operations[operationId];if (completedOp?.context.agentId) {- get().markUnreadCompleted(completedOp.context.agentId, completedOp.context.topicId);+ get().markTopicUnread({+ agentId: completedOp.context.agentId,+ groupId: completedOp.context.groupId,+ topicId: completedOp.context.topicId,+ });}break;}diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.tsindex 185b641a1e2..a252d25c232 100644--- a/src/store/chat/slices/operation/actions.ts+++ b/src/store/chat/slices/operation/actions.ts@@ -5,10 +5,11 @@ import { produce } from 'immer';import { type ChatStore } from '@/store/chat/store';import { type MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';+import { getHomeStoreState } from '@/store/home';import { type StoreSetter } from '@/store/types';import { setNamespace } from '@/utils/storeDebug';-import { DEFAULT_TOPIC_UNREAD_KEY } from './initialState';import {type AfterCompletionCallback,AI_RUNTIME_OPERATION_TYPES,@@ -661,82 +662,74 @@ export class OperationActionsImpl {);};- markUnreadCompleted = (agentId: string, topicId?: string | null): void => {- const { activeAgentId, activeTopicId } = this.#get();-- // Only mark when user is NOT currently viewing this exact (agent, topic) pair.- // The default (no-topic) conversation is represented by DEFAULT_TOPIC_UNREAD_KEY.- const isViewingTopic =- activeAgentId === agentId && (activeTopicId ?? null) === (topicId ?? null);- if (isViewingTopic) return;-- const key = topicId ?? DEFAULT_TOPIC_UNREAD_KEY;- this.#set(- produce((state: ChatStore) => {- const existing = state.unreadCompletedTopicsByAgent[agentId];- if (existing) {- existing.add(key);- } else {- state.unreadCompletedTopicsByAgent[agentId] = new Set([key]);- }- }),- false,- n(`markUnreadCompleted/${agentId}/${key || 'default'}`),- );- };-- clearUnreadCompletedAgent = (agentId: string): void => {- if (!this.#get().unreadCompletedTopicsByAgent[agentId]) return;- this.#set(- produce((state: ChatStore) => {- delete state.unreadCompletedTopicsByAgent[agentId];- }),- false,- n(`clearUnreadCompleted/agent/${agentId}`),- );+ /**+ * Mark a topic as having an unread completed generation by persisting+ * `status: 'unread'`. Skipped when the user is already viewing the topic, or+ * for the default (no-topic) conversation which has no persisted row.+ *+ * The write goes through `updateTopicStatus`, which optimistically patches the+ * in-memory topic map (so the sidebar dot lights up instantly for the active+ * agent) and persists fire-and-forget. After it persists we refresh the home+ * sidebar list so the cross-agent unread badge updates even for agents whose+ * topics aren't loaded on this client.+ */+ markTopicUnread = ({+ agentId,+ groupId,+ topicId,+ }: {+ agentId?: string;+ groupId?: string | null;+ topicId?: string | null;+ }): void => {+ if (!topicId) return;+ if (this.#get().activeTopicId === topicId) return;++ void this.#get()+ .updateTopicStatus?.({+ agentId,+ groupId: groupId ?? undefined,+ status: 'unread',+ topicId,+ })+ ?.then(() => {+ void getHomeStoreState().refreshAgentList?.();+ });};/**- * Remove the given topicIds from every agent's unread set.- * Used when topics are deleted and we don't know which agents marked them unread- * (e.g. group conversations where the bot's agentId β not activeAgentId β owns the entry).+ * Clear a topic's unread mark by flipping `status: 'unread'` back to 'active'.+ * Only touches topics currently in the unread state β never stomps a+ * running / paused / completed status. Invoked when the user opens the topic.*/- purgeUnreadTopics = (topicIds: string[]): void => {- if (topicIds.length === 0) return;- const map = this.#get().unreadCompletedTopicsByAgent;- const keys = new Set(topicIds);- const affected = Object.entries(map).some(([, set]) => {- for (const id of keys) if (set.has(id)) return true;- return false;+ markTopicRead = ({+ agentId,+ groupId,+ topicId,+ }: {+ agentId?: string;+ groupId?: string | null;+ topicId?: string | null;+ }): void => {+ if (!topicId) return;++ const key = topicMapKey({+ agentId: agentId ?? this.#get().activeAgentId,+ groupId: groupId ?? this.#get().activeGroupId,});- if (!affected) return;-- this.#set(- produce((state: ChatStore) => {- for (const [agentId, set] of Object.entries(state.unreadCompletedTopicsByAgent)) {- for (const id of keys) set.delete(id);- if (set.size === 0) delete state.unreadCompletedTopicsByAgent[agentId];- }- }),- false,- n(`purgeUnreadTopics/count=${topicIds.length}`),- );- };-- clearUnreadCompletedTopic = (agentId: string, topicId?: string | null): void => {- const key = topicId ?? DEFAULT_TOPIC_UNREAD_KEY;- const set = this.#get().unreadCompletedTopicsByAgent[agentId];- if (!set?.has(key)) return;- this.#set(- produce((state: ChatStore) => {- const target = state.unreadCompletedTopicsByAgent[agentId];- if (!target) return;- target.delete(key);- if (target.size === 0) delete state.unreadCompletedTopicsByAgent[agentId];- }),- false,- n(`clearUnreadCompleted/${agentId}/${key || 'default'}`),- );+ const topic = this.#get().topicDataMap[key]?.items?.find((t) => t.id === topicId);+ if (topic?.status !== 'unread') return;++ void this.#get()+ .updateTopicStatus?.({+ agentId,+ groupId: groupId ?? undefined,+ status: 'active',+ topicId,+ })+ ?.then(() => {+ void getHomeStoreState().refreshAgentList?.();+ });};// βββ Message Queue Actions βββdiff --git a/src/store/chat/slices/operation/initialState.ts b/src/store/chat/slices/operation/initialState.tsindex 66704102a1b..07f68369ea7 100644--- a/src/store/chat/slices/operation/initialState.ts+++ b/src/store/chat/slices/operation/initialState.ts@@ -41,21 +41,8 @@ export interface ChatOperationState {* or by triggering a new sendMessage when no operation is running.*/queuedMessages: Record<string, QueuedMessage[]>;-- /**- * Per-agent unread completed topics.- * key: agentId, value: Set of topicId (use DEFAULT_TOPIC_UNREAD_KEY for the default/empty topic)- * Agent-level unread count is derived from `set.size`.- */- unreadCompletedTopicsByAgent: Record<string, Set<string>>;}-/**- * Sentinel topicId used inside `unreadCompletedTopicsByAgent` Sets to represent- * the agent's default (no-topic) conversation, so agent-level counts include it.- */-export const DEFAULT_TOPIC_UNREAD_KEY = '';-export const initialOperationState: ChatOperationState = {messageOperationMap: {},operations: {},@@ -63,5 +50,4 @@ export const initialOperationState: ChatOperationState = {operationsByMessage: {},operationsByType: {} as Record<OperationType, string[]>,queuedMessages: {},- unreadCompletedTopicsByAgent: {},};diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.tsindex 35325fc1362..4d1417b0271 100644--- a/src/store/chat/slices/operation/selectors.ts+++ b/src/store/chat/slices/operation/selectors.ts@@ -1,5 +1,6 @@import { type ChatStoreState } from '@/store/chat/initialState';import { messageMapKey, type MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';import { type Operation, type OperationType } from './types';import { AI_RUNTIME_OPERATION_TYPES, INPUT_LOADING_OPERATION_TYPES } from './types';@@ -555,50 +556,63 @@ const isSendingMessage = (s: ChatStoreState): boolean => {};// === Unread Completion ===+//+// Unread is now a persisted topic status (`topics.status === 'unread'`), so+// these selectors derive from the loaded topic map. The cross-agent badge on the+// home sidebar reads the server-computed `SidebarAgentItem.unreadCount` instead,+// since the home list doesn't load every agent's topics into `topicDataMap`./**- * Number of topics with unread completed generation for the given agent.- * Drives the agent-level badge count.+ * Number of topics with an unread completed generation for the given agent,+ * counted from the agent's loaded topic bucket.*/const agentUnreadCount =(agentId: string) =>(s: ChatStoreState): number => {- return s.unreadCompletedTopicsByAgent[agentId]?.size ?? 0;+ const items = s.topicDataMap[topicMapKey({ agentId })]?.items;+ if (!items) return 0;+ let count = 0;+ for (const topic of items) if (topic.status === 'unread') count += 1;+ return count;};/**- * Whether the agent has any unread completed generation.+ * Whether the agent has any unread completed generation (from loaded topics).*/const isAgentUnreadCompleted =(agentId: string) =>- (s: ChatStoreState): boolean => {- return (s.unreadCompletedTopicsByAgent[agentId]?.size ?? 0) > 0;- };+ (s: ChatStoreState): boolean =>+ agentUnreadCount(agentId)(s) > 0;/**- * Whether a specific topic has unread completed generation.- * Scans across agents since topic items don't carry agentId in scope here.+ * Whether a specific topic has an unread completed generation. Scans the loaded+ * topic buckets since topic items don't carry their agentId in this scope.*/const isTopicUnreadCompleted =(topicId: string) =>(s: ChatStoreState): boolean => {- for (const set of Object.values(s.unreadCompletedTopicsByAgent)) {- if (set.has(topicId)) return true;+ for (const data of Object.values(s.topicDataMap)) {+ const topic = data.items?.find((t) => t.id === topicId);+ if (topic) return topic.status === 'unread';}return false;};/**- * Number of topics with unread completed generation among the given topic ids.+ * Number of topics with an unread completed generation among the given topic ids.* Used to surface an aggregated unread indicator on a collapsed topic group.*/const unreadCompletedCountForTopics =(topicIds: string[]) =>(s: ChatStoreState): number => {- const sets = Object.values(s.unreadCompletedTopicsByAgent);+ if (topicIds.length === 0) return 0;+ const wanted = new Set(topicIds);let count = 0;- for (const topicId of topicIds) {- if (sets.some((set) => set.has(topicId))) count += 1;+ for (const data of Object.values(s.topicDataMap)) {+ if (!data.items) continue;+ for (const topic of data.items) {+ if (wanted.has(topic.id) && topic.status === 'unread') count += 1;+ }}return count;};diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex cf42f474a88..45c2098ed70 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -829,7 +829,7 @@ export class ChatTopicActionImpl {);if (activeAgentId) {- this.#get().clearUnreadCompletedTopic(activeAgentId, id ?? null);+ this.#get().markTopicRead({ agentId: activeAgentId, topicId: id ?? null });}if (opts.skipRefreshMessage) return;@@ -845,11 +845,10 @@ export class ChatTopicActionImpl {};removeSessionTopics = async (): Promise<void> => {- const { switchTopic, activeAgentId, refreshTopic, clearUnreadCompletedAgent } = this.#get();+ const { switchTopic, activeAgentId, refreshTopic } = this.#get();if (!activeAgentId) return;await topicService.removeTopicsByAgentId(activeAgentId);- clearUnreadCompletedAgent(activeAgentId);await refreshTopic();// switch to default topic@@ -857,7 +856,7 @@ export class ChatTopicActionImpl {};removeGroupTopics = async (groupId: string): Promise<void> => {- const { switchTopic, refreshTopic, purgeUnreadTopics } = this.#get();+ const { switchTopic, refreshTopic } = this.#get();// Get topics for this specific group from the topic map using topicMapKeyconst key = topicMapKey({ groupId });@@ -866,7 +865,6 @@ export class ChatTopicActionImpl {if (topicIds.length > 0) {await topicService.batchRemoveTopics(topicIds);- purgeUnreadTopics(topicIds);}await refreshTopic();@@ -879,26 +877,17 @@ export class ChatTopicActionImpl {const { refreshTopic } = this.#get();await topicService.removeAllTopic();- this.#set({ unreadCompletedTopicsByAgent: {} }, false, n('removeAllTopics/clearUnread'));await refreshTopic();};removeTopic = async (id: string): Promise<void> => {- const {- activeAgentId,- activeGroupId,- activeTopicId,- switchTopic,- refreshTopic,- purgeUnreadTopics,- } = this.#get();+ const { activeAgentId, activeGroupId, activeTopicId, switchTopic, refreshTopic } = this.#get();// Allow deletion when either agentId or groupId is activeif (!activeAgentId && !activeGroupId) return;// remove topicawait topicService.removeTopic(id);this.#get().internal_dispatchTopic({ type: 'deleteTopic', id }, 'removeTopic');- purgeUnreadTopics([id]);await refreshTopic();// switch back to default topic@@ -906,12 +895,11 @@ export class ChatTopicActionImpl {};removeUnstarredTopic = async (): Promise<void> => {- const { refreshTopic, switchTopic, purgeUnreadTopics } = this.#get();+ const { refreshTopic, switchTopic } = this.#get();const topics = topicSelectors.currentUnFavTopics(this.#get());const topicIds = topics.map((t) => t.id);await topicService.batchRemoveTopics(topicIds);- purgeUnreadTopics(topicIds);await refreshTopic();// Switch to default topic@@ -921,7 +909,7 @@ export class ChatTopicActionImpl {batchMoveTopicsToAgent = async (topicIds: string[], targetAgentId: string): Promise<void> => {if (topicIds.length === 0) return;- const { activeTopicId, switchTopic, refreshTopic, purgeUnreadTopics } = this.#get();+ const { activeTopicId, switchTopic, refreshTopic } = this.#get();await topicService.batchMoveTopics(topicIds, targetAgentId);@@ -930,7 +918,6 @@ export class ChatTopicActionImpl {topicIds.forEach((id) =>this.#get().internal_dispatchTopic({ type: 'deleteTopic', id }, 'batchMoveTopicsToAgent'),);- purgeUnreadTopics(topicIds);await refreshTopic();// If the active topic was moved away, fall back to the default topic.diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.tsindex 985ac685a8c..cb51e37feaf 100644--- a/src/store/chat/slices/topic/selectors.ts+++ b/src/store/chat/slices/topic/selectors.ts@@ -122,7 +122,6 @@ const getGroupFn = (groupMode: TopicGroupMode,sortBy: TopicSortBy,loadingTopicIds?: ReadonlySet<string>,- unreadTopicIds?: ReadonlySet<string>,) => {const field: 'createdAt' | 'updatedAt' = sortBy === 'createdAt' ? 'createdAt' : 'updatedAt';if (groupMode === 'byProject') {@@ -135,7 +134,7 @@ const getGroupFn = (}if (groupMode === 'byStatus') {return (topics: ChatTopic[]) =>- groupTopicsByStatus(topics, field, loadingTopicIds, unreadTopicIds).map((group) => ({+ groupTopicsByStatus(topics, field, loadingTopicIds).map((group) => ({...group,title: t(`groupTitle.byStatus.${group.id}` as any, { ns: 'topic' }),}));@@ -181,19 +180,12 @@ const groupedTopicsForSidebar =(s: ChatStoreState): GroupedTopic[] => {const limitedTopics = displayTopicsForSidebar(pageSize, sortBy)(s);if (!limitedTopics) return [];- // Topics actively streaming on this client surface under "running", and- // topics with an unread completion surface under "pending", even though- // their persisted status says otherwise β see resolveStatusBucket. Both are- // client-only states the server can't see.+ // Topics actively streaming on this client surface under "running" even+ // though their persisted status says otherwise β that's the one client-only+ // overlay (see resolveStatusBucket). Unread is now a persisted status, so it+ // buckets straight from `topic.status`.const loadingTopicIds = groupMode === 'byStatus' ? new Set(s.topicLoadingIds) : undefined;- const unreadTopicIds =- groupMode === 'byStatus'- ? new Set(Object.values(s.unreadCompletedTopicsByAgent).flatMap((set) => [...set]))- : undefined;- return buildGroupedTopics(- limitedTopics,- getGroupFn(groupMode, sortBy, loadingTopicIds, unreadTopicIds),- );+ return buildGroupedTopics(limitedTopics, getGroupFn(groupMode, sortBy, loadingTopicIds));};const hasMoreTopics = (s: ChatStoreState): boolean => {