π€― 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
π fix(project): clear the unread mark when a project conversation is opened (#21472)
LiJian6c8f2ea3336b
diff --git a/apps/server/src/routers/lambda/topic/index.procedures.test.ts b/apps/server/src/routers/lambda/topic/index.procedures.test.tsindex fea367c688f..dcb127a9408 100644--- a/apps/server/src/routers/lambda/topic/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/topic/index.procedures.test.ts@@ -50,6 +50,7 @@ function expected(): Array<['hasTopics', 'query', 11],['importHeteroSessions', 'mutation', 13],['importTopic', 'mutation', 13],+ ['markTopicRead', 'mutation', 13],['queryTopics', 'query', 12],['rankTopics', 'query', 12],['recentTopics', 'query', 12],diff --git a/apps/server/src/routers/lambda/topic/update.ts b/apps/server/src/routers/lambda/topic/update.tsindex c028c58a4ea..8f42b1e9c8a 100644--- a/apps/server/src/routers/lambda/topic/update.ts+++ b/apps/server/src/routers/lambda/topic/update.ts@@ -65,6 +65,20 @@ export const updateRouter = router({sessionId: resolved.sessionId,});}),+ /**+ * Clear the unread mark only while the topic is still unread β see+ * `TopicModel.markRead`. Returns the cleared row, or `null` when the status+ * had already moved on. Same co-editing rules as `updateTopic`.+ */+ markTopicRead: topicProcedure+ .use(withScopedPermission('topic:update'))+ .input(z.object({ id: z.string() }))+ .mutation(async ({ input, ctx }) => {+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);+ const [cleared] = await ctx.topicModel.markRead(input.id);+ return cleared ?? null;+ }),/*** Switch the topic's pinned model and its effort pin atomically β see* `TopicModel.updateModelPin`. Same co-editing rules as `updateTopic`.diff --git a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts b/packages/database/src/models/__tests__/topics/topic.characterization.test.tsindex 6176b85cd98..21b79baf8a2 100644--- a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.characterization.test.ts@@ -61,6 +61,7 @@ const PUBLIC_METHODS = ['getCronTopicsGroupedByCronJob','isRunningOperationAlive','listTopicsForMemoryExtractor',+ 'markRead','patchRunningOperation','purge','query',diff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.tsindex 0bec6692e03..4f00881350c 100644--- a/packages/database/src/models/__tests__/topics/topic.update.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts@@ -910,4 +910,41 @@ describe('TopicModel - Update', () => {expect(topic.cost).toBeNull();});});++ describe('markRead', () => {+ const statusOf = async (id: string) =>+ (await serverDB.select().from(topics).where(eq(topics.id, id)))[0]?.status;++ it('flips an unread topic to active and returns the cleared row', async () => {+ await serverDB.insert(topics).values({ id: 'read-1', sessionId, status: 'unread', userId });++ const cleared = await topicModel.markRead('read-1');++ expect(cleared).toEqual([{ id: 'read-1', status: 'active' }]);+ expect(await statusOf('read-1')).toBe('active');+ });++ /** @example A stale "unread" copy must not overwrite a run that started since. */+ it.each(['running', 'waitingForHuman', 'completed'] as const)(+ 'leaves a %s topic untouched',+ async (status) => {+ await serverDB.insert(topics).values({ id: 'read-2', sessionId, status, userId });++ const cleared = await topicModel.markRead('read-2');++ expect(cleared).toEqual([]);+ expect(await statusOf('read-2')).toBe(status);+ },+ );++ it("does not clear another user's topic", async () => {+ await serverDB.insert(users).values({ id: 'read-other-user' });+ await serverDB+ .insert(topics)+ .values({ id: 'read-3', status: 'unread', userId: 'read-other-user' });++ expect(await topicModel.markRead('read-3')).toEqual([]);+ expect(await statusOf('read-3')).toBe('unread');+ });+ });});diff --git a/packages/database/src/models/topic/index.ts b/packages/database/src/models/topic/index.tsindex e5082507c77..8f4b1083b14 100644--- a/packages/database/src/models/topic/index.ts+++ b/packages/database/src/models/topic/index.ts@@ -173,6 +173,7 @@ export class TopicModel {update = this.withContext(update.update);settleRunningStatus = this.withContext(update.settleRunningStatus);+ markRead = this.withContext(update.markRead);recomputeUsage = this.withContext(update.recomputeUsage);updateMetadata = this.withContext(update.updateMetadata);updateModelPin = this.withContext(update.updateModelPin);diff --git a/packages/database/src/models/topic/update.ts b/packages/database/src/models/topic/update.tsindex 80da6b3a931..fa179593145 100644--- a/packages/database/src/models/topic/update.ts+++ b/packages/database/src/models/topic/update.ts@@ -85,6 +85,24 @@ export const settleRunningStatus = async (.returning({ id: topics.id, status: topics.status });};+/**+ * Clear a topic's unread mark: `unread` β `active`.+ *+ * Guarded on `status = 'unread'` like `settleRunningStatus`, so a reader acting+ * on a stale copy of the row (a persisted list, another tab) degrades to a no-op+ * instead of overwriting a status that has moved on β a run started since, or+ * one now waiting for a human.+ *+ * Returns the cleared row, or nothing when the topic was not unread.+ */+export const markRead = async (ctx: TopicModelContext, id: string) => {+ return ctx.db+ .update(topics)+ .set({ status: 'active', updatedAt: new Date() })+ .where(and(eq(topics.id, id), eq(topics.status, 'unread'), ctx.ownership()))+ .returning({ id: topics.id, status: topics.status });+};+/*** Recompute this topic's denormalized usage/cost rollup from its assistant* messages. The canonical aggregation lives in `recomputeTopicUsage`; thediff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsxindex 83cd5d9a184..658e9878408 100644--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx@@ -467,6 +467,25 @@ describe('TopicItem active state', () => {expect(screen.getByTestId('topic-unread-dot')).toBeInTheDocument();});+ /** @example A project row is not in the chat store, so only its own status says unread. */+ it('shows the unread dot for a project row whose own status is unread', () => {+ scopedTopicMock.value = { agentId: 'other-agent', agentName: 'Other Agent' };+ useTopicNavigationMock.mockReturnValue({+ isInAgentSubRoute: false,+ isInTopicContextRoute: false,+ navigateToTopic: vi.fn(),+ routeTopicId: undefined,+ });++ render(+ <TopicListScopeContext value={{ projectId: 'project-1' }}>+ <TopicItem id="project-topic" status="unread" title="Project work" />+ </TopicListScopeContext>,+ );++ expect(screen.getByTestId('topic-unread-dot')).toBeInTheDocument();+ });+it('shows the pull request marker once the topic is no longer unread', () => {topicMetaCardMock.value = { pullRequest: { state: 'open' } };useTopicNavigationMock.mockReturnValue({diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsxindex 560ef88b2f1..3f05f655165 100644--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx@@ -386,7 +386,9 @@ const TopicItemRow = memo<TopicItemRowProps>(// while the user is viewing the topic, like markTopicUnread's own guard.const isRunningTailUnread = isMaskedRunningTail && !isTopicActive;- const hasUnread = id && (isUnreadCompleted || isRunningTailUnread);+ // `status` is the row's own copy: a project list keeps its topics outside+ // the chat store, so `isUnreadCompleted` never sees them there.+ const hasUnread = id && (isUnreadCompleted || status === 'unread' || isRunningTailUnread);useEffect(() => {if (!activeAgentId || !id || !isUnreadCompleted || hasLocalRunningRuntime) return;diff --git a/src/features/Conversation/hooks/useClearActiveTopicUnread.ts b/src/features/Conversation/hooks/useClearActiveTopicUnread.tsindex cac80bcd2bc..6e3bd249072 100644--- a/src/features/Conversation/hooks/useClearActiveTopicUnread.ts+++ b/src/features/Conversation/hooks/useClearActiveTopicUnread.ts@@ -26,6 +26,6 @@ export const useClearActiveTopicUnread = () => {const markTopicRead = useChatStore((s) => s.markTopicRead);useEffect(() => {- if (activeTopicId && isActiveTopicUnread) markTopicRead({ topicId: activeTopicId });+ if (activeTopicId && isActiveTopicUnread) void markTopicRead({ topicId: activeTopicId });}, [activeTopicId, isActiveTopicUnread, markTopicRead]);};diff --git a/src/features/Projects/Conversation/index.tsx b/src/features/Projects/Conversation/index.tsxindex ee53e652668..98758af615a 100644--- a/src/features/Projects/Conversation/index.tsx+++ b/src/features/Projects/Conversation/index.tsx@@ -26,6 +26,7 @@ import {import { getProjectConversationPath } from '../Layout/navigation';import { freshProjectTopicAgentId } from './freshProjectTopicAgentId';+import { useMarkProjectTopicRead } from './useMarkProjectTopicRead';import { useProjectDraftStaging } from './useProjectDraftStaging';import { useRevalidateWhileUnlisted } from './useRevalidateWhileUnlisted';@@ -87,6 +88,7 @@ const ProjectConversation = memo(() => {const agent = useInitAgentConfig(conversationAgentId);const topicDetail = useChatStore((s) => s.useFetchTopicDetail)(selectedTopic?.id);+ useMarkProjectTopicRead(detail?.project.id, selectedTopic);useLayoutEffect(() => {if (!conversationAgentId) return;diff --git a/src/features/Projects/Conversation/useMarkProjectTopicRead.test.ts b/src/features/Projects/Conversation/useMarkProjectTopicRead.test.tsnew file mode 100644index 00000000000..7cabd653630--- /dev/null+++ b/src/features/Projects/Conversation/useMarkProjectTopicRead.test.ts@@ -0,0 +1,67 @@+import { renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useChatStore } from '@/store/chat';+import { type ProjectTopic } from '@/store/projectWorkingDirectory/projection';++import { useMarkProjectTopicRead } from './useMarkProjectTopicRead';++const revalidateReplica = vi.hoisted(() => vi.fn());+vi.mock('@/libs/replica', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ revalidateReplica,+}));++const topic = (status: ProjectTopic['status']) =>+ ({ agentId: 'agent-1', id: 'topic-1', status }) as ProjectTopic;++describe('useMarkProjectTopicRead', () => {+ const markTopicRead = vi.fn();++ beforeEach(() => {+ markTopicRead.mockReset().mockResolvedValue(undefined);+ revalidateReplica.mockReset();+ useChatStore.setState({ markTopicRead });+ });++ afterEach(() => {+ useChatStore.setState(useChatStore.getInitialState());+ });++ /** @example A run that finished while unwatched must leave "pending" once the project conversation is opened. */+ it('marks the open unread conversation read and refreshes the project rows', async () => {+ renderHook(() => useMarkProjectTopicRead('prj-1', topic('unread')));++ expect(markTopicRead).toHaveBeenCalledWith({+ agentId: 'agent-1',+ status: 'unread',+ topicId: 'topic-1',+ });+ await waitFor(() =>+ expect(revalidateReplica).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'projectTopics' }),+ 'prj-1',+ ),+ );+ });++ it('clears a conversation that turns unread while it is open', () => {+ const { rerender } = renderHook(+ ({ status }) => useMarkProjectTopicRead('prj-1', topic(status)),+ {+ initialProps: { status: 'running' as ProjectTopic['status'] },+ },+ );+ expect(markTopicRead).not.toHaveBeenCalled();++ rerender({ status: 'unread' });++ expect(markTopicRead).toHaveBeenCalledTimes(1);+ });++ it('leaves a read conversation alone', () => {+ renderHook(() => useMarkProjectTopicRead('prj-1', topic('active')));++ expect(markTopicRead).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Projects/Conversation/useMarkProjectTopicRead.ts b/src/features/Projects/Conversation/useMarkProjectTopicRead.tsnew file mode 100644index 00000000000..397e9e75a4f--- /dev/null+++ b/src/features/Projects/Conversation/useMarkProjectTopicRead.ts@@ -0,0 +1,32 @@+import { useEffect } from 'react';++import { revalidateReplica } from '@/libs/replica';+import { useChatStore } from '@/store/chat';+import {+ type ProjectTopic,+ projectTopicsResource,+} from '@/store/projectWorkingDirectory/projection';++/**+ * Clear the unread mark of the project conversation being read.+ *+ * The Agent route clears it through `switchTopic` and `useClearActiveTopicUnread`,+ * which both read the status from the chat store's `topicDataMap`. A project+ * lists its conversations in its own replica, so neither sees the topic and a+ * finished run stayed under "pending" while the user was reading it. This reads+ * the status from the project row and refreshes the rows once the write lands.+ */+export const useMarkProjectTopicRead = (projectId?: string, topic?: ProjectTopic) => {+ const markTopicRead = useChatStore((s) => s.markTopicRead);+ const topicId = topic?.id;+ const agentId = topic?.agentId ?? undefined;+ const isUnread = topic?.status === 'unread';++ useEffect(() => {+ if (!projectId || !topicId || !isUnread) return;++ void markTopicRead({ agentId, status: 'unread', topicId }).then(() =>+ revalidateReplica(projectTopicsResource, projectId),+ );+ }, [agentId, isUnread, markTopicRead, projectId, topicId]);+};diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex 5493cbee44c..e1288ccab70 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -202,6 +202,11 @@ export class TopicService {return lambdaClient.topic.updateTopicMetadata.mutate({ id, metadata });};+ /** `unread` β `active` only while the topic is still unread; `null` when it was not. */+ markTopicRead = (id: string) => {+ return lambdaClient.topic.markTopicRead.mutate({ id });+ };+settleRunningOperation = (id: string,operationId: string,diff --git a/src/store/chat/slices/operation/__tests__/markTopicRead.test.ts b/src/store/chat/slices/operation/__tests__/markTopicRead.test.tsnew file mode 100644index 00000000000..268fd0b1e91--- /dev/null+++ b/src/store/chat/slices/operation/__tests__/markTopicRead.test.ts@@ -0,0 +1,163 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { topicService } from '@/services/topic';+import { useChatStore } from '@/store/chat/store';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';++const AGENT_ID = 'agent-1';+const TOPIC_ID = 'topic-1';+const RUN_TOPIC_ID = 'topic-run';+const BUCKET = topicMapKey({ agentId: AGENT_ID });++const seedBucket = (status: 'unread' | 'active', id = TOPIC_ID) =>+ useChatStore.setState({+ topicDataMap: {+ [BUCKET]: { hasMore: false, items: [{ id, status, title: 't' } as any] } as any,+ },+ });++const bucketStatus = (id = TOPIC_ID) =>+ useChatStore.getState().topicDataMap[BUCKET]?.items?.find((t) => t.id === id)?.status;++describe('markTopicRead', () => {+ beforeEach(() => {+ useChatStore.setState(useChatStore.getInitialState());+ useChatStore.setState({ activeAgentId: AGENT_ID });+ vi.spyOn(topicService, 'markTopicRead').mockResolvedValue({+ id: TOPIC_ID,+ status: 'active',+ } as any);+ vi.spyOn(topicService, 'updateTopic').mockResolvedValue(undefined as any);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('clears an unread topic loaded in the topic buckets and mirrors it locally', async () => {+ seedBucket('unread');++ await useChatStore.getState().markTopicRead({ agentId: AGENT_ID, topicId: TOPIC_ID });++ expect(topicService.markTopicRead).toHaveBeenCalledWith(TOPIC_ID);+ expect(bucketStatus()).toBe('active');+ });++ it('leaves a topic it cannot see alone', async () => {+ await useChatStore.getState().markTopicRead({ agentId: AGENT_ID, topicId: TOPIC_ID });++ expect(topicService.markTopicRead).not.toHaveBeenCalled();+ });++ /** @example A project conversation lives in the project replica, not in `topicDataMap`. */+ it('clears a topic outside the topic buckets when the caller knows it is unread', async () => {+ await useChatStore+ .getState()+ .markTopicRead({ agentId: AGENT_ID, status: 'unread', topicId: TOPIC_ID });++ expect(topicService.markTopicRead).toHaveBeenCalledWith(TOPIC_ID);+ });++ it('skips the write when the caller reports a status other than unread', async () => {+ await useChatStore+ .getState()+ .markTopicRead({ agentId: AGENT_ID, status: 'running', topicId: TOPIC_ID });++ expect(topicService.markTopicRead).not.toHaveBeenCalled();+ });++ /**+ * @example A persisted project row still says unread, but a run started since+ * on another device: the server keeps `running`, so nothing writes `active`.+ */+ it('never writes active itself and mirrors nothing when the server says the topic moved on', async () => {+ vi.mocked(topicService.markTopicRead).mockResolvedValue(null);+ seedBucket('unread');++ await useChatStore.getState().markTopicRead({ agentId: AGENT_ID, topicId: TOPIC_ID });++ expect(topicService.updateTopic).not.toHaveBeenCalled();+ expect(bucketStatus()).toBe('unread');+ });++ /**+ * @example The user sends a message while the clear is in flight: the clear's+ * `active` answer is already stale and must not replace the run's status.+ */+ it('keeps a run that started while the clear was in flight', async () => {+ // Pins outlive `setState` resets, so this topic is kept apart from the others.+ let answer!: (value: any) => void;+ vi.mocked(topicService.markTopicRead).mockReturnValue(+ new Promise((resolve) => (answer = resolve)) as any,+ );+ seedBucket('unread', RUN_TOPIC_ID);++ const clearing = useChatStore+ .getState()+ .markTopicRead({ agentId: AGENT_ID, topicId: RUN_TOPIC_ID });+ useChatStore+ .getState()+ .internal_pinTopicStatus({ agentId: AGENT_ID, status: 'running', topicId: RUN_TOPIC_ID });+ answer({ id: RUN_TOPIC_ID, status: 'active' });+ await clearing;++ expect(bucketStatus(RUN_TOPIC_ID)).toBe('running');+ });++ describe('when the clear fails', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ useChatStore.setState({ activeTopicId: TOPIC_ID });+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ /** @example The open conversation must not stay unread after a dropped request. */+ it('retries a transient failure while the topic stays open', async () => {+ vi.mocked(topicService.markTopicRead)+ .mockRejectedValueOnce(new TypeError('Failed to fetch'))+ .mockResolvedValueOnce({ id: TOPIC_ID, status: 'active' } as any);+ seedBucket('unread');++ const clearing = useChatStore+ .getState()+ .markTopicRead({ agentId: AGENT_ID, topicId: TOPIC_ID });+ await vi.runAllTimersAsync();+ await clearing;++ expect(topicService.markTopicRead).toHaveBeenCalledTimes(2);+ expect(bucketStatus()).toBe('active');+ });++ it('does not retry a client error', async () => {+ vi.mocked(topicService.markTopicRead).mockRejectedValue({ data: { httpStatus: 403 } });+ seedBucket('unread');++ const clearing = useChatStore+ .getState()+ .markTopicRead({ agentId: AGENT_ID, topicId: TOPIC_ID });+ await vi.runAllTimersAsync();+ await clearing;++ expect(topicService.markTopicRead).toHaveBeenCalledTimes(1);+ expect(bucketStatus()).toBe('unread');+ });++ it('stops retrying once the user leaves the topic', async () => {+ vi.mocked(topicService.markTopicRead).mockRejectedValue(new TypeError('Failed to fetch'));+ seedBucket('unread');++ const clearing = useChatStore+ .getState()+ .markTopicRead({ agentId: AGENT_ID, topicId: TOPIC_ID });+ useChatStore.setState({ activeTopicId: 'another-topic' });+ await vi.runAllTimersAsync();+ await clearing;++ expect(topicService.markTopicRead).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.tsindex 8c5cf662401..5647d092333 100644--- a/src/store/chat/slices/operation/actions.ts+++ b/src/store/chat/slices/operation/actions.ts@@ -2,12 +2,14 @@ import { nanoid } from '@lobechat/utils';import debug from 'debug';import { produce } from 'immer';+import { topicService } from '@/services/topic';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 { type ChatTopicStatus } from '@/types/topic';import { setNamespace } from '@/utils/storeDebug';import { operationSelectors } from './selectors';@@ -26,6 +28,14 @@ import {} from './types';const n = setNamespace('operation');+const MARK_READ_RETRY_BASE_MS = 1000;++/** A network failure (no HTTP status) or a 5xx may pass on retry; a 4xx will not. */+const isRetryableWriteError = (error: unknown) => {+ const status = (error as { data?: { httpStatus?: unknown } } | null)?.data?.httpStatus;+ return typeof status !== 'number' || status >= 500;+};+const log = debug('lobe-store:operation');const isSameNullableContextValue = (left?: string | null, right?: string | null): boolean =>@@ -803,37 +813,65 @@ export class OperationActionsImpl {/*** 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.+ * Invoked when the user opens the topic.+ *+ * `status` is the caller's own copy of the topic's status, for surfaces that+ * list topics outside `topicDataMap` (the project sidebar); without it the+ * status is read from the loaded topic buckets. That copy may be stale (a+ * persisted list, another tab), so the server write is conditional on the row+ * still being unread, and the local mirror never outranks a newer transition β+ * a run started since keeps its `running` status. A transient failure is+ * retried while the topic stays open, since the callers fire once per open.*/- markTopicRead = ({+ markTopicRead = async ({agentId,groupId,+ status,topicId,}: {agentId?: string;groupId?: string | null;+ status?: ChatTopicStatus | null;topicId?: string | null;- }): void => {+ }): Promise<void> => {if (!topicId) return;const key = topicMapKey({agentId: agentId ?? this.#get().activeAgentId,groupId: groupId ?? this.#get().activeGroupId,});- const topic = this.#get().topicDataMap[key]?.items?.find((t) => t.id === topicId);- if (topic?.status !== 'unread') return;+ const knownStatus =+ status === undefined+ ? this.#get().topicDataMap[key]?.items?.find((t) => t.id === topicId)?.status+ : status;+ if (knownStatus !== 'unread') return;- void this.#get()- .updateTopicStatus?.({- agentId,- groupId: groupId ?? undefined,- status: 'active',- topicId,- })- ?.then(() => {- void getHomeStoreState().refreshAgentList?.();- });+ const cleared = await this.#clearUnread(topicId);+ if (!cleared) return;++ this.#get().internal_settleTopicRead?.({ agentId, groupId: groupId ?? undefined, topicId });+ void getHomeStoreState().refreshAgentList?.();+ };++ /**+ * The conditional server clear, retried with backoff while the topic stays+ * open. A 4xx will not change on retry, so it ends the attempt.+ */+ #clearUnread = async (topicId: string) => {+ for (let attempt = 0; ; attempt += 1) {+ try {+ return await topicService.markTopicRead(topicId);+ } catch (error) {+ if (!isRetryableWriteError(error)) {+ console.error('[markTopicRead] persist failed:', error);+ return null;+ }+ await new Promise((resolve) =>+ setTimeout(resolve, Math.min(MARK_READ_RETRY_BASE_MS * 2 ** attempt, 30_000)),+ );+ if (this.#get().activeTopicId !== topicId) return null;+ }+ }};// βββ Message Queue Actions βββdiff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 87ba9180eba..9befffc50ca 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -70,6 +70,7 @@ import { setNamespace } from '@/utils/storeDebug';import { displayMessageSelectors } from '../message/selectors';import { type TopicData } from './initialState';+import { type PendingTopicStatusSource, PendingTopicStatusWrites } from './pendingStatusWrites';import {applyTopicDispatchToBucket,normalizeTopicListParams,@@ -129,8 +130,6 @@ type TopicPatchScope = {scope?: TopicMapScope;};-type PendingTopicStatusSource = 'cache' | 'server';-/*** Options for switchTopic action*/@@ -884,72 +883,15 @@ export class ChatTopicActionImpl {throw error;};- /**- * Optimistic `updateTopicStatus` writes that a topic-list refetch must not- * clobber. A refetch whose server query ran BEFORE a status write can land- * AFTER the optimistic dispatch and revert the row β e.g. a run-end 'unread'- * reverting to 'running', leaving the sidebar spinning forever on a finished- * topic. Fetched rows are reconciled against this map: a row still carrying- * the pre-write status gets the pending status re-applied; a row already- * reflecting it confirms propagation and drops the pin. TTL-bounded so a- * failed persist or a legit cross-device status change can't be suppressed- * indefinitely.- */- #pendingTopicStatusWrites = new Map<string, { expiresAt: number; status: ChatTopicStatus }>();-- /**- * Reconcile ONE server-sourced row against the pending optimistic writes.- *- * Every path that brings a topic row back from the server must go through- * here before the row reaches the store β list fetches, search, and the- * single-topic pull in {@link syncScheduledTopicRun} alike. A path that- * bypasses it silently reverts whatever the user just did, and the reader- * that trips it is usually the one the optimistic write itself woke up.- *- * Returns the row to trust: the fetched one, or the fetched one with the- * pending status re-applied when it predates the write.- */- #applyPendingStatusWrite = (item: ChatTopic, source: PendingTopicStatusSource): ChatTopic => {- const pending = this.#pendingTopicStatusWrites.get(item.id);- if (!pending) return item;- if (pending.expiresAt <= Date.now()) {- this.#pendingTopicStatusWrites.delete(item.id);- return item;- }- if (item.status === pending.status) {- if (source === 'server') this.#pendingTopicStatusWrites.delete(item.id);- return item;- }- return { ...item, status: pending.status };- };-- /**- * Apply pending terminal statuses before a fetched topic list enters SWR.- *- * Reconciling only in `onData` keeps Zustand correct but is too late for the- * persisted cache: SWR has already accepted the older raw response and can- * flush `running` to IndexedDB. After the 15-second pin expires, remounting- * the sidebar restores that stale spinner. This step deliberately- * handles statuses only; client-only optimistic rows are still added later by- * {@link #reconcileFetchedTopics} and never enter the persisted response.- * Persisting the pin also means a failed write can survive until the next- * successful revalidation; that bounded, self-healing window is preferable to- * reintroducing an older response after a confirmed local terminal event.- */- #applyPendingStatusWrites = (- items: ChatTopic[],- source: PendingTopicStatusSource,- ): ChatTopic[] => {- if (this.#pendingTopicStatusWrites.size === 0) return items;- return items.map((item) => this.#applyPendingStatusWrite(item, source));- };+ /** Optimistic status writes a refetch must not clobber β see {@link PendingTopicStatusWrites}. */+ #pendingTopicStatusWrites = new PendingTopicStatusWrites();#reconcileFetchedTopics = (items: ChatTopic[],currentItems: ChatTopic[] | undefined,source: PendingTopicStatusSource,): ChatTopic[] => {- let next = this.#applyPendingStatusWrites(items, source);+ let next = this.#pendingTopicStatusWrites.applyAll(items, source);// In-flight first-send optimistic rows are client-only, so any refetch// landing mid-send (e.g. the fire-and-forget refreshTopic after a previous@@ -1065,7 +1007,7 @@ export class ChatTopicActionImpl {await topicService.updateTopic(topicId, patch).catch((err) => {console.error('[updateTopicStatus] persist failed:', err);// The DB never got the write β stop pinning it over fetched rows.- this.#pendingTopicStatusWrites.delete(topicId);+ this.#pendingTopicStatusWrites.drop(topicId);});};@@ -1109,7 +1051,7 @@ export class ChatTopicActionImpl {const patch: Partial<ChatTopic> =status === 'completed' ? { completedAt: new Date(), status } : { status };- this.#pendingTopicStatusWrites.set(topicId, { expiresAt: Date.now() + 15_000, status });+ this.#pendingTopicStatusWrites.pin(topicId, status);// Scope on the payload routes the write to the owning bucket inside// `internal_dispatchTopic`. A no-op if the bucket isn't loaded; the pin@@ -1124,6 +1066,34 @@ export class ChatTopicActionImpl {});};+ /**+ * Local mirror of a server-confirmed `unread β active` clear (`markTopicRead`).+ * Unlike {@link internal_pinTopicStatus} it never pins: the clear's response+ * may already be stale when it lands (a run started meanwhile, here or on+ * another device), so a newer pending write wins and the next fetch stays+ * authoritative. Only a loaded row that is still unread follows.+ */+ internal_settleTopicRead = (params: { agentId?: string; groupId?: string; topicId: string }) => {+ const { agentId, groupId, topicId } = params;+ if (!this.#pendingTopicStatusWrites.settle(topicId, 'unread')) return;++ const state = this.#get();+ const key = topicMapKey({+ agentId: agentId ?? state.activeAgentId,+ groupId: groupId ?? state.activeGroupId,+ });+ const topic = state.topicDataMap[key]?.items?.find((t) => t.id === topicId);+ if (topic?.status !== 'unread') return;++ state.internal_dispatchTopic({+ type: 'updateTopic',+ id: topicId,+ value: { status: 'active' },+ agentId,+ groupId,+ });+ };+#getTopicUpdatedAt = (topic: RunningTopicForWatchdog): number | undefined => {const timestamp =typeof topic.updatedAt === 'number' ? topic.updatedAt : new Date(topic.updatedAt).getTime();@@ -1276,7 +1246,7 @@ export class ChatTopicActionImpl {// (the button reading as a no-op until pressed a second time). The pin is// dropped when the persist fails, so a write that never reached the DB// still reverts here.- const fresh = this.#applyPendingStatusWrite(fetched, 'server');+ const fresh = this.#pendingTopicStatusWrites.apply(fetched, 'server');if (fresh.status !== fetched.status) return false;// Server still parked β nothing to fold in.@@ -1350,7 +1320,7 @@ export class ChatTopicActionImpl {pageSize,...query,});- const items = this.#applyPendingStatusWrites(result.items, 'server');+ const items = this.#pendingTopicStatusWrites.applyAll(result.items, 'server');if (isHead)this.#prefetchUnreadTopicMessages(items, this.#get().topicDataMap[containerKey]?.items, {agentId,@@ -1374,7 +1344,7 @@ export class ChatTopicActionImpl {withDetails,});return {- items: this.#applyPendingStatusWrites(result.items, 'server'),+ items: this.#pendingTopicStatusWrites.applyAll(result.items, 'server'),total: result.total,};};@@ -1600,7 +1570,7 @@ export class ChatTopicActionImpl {);if (activeAgentId) {- this.#get().markTopicRead({ agentId: activeAgentId, topicId: id ?? null });+ void this.#get().markTopicRead({ agentId: activeAgentId, topicId: id ?? null });}if (opts.skipRefreshMessage) return;diff --git a/src/store/chat/slices/topic/pendingStatusWrites.test.ts b/src/store/chat/slices/topic/pendingStatusWrites.test.tsnew file mode 100644index 00000000000..23eb3e07ae4--- /dev/null+++ b/src/store/chat/slices/topic/pendingStatusWrites.test.ts@@ -0,0 +1,75 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { ChatTopic } from '@/types/topic';++import { PendingTopicStatusWrites } from './pendingStatusWrites';++const row = (status: ChatTopic['status']) => ({ id: 'topic-1', status }) as ChatTopic;++describe('PendingTopicStatusWrites', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('re-applies a pinned status over a fetched row that predates it', () => {+ const writes = new PendingTopicStatusWrites();+ writes.pin('topic-1', 'unread');++ expect(writes.apply(row('running'), 'server').status).toBe('unread');+ });++ it('drops the pin once a server row confirms it', () => {+ const writes = new PendingTopicStatusWrites();+ writes.pin('topic-1', 'unread');++ writes.apply(row('unread'), 'server');++ expect(writes.apply(row('running'), 'server').status).toBe('running');+ });++ it('stops overriding fetched rows after the pin expires', () => {+ vi.useFakeTimers();+ const writes = new PendingTopicStatusWrites();+ writes.pin('topic-1', 'unread');++ vi.advanceTimersByTime(15_001);++ expect(writes.apply(row('running'), 'server').status).toBe('running');+ });++ describe('settle', () => {+ /** @example A clear that landed must not let the old unread pin bring the dot back. */+ it('drops the pin the compare-and-set replaced', () => {+ const writes = new PendingTopicStatusWrites();+ writes.pin('topic-1', 'unread');++ expect(writes.settle('topic-1', 'unread')).toBe(true);+ expect(writes.apply(row('active'), 'server').status).toBe('active');+ });++ /** @example A run started while the clear was in flight keeps its own pin. */+ it('yields to a newer pending write', () => {+ const writes = new PendingTopicStatusWrites();+ writes.pin('topic-1', 'running');++ expect(writes.settle('topic-1', 'unread')).toBe(false);+ expect(writes.apply(row('active'), 'server').status).toBe('running');+ });++ it('adds no pin of its own, so a later fetch stays authoritative', () => {+ const writes = new PendingTopicStatusWrites();++ expect(writes.settle('topic-1', 'unread')).toBe(true);+ expect(writes.apply(row('running'), 'server').status).toBe('running');+ });++ it('ignores an expired newer write', () => {+ vi.useFakeTimers();+ const writes = new PendingTopicStatusWrites();+ writes.pin('topic-1', 'running');+ vi.advanceTimersByTime(15_001);++ expect(writes.settle('topic-1', 'unread')).toBe(true);+ });+ });+});diff --git a/src/store/chat/slices/topic/pendingStatusWrites.ts b/src/store/chat/slices/topic/pendingStatusWrites.tsnew file mode 100644index 00000000000..4ee5058bb16--- /dev/null+++ b/src/store/chat/slices/topic/pendingStatusWrites.ts@@ -0,0 +1,87 @@+import type { ChatTopic, ChatTopicStatus } from '@/types/topic';++export type PendingTopicStatusSource = 'cache' | 'server';++const PENDING_STATUS_TTL_MS = 15_000;++/**+ * Optimistic `updateTopicStatus` writes that a topic-list refetch must not+ * clobber. A refetch whose server query ran BEFORE a status write can land+ * AFTER the optimistic dispatch and revert the row β e.g. a run-end 'unread'+ * reverting to 'running', leaving the sidebar spinning forever on a finished+ * topic. Fetched rows are reconciled against these writes: a row still carrying+ * the pre-write status gets the pending status re-applied; a row already+ * reflecting it confirms propagation and drops the pin. TTL-bounded so a+ * failed persist or a legit cross-device status change can't be suppressed+ * indefinitely.+ */+export class PendingTopicStatusWrites {+ #writes = new Map<string, { expiresAt: number; status: ChatTopicStatus }>();++ pin = (topicId: string, status: ChatTopicStatus) => {+ this.#writes.set(topicId, { expiresAt: Date.now() + PENDING_STATUS_TTL_MS, status });+ };++ drop = (topicId: string) => {+ this.#writes.delete(topicId);+ };++ /**+ * Reconcile ONE server-sourced row against the pending optimistic writes.+ *+ * Every path that brings a topic row back from the server must go through+ * here before the row reaches the store β list fetches, search, and the+ * single-topic pull in `syncScheduledTopicRun` alike. A path that bypasses+ * it silently reverts whatever the user just did, and the reader that trips+ * it is usually the one the optimistic write itself woke up.+ *+ * Returns the row to trust: the fetched one, or the fetched one with the+ * pending status re-applied when it predates the write.+ */+ apply = (item: ChatTopic, source: PendingTopicStatusSource): ChatTopic => {+ const pending = this.#writes.get(item.id);+ if (!pending) return item;+ if (pending.expiresAt <= Date.now()) {+ this.#writes.delete(item.id);+ return item;+ }+ if (item.status === pending.status) {+ if (source === 'server') this.#writes.delete(item.id);+ return item;+ }+ return { ...item, status: pending.status };+ };++ /**+ * Apply pending terminal statuses before a fetched topic list enters SWR.+ *+ * Reconciling only in `onData` keeps Zustand correct but is too late for the+ * persisted cache: SWR has already accepted the older raw response and can+ * flush `running` to IndexedDB. After the 15-second pin expires, remounting+ * the sidebar restores that stale spinner. This step deliberately+ * handles statuses only; client-only optimistic rows are still added later by+ * the store's fetched-topic reconciliation and never enter the persisted+ * response. Persisting the pin also means a failed write can survive until the+ * next successful revalidation; that bounded, self-healing window is+ * preferable to reintroducing an older response after a confirmed local+ * terminal event.+ */+ applyAll = (items: ChatTopic[], source: PendingTopicStatusSource): ChatTopic[] => {+ if (this.#writes.size === 0) return items;+ return items.map((item) => this.apply(item, source));+ };++ /**+ * Fold in a server-confirmed compare-and-set away from `from` without adding+ * a pin: its response may already be stale when it lands, so the next fetch+ * has to stay authoritative. A live write to any other status is a newer+ * local transition and wins (returns `false`); a pin still at `from` is+ * exactly what the server just replaced, so it is dropped.+ */+ settle = (topicId: string, from: ChatTopicStatus): boolean => {+ const pending = this.#writes.get(topicId);+ if (pending && pending.expiresAt > Date.now() && pending.status !== from) return false;+ this.#writes.delete(topicId);+ return true;+ };+}