π€― 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(topic): drop switchTopic race under rapid sidebar clicks (#14115)
Arvin Xub9a4a9093c48
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsxindex 1dc090a4fd5..aca4854da2e 100644--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx@@ -2,7 +2,7 @@ import type { ChatTopicMetadata, ChatTopicStatus } from '@lobechat/types';import { Flexbox, Icon, Skeleton, Tag } from '@lobehub/ui';import { createStaticStyles, cssVar, keyframes, useTheme } from 'antd-style';import { CheckCircle2, HashIcon, MessageSquareDashed } from 'lucide-react';-import { memo, Suspense, useCallback, useMemo, useRef } from 'react';+import { memo, Suspense, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import DotsLoading from '@/components/DotsLoading';@@ -71,6 +71,18 @@ const styles = createStaticStyles(({ css }) => ({`,}));+// Module-scoped so a click on any topic cancels a pending click on another.+// Per-item refs can't do that, which lets rapid clicks across items all+// fire β each racing to write activeTopicId (see LOBE-7785).+let pendingSingleClickTimer: ReturnType<typeof setTimeout> | null = null;++const cancelPendingSingleClick = () => {+ if (pendingSingleClickTimer) {+ clearTimeout(pendingSingleClickTimer);+ pendingSingleClickTimer = null;+ }+};+interface TopicItemProps {active?: boolean;fav?: boolean;@@ -125,13 +137,12 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, meta[id],);- const clickTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);-const handleClick = useCallback(() => {if (editing) return;if (isDesktop) {- clickTimerRef.current = setTimeout(() => {- clickTimerRef.current = null;+ cancelPendingSingleClick();+ pendingSingleClickTimer = setTimeout(() => {+ pendingSingleClickTimer = null;void navigateToTopic(id);}, 250);} else {@@ -141,10 +152,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, metaconst handleDoubleClick = useCallback(async () => {if (!id || !activeAgentId || !isDesktop) return;- if (clickTimerRef.current) {- clearTimeout(clickTimerRef.current);- clickTimerRef.current = null;- }+ cancelPendingSingleClick();if (await focusTopicPopup(id)) {void navigateToTopic(id, { skipPopupFocus: true });return;diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsxindex f36b01ff2b4..61aa7e08cd3 100644--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx@@ -3,7 +3,7 @@ import { Flexbox, Icon, Skeleton, Tag } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';import { CheckCircle2, HashIcon, Loader2Icon, MessageSquareDashed } from 'lucide-react';import { AnimatePresence, m } from 'motion/react';-import { memo, Suspense, useCallback, useMemo, useRef } from 'react';+import { memo, Suspense, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import DotsLoading from '@/components/DotsLoading';@@ -58,6 +58,18 @@ const styles = createStaticStyles(({ css }) => ({`,}));+// Module-scoped so a click on any topic cancels a pending click on another.+// Per-item refs can't do that, which lets rapid clicks across items all+// fire β each racing to write activeTopicId (see LOBE-7785).+let pendingSingleClickTimer: ReturnType<typeof setTimeout> | null = null;++const cancelPendingSingleClick = () => {+ if (pendingSingleClickTimer) {+ clearTimeout(pendingSingleClickTimer);+ pendingSingleClickTimer = null;+ }+};+interface TopicItemProps {active?: boolean;fav?: boolean;@@ -96,13 +108,12 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stat[id],);- const clickTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);-const handleClick = useCallback(() => {if (editing) return;if (isDesktop) {- clickTimerRef.current = setTimeout(() => {- clickTimerRef.current = null;+ cancelPendingSingleClick();+ pendingSingleClickTimer = setTimeout(() => {+ pendingSingleClickTimer = null;void (async () => {await focusTopicPopup(id);switchTopic(id);@@ -120,10 +131,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, statconst handleDoubleClick = useCallback(async () => {if (!id || !activeGroupId || !isDesktop) return;- if (clickTimerRef.current) {- clearTimeout(clickTimerRef.current);- clickTimerRef.current = null;- }+ cancelPendingSingleClick();if (await focusTopicPopup(id)) {switchTopic(id);toggleMobileTopic(false);diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 4cfdf5f0b8f..b03d8c1601c 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -752,6 +752,23 @@ describe('topic action', () => {// Verify activeTopicId is set to the new topicexpect(useChatStore.getState().activeTopicId).toBe('new-created-topic-id');});++ it('should skip refreshMessages for superseded overlapping switches', async () => {+ const { result } = renderHook(() => useChatStore());+ const refreshSpy = vi.spyOn(result.current, 'refreshMessages').mockResolvedValue(undefined);++ // Fire two overlapping switches: the sync body of both runs before+ // either yields, so by the microtask boundary the second has already+ // bumped the epoch and the first should bail out before fetching.+ await act(async () => {+ const p1 = result.current.switchTopic('topic-a');+ const p2 = result.current.switchTopic('topic-b');+ await Promise.all([p1, p2]);+ });++ expect(refreshSpy).toHaveBeenCalledTimes(1);+ expect(useChatStore.getState().activeTopicId).toBe('topic-b');+ });});describe('removeSessionTopics', () => {it('should remove all topics from the current session and refresh the topic list', async () => {diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 76d3887506a..0bb71be87b4 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -70,6 +70,12 @@ export class ChatTopicActionImpl {readonly #get: () => ChatStore;readonly #set: Setter;+ // Monotonic token for switchTopic. Each call increments it and captures a+ // local copy; after awaited work, a mismatch means a newer switch has+ // started and our continuation is stale β drop it rather than let it+ // clobber the newer topic (see LOBE-7785).+ #switchTopicEpoch = 0;+constructor(set: Setter, get: () => ChatStore, _api?: unknown) {void _api;this.#set = set;@@ -521,6 +527,7 @@ export class ChatTopicActionImpl {switchTopic = async (id?: string | null, options?: SwitchTopicOptions): Promise<void> => {const opts = options ?? {};+ const epoch = ++this.#switchTopicEpoch;const { activeAgentId, activeGroupId } = this.#get();@@ -561,6 +568,14 @@ export class ChatTopicActionImpl {}if (opts.skipRefreshMessage) return;++ // Yield a microtask so any switchTopic calls queued behind us can run+ // their sync bodies (and bump #switchTopicEpoch) before we commit to a+ // refresh. On the other side of the yield, an epoch mismatch means a+ // newer switch has taken over β skip the redundant SWR mutate.+ await Promise.resolve();+ if (epoch !== this.#switchTopicEpoch) return;+await this.#get().refreshMessages();};