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(popover): close popovers when their content navigates or opens a modal (#21555)

YuTengjingf10fe330d0cb
diff --git a/.agents/skills/react/SKILL.md b/.agents/skills/react/SKILL.md
index fc94cf16185..e1a84155328 100644
--- a/.agents/skills/react/SKILL.md
+++ b/.agents/skills/react/SKILL.md
@@ -72,6 +72,14 @@ Keep transient state in its smallest useful owner. Extract a custom hook when st
Split a component only to establish a real state, reuse, render-update, or mountable-capability boundary. Do not split solely to make files smaller; when a file reaches the 1200-line limit in **`source-layout`**, find one of these boundaries rather than cutting at a line count. Decomposing a heavy domain feature into host-assembled atoms is owned by **`compose-atoms`**.
+## Popover Exits
+
+An action inside popover content that leaves the popover must close it, or the popover stays over the destination (for example, a plan badge in the user panel navigating to `/settings/plans`).
+
+- Navigation: a host whose content links or navigates keeps `open` state, calls `useCloseOnNavigate(open, () => setOpen(false))` from `@/hooks/useCloseOnNavigate`, and passes the returned key to its `Popover`. This covers links added later, including links from other files. The key matters when navigation hides the host in an `<Activity>` (the home sidebar): a hidden tree sets up no new effects, so the base-ui popup never finishes its exit animation and stays on screen until a remount removes it.
+- Modal handoff or a final pick: call `usePopoverContext().close()` (or the host's setter) before opening the modal or after the pick, as `NavPanel/switcher/SwitcherMenu.tsx` does. Content rendered outside a popover cannot use the context, because its default `close` throws in development.
+- A confirm step whose result appears in the same popover, such as the share-link privacy confirm, keeps it open.
+
## Render Performance and Memoization
Treat `memo`, `useMemo`, and `useCallback` as opt-in optimizations, not default component wrappers. Before adding one, identify the actual rerender boundary and prefer structural fixes:
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsx
index e089c43154f..56bedfc0cfe 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaAccountSwitcher.tsx
@@ -1,7 +1,15 @@
'use client';
import type { QuotaAccountIdentity } from '@lobechat/heterogeneous-agents/quota';
-import { ActionIcon, Button, createStaticStyles, cssVar, Flexbox, Text } from '@lobehub/ui';
+import {
+ ActionIcon,
+ Button,
+ createStaticStyles,
+ cssVar,
+ Flexbox,
+ Text,
+ usePopoverContext,
+} from '@lobehub/ui';
import { CalendarDaysIcon } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -38,10 +46,15 @@ const QuotaAccountSwitcher = memo<{
const { t } = useTranslation('chat');
const agentId = useAgentId();
const identity = snapshot.identity;
+ // Only rendered inside the quota popover; hand off to each modal without
+ // leaving the popover open underneath it.
+ const { close } = usePopoverContext();
const openManager = useCallback(() => {
- if (agentId) openQuotaAccountManagerModal(agentId, { deviceId });
- }, [agentId, deviceId]);
+ if (!agentId) return;
+ close();
+ openQuotaAccountManagerModal(agentId, { deviceId });
+ }, [agentId, close, deviceId]);
if (!agentId) return null;
@@ -67,9 +80,10 @@ const QuotaAccountSwitcher = memo<{
size={'small'}
style={{ flex: 'none' }}
title={t('heteroAgent.claudeQuota.calendar.entry')}
- onClick={() =>
- openQuotaCalendarModal({ externalAccountId: identity?.externalAccountId, provider })
- }
+ onClick={() => {
+ close();
+ openQuotaCalendarModal({ externalAccountId: identity?.externalAccountId, provider });
+ }}
/>
</Flexbox>
{/*
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.claudeCode.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.claudeCode.test.tsx
index 665ed069995..54e9497a2c8 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.claudeCode.test.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.claudeCode.test.tsx
@@ -102,6 +102,8 @@ vi.mock('react-i18next', () => ({
}),
}));
+const closePopoverMock = vi.hoisted(() => vi.fn());
+
vi.mock('@lobehub/ui', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
const factories: ((original: typeof importOriginal) => unknown)[] = [
@@ -186,10 +188,13 @@ vi.mock('@lobehub/ui', async (importOriginal) => {
const part = (await factory(importOriginal)) as Record<string, unknown>;
for (const [key, value] of Object.entries(part)) if (value !== actual[key]) merged[key] = value;
}
+ // The mocked Popover has no provider; the header switcher closes it before opening modals.
+ merged.usePopoverContext = () => ({ close: closePopoverMock });
return merged;
});
beforeEach(() => {
+ closePopoverMock.mockReset();
isolateQuotaReplica();
confirmModalMock.mockReset();
mockService.consumeCodexRateLimitResetCredit.mockReset();
@@ -222,6 +227,7 @@ describe('ClaudeCodeQuotaMenu', () => {
fireEvent.click(await screen.findByTestId('calendar'));
+ expect(closePopoverMock).toHaveBeenCalledTimes(1);
expect(openQuotaCalendarModal).toHaveBeenCalledWith({
externalAccountId: 'ext-1',
provider: 'claude-code',
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
index e4269b47fe8..543e61224c3 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/QuotaMenu/QuotaMenu.test.tsx
@@ -96,6 +96,8 @@ vi.mock('react-i18next', () => ({
}),
}));
+const closePopoverMock = vi.hoisted(() => vi.fn());
+
vi.mock('@lobehub/ui', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
const factories: ((original: typeof importOriginal) => unknown)[] = [
@@ -180,10 +182,13 @@ vi.mock('@lobehub/ui', async (importOriginal) => {
const part = (await factory(importOriginal)) as Record<string, unknown>;
for (const [key, value] of Object.entries(part)) if (value !== actual[key]) merged[key] = value;
}
+ // The mocked Popover has no provider; the header switcher closes it before opening modals.
+ merged.usePopoverContext = () => ({ close: closePopoverMock });
return merged;
});
beforeEach(() => {
+ closePopoverMock.mockReset();
isolateQuotaReplica();
confirmModalMock.mockReset();
mockService.consumeCodexRateLimitResetCredit.mockReset();
@@ -369,6 +374,7 @@ describe('KimiCodeQuotaMenu', () => {
fireEvent.click(await screen.findByTestId('calendar'));
+ expect(closePopoverMock).toHaveBeenCalledTimes(1);
expect(openQuotaCalendarModal).toHaveBeenCalledWith({
externalAccountId: 'kimi-ext-1',
provider: 'kimi-code',
@@ -389,6 +395,7 @@ describe('CodexQuotaMenu', () => {
fireEvent.click(await screen.findByTestId('calendar'));
+ expect(closePopoverMock).toHaveBeenCalledTimes(1);
expect(openQuotaCalendarModal).toHaveBeenCalledWith({
externalAccountId: 'codex-ext-1',
provider: 'codex',
diff --git a/src/features/User/UserPanel/index.tsx b/src/features/User/UserPanel/index.tsx
index ee3aa14124f..aa7fdfee6c2 100644
--- a/src/features/User/UserPanel/index.tsx
+++ b/src/features/User/UserPanel/index.tsx
@@ -5,6 +5,7 @@ import { type PropsWithChildren } from 'react';
import { memo, Suspense, useState } from 'react';
import { isDesktop } from '@/const/version';
+import { useCloseOnNavigate } from '@/hooks/useCloseOnNavigate';
import PanelContent from './PanelContent';
import PanelContentSkeleton from './PanelContentSkeleton';
@@ -27,12 +28,15 @@ const styles = createStaticStyles(({ css }) => {
const UserPanel = memo<PropsWithChildren>(({ children }) => {
const hasNewVersion = useNewVersion();
const [open, setOpen] = useState(false);
+ // Panel entries, including business slots, may navigate without a close callback.
+ const popoverKey = useCloseOnNavigate(open, () => setOpen(false));
return (
<Suspense fallback={children}>
<UpgradeBadge showBadge={hasNewVersion}>
<Popover
arrow={false}
+ key={popoverKey}
open={open}
placement="topLeft"
trigger="click"
diff --git a/src/hooks/useCloseOnNavigate.test.ts b/src/hooks/useCloseOnNavigate.test.ts
new file mode 100644
index 00000000000..786c22ae925
--- /dev/null
+++ b/src/hooks/useCloseOnNavigate.test.ts
@@ -0,0 +1,79 @@
+import { act, renderHook } from '@testing-library/react';
+import { Activity, createElement, type ReactNode } from 'react';
+import { MemoryRouter, useNavigate } from 'react-router';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useCloseOnNavigate } from './useCloseOnNavigate';
+
+const wrapper = ({ children }: { children: ReactNode }) =>
+ createElement(MemoryRouter, { initialEntries: ['/'] }, children);
+
+const setup = (open: boolean) => {
+ const close = vi.fn();
+ const hook = renderHook(
+ ({ open }) => {
+ useCloseOnNavigate(open, close);
+ return useNavigate();
+ },
+ { initialProps: { open }, wrapper },
+ );
+ return { close, ...hook };
+};
+
+describe('useCloseOnNavigate', () => {
+ it('does not close on mount', () => {
+ const { close } = setup(true);
+
+ expect(close).not.toHaveBeenCalled();
+ });
+
+ it('closes an open host when navigation commits', () => {
+ const { close, result } = setup(true);
+
+ act(() => {
+ void result.current('/settings/plans');
+ });
+
+ expect(close).toHaveBeenCalledTimes(1);
+ });
+
+ it('closes on a same-path navigation', () => {
+ const { close, result } = setup(true);
+
+ act(() => {
+ void result.current('/');
+ });
+
+ expect(close).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves a closed host alone and does not close it on reopen', () => {
+ const { close, rerender, result } = setup(false);
+
+ act(() => {
+ void result.current('/settings/stats');
+ });
+ rerender({ open: true });
+
+ expect(close).not.toHaveBeenCalled();
+ });
+
+ it('closes and rekeys an open host when it is hidden instead of re-rendered', () => {
+ const close = vi.fn();
+ let mode: 'hidden' | 'visible' = 'visible';
+ const activityWrapper = ({ children }: { children: ReactNode }) =>
+ wrapper({ children: createElement(Activity, { mode }, children) });
+ const { rerender, result } = renderHook(() => useCloseOnNavigate(true, close), {
+ wrapper: activityWrapper,
+ });
+ expect(result.current).toBe(0);
+
+ mode = 'hidden';
+ rerender();
+ mode = 'visible';
+ rerender();
+
+ expect(close).toHaveBeenCalledTimes(1);
+ expect(result.current).toBe(1);
+ });
+});
diff --git a/src/hooks/useCloseOnNavigate.ts b/src/hooks/useCloseOnNavigate.ts
new file mode 100644
index 00000000000..05a755fc194
--- /dev/null
+++ b/src/hooks/useCloseOnNavigate.ts
@@ -0,0 +1,54 @@
+import { useLayoutEffect, useRef, useState } from 'react';
+
+import { useActiveLocation } from './useActiveLocation';
+
+/**
+ * Closes a floating host (popover, panel) once the active location changes, so
+ * any link or `navigate()` call inside its content leaves the host behind
+ * without wiring a close callback through every entry.
+ *
+ * The identity combines `key` with the path: web navigations always mint a new
+ * `key` (also for same-path pushes), while the desktop tab mirror keeps a fixed
+ * key and only changes its URL.
+ *
+ * Only for hosts whose every navigation should dismiss them; a click that does
+ * not commit a navigation (for example re-selecting the current item) still
+ * needs an explicit close.
+ *
+ * Returns a key for the host's popover element. A navigation can hide the host
+ * instead of re-rendering it (the home sidebar stays in a hidden `<Activity>`
+ * on other routes); a hidden tree runs no effects, so a closing popover never
+ * finishes its exit and its portaled popup stays on screen. On hide the key
+ * changes, remounting the popover so React drops the popup directly.
+ */
+export const useCloseOnNavigate = (open: boolean, close: () => void): number => {
+ const { key, pathname, search } = useActiveLocation();
+ const identity = `${key}|${pathname}${search}`;
+ const lastIdentity = useRef(identity);
+ const latestOpen = useRef(open);
+ const [hostKey, setHostKey] = useState(0);
+
+ useLayoutEffect(() => {
+ latestOpen.current = open;
+ });
+
+ // Layout effect so the destination's first paint is not covered by the host.
+ useLayoutEffect(() => {
+ if (lastIdentity.current === identity) return;
+ lastIdentity.current = identity;
+ if (open) close();
+ // Keyed on the location only: a new `close` identity must not trigger it.
+ }, [identity]);
+
+ // Layout cleanups run when the host is hidden (and on unmount).
+ useLayoutEffect(
+ () => () => {
+ if (!latestOpen.current) return;
+ close();
+ setHostKey((key) => key + 1);
+ },
+ [],
+ );
+
+ return hostKey;
+};
diff --git a/src/routes/(main)/agent/features/Conversation/Header/Tags/ThreadSwitcher.tsx b/src/routes/(main)/agent/features/Conversation/Header/Tags/ThreadSwitcher.tsx
index 59ab6f43d6d..dbdc32887ac 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/Tags/ThreadSwitcher.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/Tags/ThreadSwitcher.tsx
@@ -1,7 +1,7 @@
'use client';
import { createStaticStyles, cx, Flexbox, Popover } from '@lobehub/ui';
-import { memo } from 'react';
+import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useChatStore } from '@/store/chat';
@@ -91,7 +91,11 @@ const ThreadSwitcher = memo<ThreadSwitcherProps>(({ title }) => {
const threads = useChatStore(threadSelectors.currentTopicThreads);
const switchThread = useChatStore((s) => s.switchThread);
+ const [open, setOpen] = useState(false);
+
const handleSwitch = (id: string) => {
+ // A pick, including the current thread, completes the switcher.
+ setOpen(false);
if (id === activeThreadId) return;
void switchThread(id);
};
@@ -125,9 +129,11 @@ const ThreadSwitcher = memo<ThreadSwitcherProps>(({ title }) => {
classNames={{ trigger: styles.trigger }}
content={content}
nativeButton={false}
+ open={open}
placement={'bottomLeft'}
styles={{ content: { padding: 4 } }}
trigger={'click'}
+ onOpenChange={setOpen}
>
{title}
</Popover>
diff --git a/src/routes/(main)/group/_layout/Sidebar/Header/Agent/SwitchPanel.tsx b/src/routes/(main)/group/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
index 03e243a4ddc..cb08334b1e8 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
@@ -1,16 +1,23 @@
import { Flexbox, Popover } from '@lobehub/ui';
import { type PropsWithChildren } from 'react';
-import React, { memo, Suspense } from 'react';
+import React, { memo, Suspense, useState } from 'react';
import List from '@/features/HomeSidebar/Body/Agent/List';
import { AgentModalProvider } from '@/features/HomeSidebar/Body/Agent/ModalProvider';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useCloseOnNavigate } from '@/hooks/useCloseOnNavigate';
const SwitchPanel = memo<PropsWithChildren>(({ children }) => {
const navigate = useWorkspaceAwareNavigate();
+ const [open, setOpen] = useState(false);
+ // Agent rows are links; leaving for another agent should dismiss the switcher.
+ const popoverKey = useCloseOnNavigate(open, () => setOpen(false));
+
return (
<Popover
+ key={popoverKey}
+ open={open}
placement="bottomLeft"
trigger="click"
content={
@@ -35,6 +42,7 @@ const SwitchPanel = memo<PropsWithChildren>(({ children }) => {
width: 240,
},
}}
+ onOpenChange={setOpen}
>
{children}
</Popover>