Skip to content

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

πŸ› fix(sidebar): stop opening a new tab when a topic is double clicked (#23076)

YuTengjing40479e8690e3
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
index b28d1789d39..4c1ec0087b9 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
@@ -1,8 +1,8 @@
/**
* @vitest-environment happy-dom
*/
-import { render, screen, waitFor, within } from '@testing-library/react';
-import type { ReactNode } from 'react';
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import type { MouseEvent, ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { TopicListScopeContext } from '../../TopicListScope';
@@ -22,6 +22,12 @@ const onlyMineMock = vi.hoisted(() => ({ value: false }));
const currentUserIdMock = vi.hoisted(() => ({ value: 'user-1' as string | undefined }));
const goalsEnabledMock = vi.hoisted(() => ({ value: true }));
const hasDraftMock = vi.hoisted(() => ({ value: false }));
+const isDesktopMock = vi.hoisted(() => ({ value: false }));
+const electronTabMocks = vi.hoisted(() => ({
+ activateTab: vi.fn(),
+ addNewTab: vi.fn(),
+ addTab: vi.fn(),
+}));
const topicMetaCardMock = vi.hoisted(() => ({
value: undefined as
| {
@@ -58,7 +64,11 @@ vi.mock('motion/react-m', () => ({
vi.mock('../../useScopedTopics', () => ({ useScopedTopic: () => scopedTopicMock.value }));
-vi.mock('@/const/version', () => ({ isDesktop: false }));
+vi.mock('@/const/version', () => ({
+ get isDesktop() {
+ return isDesktopMock.value;
+ },
+}));
vi.mock('@/features/NavPanel/components/NavItem', () => ({
default: ({
actions,
@@ -67,6 +77,8 @@ vi.mock('@/features/NavPanel/components/NavItem', () => ({
extra,
href,
icon,
+ onClick,
+ onDoubleClick,
slots,
title,
}: {
@@ -76,10 +88,18 @@ vi.mock('@/features/NavPanel/components/NavItem', () => ({
extra?: ReactNode;
href?: string;
icon?: ReactNode;
+ onClick?: (event: MouseEvent) => void;
+ onDoubleClick?: (event: MouseEvent) => void;
slots?: { iconBelow?: ReactNode; titlePrefix?: ReactNode };
title?: ReactNode;
}) => (
- <div data-active={String(active)} data-href={href} data-testid="nav-item">
+ <div
+ data-active={String(active)}
+ data-href={href}
+ data-testid="nav-item"
+ onClick={onClick}
+ onDoubleClick={onDoubleClick}
+ >
<div data-testid="nav-item-leading">
{icon}
{slots?.iconBelow}
@@ -165,9 +185,10 @@ vi.mock('@/store/chat/selectors', () => ({
},
}));
vi.mock('@/store/electron', () => {
- const useElectronStore = (selector: (state: { addTab: () => void }) => unknown) =>
- selector({ addTab: vi.fn() });
- useElectronStore.getState = () => ({ addTab: vi.fn() });
+ const state = () => ({ ...electronTabMocks, activeTabId: undefined, tabs: [] });
+ const useElectronStore = (selector: (state: ReturnType<typeof state>) => unknown) =>
+ selector(state());
+ useElectronStore.getState = state;
return { useElectronStore };
});
vi.mock('../../hooks/useTopicNavigation', () => ({
@@ -690,3 +711,43 @@ describe('TopicItem mobile thread list', () => {
expect(screen.queryByTestId('thread-list')).not.toBeInTheDocument();
});
});
+
+// A lagging UI turns a repeated click into a double click, and a double click
+// used to open the topic in a new desktop tab. New tabs now take an explicit
+// gesture (Cmd/Ctrl+click, middle click, or the context menu).
+describe('TopicItem double click on desktop', () => {
+ beforeEach(() => {
+ isDesktopMock.value = true;
+ });
+
+ afterEach(() => {
+ isDesktopMock.value = false;
+ electronTabMocks.activateTab.mockClear();
+ electronTabMocks.addNewTab.mockClear();
+ electronTabMocks.addTab.mockClear();
+ });
+
+ it('switches to the topic without opening a new tab', async () => {
+ const navigateToTopic = vi.fn();
+ useTopicNavigationMock.mockReturnValue({
+ focusTopicPopup: vi.fn().mockResolvedValue(false),
+ isInAgentSubRoute: false,
+ isInTopicContextRoute: false,
+ navigateToTopic,
+ routeTopicId: undefined,
+ urlTopicId: undefined,
+ });
+
+ render(<TopicItem id="tpc_test" title="Topic" />);
+ const row = screen.getByTestId('nav-item');
+ fireEvent.click(row, { detail: 1 });
+ fireEvent.click(row, { detail: 2 });
+ fireEvent.doubleClick(row, { detail: 2 });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(navigateToTopic).toHaveBeenCalledWith('tpc_test');
+ expect(electronTabMocks.addTab).not.toHaveBeenCalled();
+ expect(electronTabMocks.addNewTab).not.toHaveBeenCalled();
+ expect(electronTabMocks.activateTab).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
index 5f21648ebc4..488a6d786a0 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -20,7 +20,7 @@ import {
import dayjs from 'dayjs';
import isEqual from 'fast-deep-equal';
import { MessageSquareDashed, TargetIcon } from 'lucide-react';
-import type { CSSProperties, DragEvent, MouseEvent, RefObject } from 'react';
+import type { CSSProperties, DragEvent, RefObject } from 'react';
import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -65,7 +65,6 @@ import {
PR_STATE_VISUAL,
} from './metaCardData';
import MetaHoverCard from './MetaHoverCard';
-import { openTopicInNewTab, recordTopicClickOrigin } from './openTopicTab';
// Base UI Popover plays an opacity/scale enter+exit transition driven by these
// CSS vars on the positioner. Zero them so the meta hover card appears instantly
@@ -337,34 +336,14 @@ const TopicItemRow = memo<TopicItemRowProps>(
[id, title],
);
- const handleClick = useCallback(
- (event?: MouseEvent) => {
- if (event && event.detail > 1) return;
- if (id) markSidebarTopicActivation(id);
- if (isDesktop && id) recordTopicClickOrigin(id);
- void navRef.current.navigateToTopic(id);
- },
- [id, navRef],
- );
-
- const handleDoubleClick = useCallback(async () => {
- if (!id || !activeAgentId || !isDesktop) return;
- markSidebarTopicActivation(id);
- if (scope && href) {
- openTopicInNewTab(id, href);
- void navRef.current.navigateToTopic(id);
- return;
- }
- if (await navRef.current.focusTopicPopup(id)) {
- void navRef.current.navigateToTopic(id, { skipPopupFocus: true });
- return;
- }
- openTopicInNewTab(
- id,
- buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug),
- );
+ // A plain click only switches the topic. Opening a new tab takes an explicit
+ // gesture (Cmd/Ctrl+click, middle click, or the context menu): a double
+ // click used to open one, and a lagging UI turned repeated clicks into
+ // unwanted tabs.
+ const handleClick = useCallback(() => {
+ if (id) markSidebarTopicActivation(id);
void navRef.current.navigateToTopic(id);
- }, [id, activeAgentId, activeWorkspaceSlug, navRef, scope, href]);
+ }, [id, navRef]);
const isFailed = status === 'failed';
const isRunning = status === 'running';
@@ -676,7 +655,6 @@ const TopicItemRow = memo<TopicItemRowProps>(
workingDirectoryNode ? { iconBelow: draftBelowIcon } : { titlePrefix: draftPrefix }
}
onClick={handleClick}
- onDoubleClick={() => void handleDoubleClick()}
onDragStart={handleDragStart}
/>
</TopicItemContextMenu>
diff --git a/src/features/AgentSidebar/Topic/List/Item/openTopicTab.test.ts b/src/features/AgentSidebar/Topic/List/Item/openTopicTab.test.ts
deleted file mode 100644
index 0291219424d..00000000000
--- a/src/features/AgentSidebar/Topic/List/Item/openTopicTab.test.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { createMemoryRouter } from 'react-router';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { flushHiddenTabRestores } from '@/features/Electron/TabHost/hiddenTabRestore';
-import {
- getOrCreateTabRouter,
- resetTabRouterManager,
-} from '@/features/Electron/TabHost/tabRouterManager';
-import { useElectronStore } from '@/store/electron';
-import { initialState } from '@/store/electron/initialState';
-
-import { openTopicInNewTab, recordTopicClickOrigin } from './openTopicTab';
-
-const makeRouter = (url: string) =>
- createMemoryRouter([{ element: null, path: '*' }], { initialEntries: [url] });
-
-const seedActiveTab = (url: string) => {
- useElectronStore.setState({
- ...initialState,
- activeTabId: 'origin',
- tabs: [{ id: 'origin', lastVisited: 1, url }],
- });
- return getOrCreateTabRouter('origin', url, makeRouter);
-};
-
-beforeEach(() => {
- window.localStorage.clear();
- resetTabRouterManager();
-});
-
-afterEach(() => {
- resetTabRouterManager();
- useElectronStore.setState(initialState);
-});
-
-describe('openTopicInNewTab', () => {
- it('opens the topic in a new tab and puts the clicked tab back where it was', async () => {
- const router = seedActiveTab('/agent/a/tpc_before');
-
- recordTopicClickOrigin('tpc_next');
- await router.navigate('/agent/a/tpc_next', { replace: true });
- useElectronStore.getState().reportTabLocation('origin', '/agent/a/tpc_next');
-
- openTopicInNewTab('tpc_next', '/agent/a/tpc_next');
-
- const { activeTabId, tabs } = useElectronStore.getState();
- expect(tabs).toHaveLength(2);
- expect(activeTabId).not.toBe('origin');
- expect(tabs.find((tab) => tab.id === activeTabId)!.url).toBe('/agent/a/tpc_next');
-
- flushHiddenTabRestores([activeTabId!]);
- await vi.waitFor(() => expect(router.state.location.pathname).toBe('/agent/a/tpc_before'));
- expect(useElectronStore.getState().tabs.find((tab) => tab.id === 'origin')!.url).toBe(
- '/agent/a/tpc_before',
- );
- });
-
- it('keeps the single tab when the topic was already open in it', () => {
- seedActiveTab('/agent/a/tpc_same');
-
- recordTopicClickOrigin('tpc_same');
- openTopicInNewTab('tpc_same', '/agent/a/tpc_same');
-
- const { activeTabId, tabs } = useElectronStore.getState();
- expect(tabs).toHaveLength(1);
- expect(activeTabId).toBe('origin');
- });
-
- it('activates another tab that already holds the topic instead of duplicating it', () => {
- seedActiveTab('/agent/a/tpc_before');
- useElectronStore.setState({
- tabs: [
- ...useElectronStore.getState().tabs,
- { id: 'existing', lastVisited: 0, url: '/agent/a/tpc_next' },
- ],
- });
-
- recordTopicClickOrigin('tpc_next');
- useElectronStore.getState().reportTabLocation('origin', '/agent/a/tpc_next');
- openTopicInNewTab('tpc_next', '/agent/a/tpc_next');
-
- const { activeTabId, tabs } = useElectronStore.getState();
- expect(tabs).toHaveLength(2);
- expect(activeTabId).toBe('existing');
- });
-});
diff --git a/src/features/AgentSidebar/Topic/List/Item/openTopicTab.ts b/src/features/AgentSidebar/Topic/List/Item/openTopicTab.ts
deleted file mode 100644
index 8bdd6cb0b96..00000000000
--- a/src/features/AgentSidebar/Topic/List/Item/openTopicTab.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { restoreTabWhenHidden } from '@/features/Electron/TabHost/hiddenTabRestore';
-import { getTabRouter } from '@/features/Electron/TabHost/tabRouterManager';
-import { normalizeTabUrl } from '@/features/Electron/titlebar/TabBar/url';
-import { useElectronStore } from '@/store/electron';
-
-interface ClickOrigin {
- tabId: string;
- topicId: string;
- url: string;
-}
-
-let lastClickOrigin: ClickOrigin | null = null;
-
-// A single click navigates the active tab at once, so by the time the double
-// click arrives that tab already shows the topic. Remember where it was so the
-// double click can open the topic in a new tab and put the clicked tab back.
-export const recordTopicClickOrigin = (topicId: string): void => {
- const { activeTabId } = useElectronStore.getState();
- const location = activeTabId ? getTabRouter(activeTabId)?.state.location : undefined;
-
- lastClickOrigin =
- activeTabId && location
- ? {
- tabId: activeTabId,
- topicId,
- url: `${location.pathname}${location.search}${location.hash}`,
- }
- : null;
-};
-
-export const openTopicInNewTab = (topicId: string, url: string): void => {
- const origin = lastClickOrigin?.topicId === topicId ? lastClickOrigin : null;
- lastClickOrigin = null;
-
- const electron = useElectronStore.getState();
- const target = normalizeTabUrl(url);
-
- if (!origin || normalizeTabUrl(origin.url) === target) {
- electron.addTab(url);
- return;
- }
-
- const existing = electron.tabs.find(
- (tab) => tab.id !== origin.tabId && normalizeTabUrl(tab.url) === target,
- );
- if (existing) electron.activateTab(existing.id);
- else electron.addNewTab(url);
-
- restoreTabWhenHidden(origin.tabId, { from: url, to: origin.url });
-};
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.tsx
index a920d8bd42b..66847828756 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
@@ -21,24 +21,21 @@ import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspa
import DotsLoading from '@/components/DotsLoading';
import { TOPIC_STATUS_VISUALS } from '@/components/ExecutionStatus';
import RingLoadingIcon from '@/components/RingLoading';
-import { isDesktop } from '@/const/version';
import { TopicMigrationIndicator } from '@/features/AgentTransferMigration';
import { useHasDraft } from '@/features/ChatInput/draftStorage';
import NavItem from '@/features/NavPanel/components/NavItem';
import TopicCreatorAvatar, { useTopicCreator } from '@/features/TopicCreatorAvatar';
-import { useFocusTopicPopup } from '@/features/TopicPopupGuard/useTopicPopupsRegistry';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useAgentGroupStore } from '@/store/agentGroup';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { useElectronStore } from '@/store/electron';
-import { useGlobalStore } from '@/store/global';
import ThreadList from '../../TopicListContent/ThreadList';
import Actions from './Actions';
import Editing from './Editing';
import { useTopicItemDropdownMenu } from './useDropdownMenu';
+import { useTopicClick } from './useTopicClick';
const styles = createStaticStyles(({ css }) => ({
neonDotWrapper: css`
@@ -76,18 +73,6 @@ 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 ).
-let pendingSingleClickTimer: ReturnType<typeof setTimeout> | null = null;
-
-const cancelPendingSingleClick = () => {
- if (pendingSingleClickTimer) {
- clearTimeout(pendingSingleClickTimer);
- pendingSingleClickTimer = null;
- }
-};
-
interface TopicItemProps {
active?: boolean;
fav?: boolean;
@@ -106,11 +91,8 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stat
const loadingRingColor = isDarkMode
? cssVar.colorWarningBorder
: `color-mix(in srgb, ${cssVar.colorWarning} 45%, transparent)`;
- const toggleMobileTopic = useGlobalStore((s) => s.toggleMobileTopic);
- const [activeGroupId, switchTopic] = useAgentGroupStore((s) => [s.activeGroupId, s.switchTopic]);
- const addTab = useElectronStore((s) => s.addTab);
+ const activeGroupId = useAgentGroupStore((s) => s.activeGroupId);
const activeWorkspaceSlug = useActiveWorkspaceSlug();
- const focusTopicPopup = useFocusTopicPopup({ groupId: activeGroupId });
// A workspace-private group is a purely personal conversation space even
// inside a workspace β€” its topics all belong to the viewer, so the creator
// avatar carries no information there. Only workspace-shared (`public`)
@@ -144,47 +126,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stat
[id],
);
- const handleClick = useCallback(() => {
- if (editing) return;
- if (isDesktop) {
- cancelPendingSingleClick();
- pendingSingleClickTimer = setTimeout(() => {
- pendingSingleClickTimer = null;
- void (async () => {
- await focusTopicPopup(id);
- switchTopic(id);
- toggleMobileTopic(false);
- })();
- }, 250);
- } else {
- void (async () => {
- await focusTopicPopup(id);
- switchTopic(id);
- toggleMobileTopic(false);
- })();
- }
- }, [editing, focusTopicPopup, id, switchTopic, toggleMobileTopic]);
-
- const handleDoubleClick = useCallback(async () => {
- if (!id || !activeGroupId || !isDesktop) return;
- cancelPendingSingleClick();
- if (await focusTopicPopup(id)) {
- switchTopic(id);
- toggleMobileTopic(false);
- return;
- }
- addTab(buildWorkspaceAwarePath(GROUP_CHAT_TOPIC_URL(activeGroupId, id), activeWorkspaceSlug));
- switchTopic(id);
- toggleMobileTopic(false);
- }, [
- id,
- activeGroupId,
- activeWorkspaceSlug,
- addTab,
- focusTopicPopup,
- switchTopic,
- toggleMobileTopic,
- ]);
+ const handleClick = useTopicClick({ editing, id });
const dropdownMenu = useTopicItemDropdownMenu({
id,
@@ -289,7 +231,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stat
</Tag>
</Flexbox>
}
- onClick={handleClick}
+ onClick={() => void handleClick()}
/>
);
}
@@ -356,8 +298,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId, stat
iconPostfix: unreadNode,
titlePrefix: draftPrefix,
}}
- onClick={handleClick}
- onDoubleClick={() => void handleDoubleClick()}
+ onClick={() => void handleClick()}
/>
<Editing id={id} title={title} toggleEditing={toggleEditing} />
{active && (
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useTopicClick.test.ts b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useTopicClick.test.ts
new file mode 100644
index 00000000000..56ca74e6620
--- /dev/null
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useTopicClick.test.ts
@@ -0,0 +1,71 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useTopicClick } from './useTopicClick';
+
+const switchTopicMock = vi.hoisted(() => vi.fn());
+const toggleMobileTopicMock = vi.hoisted(() => vi.fn());
+const focusTopicPopupMock = vi.hoisted(() => vi.fn(async (_topicId?: string) => false));
+
+vi.mock('@/store/agentGroup', () => ({
+ useAgentGroupStore: (selector: (state: unknown) => unknown) =>
+ selector({ activeGroupId: 'grp_test', switchTopic: switchTopicMock }),
+}));
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: unknown) => unknown) =>
+ selector({ toggleMobileTopic: toggleMobileTopicMock }),
+}));
+vi.mock('@/features/TopicPopupGuard/useTopicPopupsRegistry', () => ({
+ useFocusTopicPopup: () => focusTopicPopupMock,
+}));
+
+describe('useTopicClick', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ switchTopicMock.mockClear();
+ toggleMobileTopicMock.mockClear();
+ focusTopicPopupMock.mockClear();
+ });
+
+ // Desktop used to hold every click back 250ms to tell it apart from the
+ // double click that opened a new tab.
+ it('switches to the topic on the first click without waiting', async () => {
+ vi.useFakeTimers();
+ const { result } = renderHook(() => useTopicClick({ editing: false, id: 'tpc_test' }));
+
+ await act(async () => {
+ void result.current();
+ // Only microtasks run here: a delayed single click would still be waiting.
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ expect(focusTopicPopupMock).toHaveBeenCalledWith('tpc_test');
+ expect(switchTopicMock).toHaveBeenCalledWith('tpc_test');
+ expect(toggleMobileTopicMock).toHaveBeenCalledWith(false);
+ });
+
+ it('switches on every click of a rapid repeat', async () => {
+ const { result } = renderHook(() => useTopicClick({ editing: false, id: 'tpc_test' }));
+
+ await act(async () => {
+ await Promise.all([result.current(), result.current()]);
+ });
+
+ expect(switchTopicMock).toHaveBeenCalledTimes(2);
+ expect(switchTopicMock).toHaveBeenLastCalledWith('tpc_test');
+ });
+
+ it('ignores clicks while the topic is being renamed', async () => {
+ const { result } = renderHook(() => useTopicClick({ editing: true, id: 'tpc_test' }));
+
+ await act(async () => {
+ await result.current();
+ });
+
+ expect(focusTopicPopupMock).not.toHaveBeenCalled();
+ expect(switchTopicMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useTopicClick.ts b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useTopicClick.ts
new file mode 100644
index 00000000000..fb8ffbc737b
--- /dev/null
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useTopicClick.ts
@@ -0,0 +1,35 @@
+import { useCallback } from 'react';
+
+import { useFocusTopicPopup } from '@/features/TopicPopupGuard/useTopicPopupsRegistry';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { useGlobalStore } from '@/store/global';
+
+interface UseTopicClickParams {
+ /** Rename mode swallows clicks so the input keeps focus. */
+ editing: boolean;
+ /** Group topic to open; `undefined` is the group's default (temporary) topic. */
+ id?: string;
+}
+
+/**
+ * Click handler for a group sidebar topic row.
+ *
+ * Switches on the first click. Opening a new tab takes an explicit gesture
+ * (Cmd/Ctrl+click, middle click, or the context menu): a double click used to
+ * open one, which held every click back 250ms to tell the two apart and let a
+ * lagging UI turn repeated clicks into unwanted tabs.
+ */
+export const useTopicClick = ({ editing, id }: UseTopicClickParams) => {
+ const toggleMobileTopic = useGlobalStore((s) => s.toggleMobileTopic);
+ const [activeGroupId, switchTopic] = useAgentGroupStore((s) => [s.activeGroupId, s.switchTopic]);
+ const focusTopicPopup = useFocusTopicPopup({ groupId: activeGroupId });
+
+ return useCallback(async () => {
+ if (editing) return;
+ // A topic already open in a popup window gets focused there; the main
+ // window still switches so the sidebar highlight follows the click.
+ await focusTopicPopup(id);
+ switchTopic(id);
+ toggleMobileTopic(false);
+ }, [editing, focusTopicPopup, id, switchTopic, toggleMobileTopic]);
+};