🤯 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(agent-profile): close the sidebar profile card when its trigger goes away, and add a close button (#23424)
Rdmclin269149cf9199c
diff --git a/src/features/AgentProfileCard/AgentProfilePopup.tsx b/src/features/AgentProfileCard/AgentProfilePopup.tsxindex 5e13e942a64..24056f0750f 100644--- a/src/features/AgentProfileCard/AgentProfilePopup.tsx+++ b/src/features/AgentProfileCard/AgentProfilePopup.tsx@@ -11,7 +11,7 @@ import {Text,} from '@lobehub/ui';import { SkillsIcon } from '@lobehub/ui/icons';-import { BookOpen, FileText, Settings, SquareTerminal, UserRound } from 'lucide-react';+import { BookOpen, FileText, Settings, SquareTerminal, UserRound, X } from 'lucide-react';import { memo, type PropsWithChildren, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -35,8 +35,42 @@ import {type AgentProfilePreview as AgentPreview,useAgentProfileDetail,} from './useAgentProfileDetail';+import { useAutoClosePopup } from './useAutoClosePopup';const styles = createStaticStyles(({ css, cssVar }) => ({+ closeButton: css`+ position: absolute;+ z-index: 1;+ inset-block-start: 8px;+ inset-inline-end: 8px;++ color: ${cssVar.colorText};+ opacity: 0;+ filter: drop-shadow(0 0 2px ${cssVar.colorBgElevated});++ transition: opacity ${cssVar.motionDurationMid} ${cssVar.motionEaseOut};++ @media (hover: none) {+ opacity: 1;+ }+ `,+ content: css`+ position: relative;++ &:hover [data-profile-card-close],+ &:focus-within [data-profile-card-close] {+ opacity: 1;+ }+ `,+ // A replaced card (another card opened, its trigger was pressed, the route changed)+ // leaves at once instead of fading out over whatever replaced it.+ instantClose: css`+ &[data-ending-style],+ &[data-closed] {+ visibility: hidden;+ transition: none;+ }+ `,footer: css`padding-block: 12px;padding-inline: 16px;@@ -80,6 +114,11 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(const { t } = useTranslation('chat');const navigate = useWorkspaceAwareNavigate();const [open, setOpen] = useState(false);+ const { detached, instant, onOpenChange, triggerProps } = useAutoClosePopup({+ open,+ setOpen,+ trigger,+ });const [loading, setLoading] = useState(false);const { allowed: canEditContent } = usePermission('edit_own_content');const { canEditResource: canEditAgent, isAccessResolved: isAgentAccessResolved } =@@ -266,20 +305,34 @@ const AgentProfilePopup = memo<AgentProfilePopupProps>(return (<Popover+ className={instant ? styles.instantClose : undefined}classNames={trigger === 'click' ? { trigger: styles.trigger } : undefined}nativeButton={false}open={open}placement={placement ?? (trigger === 'hover' ? 'top' : 'right')}trigger={trigger}+ triggerProps={triggerProps}content={- <div role="presentation" onClick={stopCardClick}>- {content}- </div>+ // A hidden or unmounted trigger takes the whole popover with it (see useAutoClosePopup).+ detached ? null : (+ <div className={styles.content} role="presentation" onClick={stopCardClick}>+ {content}+ <ActionIcon+ data-profile-card-close+ aria-label={t('close', { ns: 'common' })}+ className={styles.closeButton}+ icon={X}+ size={'small'}+ title={t('close', { ns: 'common' })}+ onClick={() => setOpen(false)}+ />+ </div>+ )}styles={{content: { borderRadius: 12, overflow: 'hidden', padding: 0 },}}- onOpenChange={setOpen}+ onOpenChange={onOpenChange}>{children}</Popover>diff --git a/src/features/AgentProfileCard/useAutoClosePopup.test.ts b/src/features/AgentProfileCard/useAutoClosePopup.test.tsnew file mode 100644index 00000000000..5f4040f84d7--- /dev/null+++ b/src/features/AgentProfileCard/useAutoClosePopup.test.ts@@ -0,0 +1,207 @@+/**+ * @vitest-environment happy-dom+ */+import { act, render, renderHook, waitFor } from '@testing-library/react';+import { Activity, createElement, type PointerEvent, type ReactNode } from 'react';+import { createMemoryRouter, RouterProvider } from 'react-router';+import { describe, expect, it, vi } from 'vitest';++import { useAutoClosePopup } from './useAutoClosePopup';++const setup = ({ open = true }: { open?: boolean } = {}) => {+ const setOpen = vi.fn();+ let router: ReturnType<typeof createMemoryRouter> | undefined;++ const wrapper = ({ children }: { children: ReactNode }) => {+ router ??= createMemoryRouter(+ [+ { element: children, path: '/' },+ { element: children, path: '/agent/:id' },+ ],+ { initialEntries: ['/'] },+ );+ return createElement(RouterProvider, { router });+ };++ const hook = renderHook(() => useAutoClosePopup({ open, setOpen }), { wrapper });++ return {+ ...hook,+ navigate: (to: string) => router!.navigate(to),+ setOpen,+ // A second card in the same app shares the router.+ wrapperForTest: ({ children }: { children: ReactNode }) =>+ createElement(RouterProvider, {+ router: createMemoryRouter([{ element: children, path: '*' }]),+ }),+ };+};++// renderHook publishes `result` from an effect, which a hidden <Activity> never+// runs, so the Activity case renders the flag and reads it from the DOM.+const setupProbe = () => {+ const setOpen = vi.fn();+ const Probe = () => {+ const { detached } = useAutoClosePopup({ open: true, setOpen });+ return createElement('span', { 'data-detached': String(detached) });+ };+ const router = createMemoryRouter([{ element: createElement(Probe), path: '/' }]);+ const tree = (hidden: boolean) =>+ createElement(+ Activity,+ { mode: hidden ? 'hidden' : 'visible' },+ createElement(RouterProvider, { router }),+ );+ const utils = render(tree(false));+ return {+ ...utils,+ hide: () => utils.rerender(tree(true)),+ setOpen,+ show: () => utils.rerender(tree(false)),+ };+};++const attachTrigger = (+ triggerProps: ReturnType<typeof useAutoClosePopup>['triggerProps'],+ parent: Element,+) => {+ const trigger = document.createElement('span');+ parent.append(trigger);+ triggerProps.onPointerEnter({ currentTarget: trigger } as unknown as PointerEvent<Element>);+ return trigger;+};++describe('useAutoClosePopup', () => {+ it('closes and detaches the card while an <Activity> hides the trigger', async () => {+ // Entering an Agent keeps the Home sidebar mounted in a hidden <Activity>.+ const { container, hide, setOpen, show } = setupProbe();+ const detached = () =>+ container.querySelector('[data-detached]')?.getAttribute('data-detached');+ expect(detached()).toBe('false');++ hide();++ await waitFor(() => expect(setOpen).toHaveBeenCalledWith(false));+ await waitFor(() => expect(detached()).toBe('true'));++ // Back on Home the card can open again.+ show();+ await waitFor(() => expect(detached()).toBe('false'));+ });++ it('closes the card when the route changes', async () => {+ const { navigate, setOpen } = setup();+ expect(setOpen).not.toHaveBeenCalled();++ await act(() => navigate('/agent/agt_coder'));++ expect(setOpen).toHaveBeenCalledWith(false);+ });++ it('closes the card when only the query or hash changes', async () => {+ const { navigate, setOpen } = setup();++ await act(() => navigate('/?tab=agt_writer'));+ expect(setOpen).toHaveBeenCalledTimes(1);++ await act(() => navigate('/?tab=agt_writer#skills'));+ expect(setOpen).toHaveBeenCalledTimes(2);+ });++ it('closes the card when a container of the trigger scrolls, not when anything else does', () => {+ const { result, setOpen } = setup();+ const list = document.createElement('div');+ const card = document.createElement('div');+ document.body.append(list, card);+ attachTrigger(result.current.triggerProps, list);++ card.dispatchEvent(new Event('scroll'));+ expect(setOpen).not.toHaveBeenCalled();++ list.dispatchEvent(new Event('scroll'));+ expect(setOpen).toHaveBeenCalledWith(false);+ });++ it('closes the card on Escape even when a focused editor stops the key', () => {+ const { setOpen } = setup();+ const editor = document.createElement('div');+ editor.addEventListener('keydown', (event) => event.stopPropagation());+ document.body.append(editor);++ editor.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' }));++ expect(setOpen).toHaveBeenCalledWith(false);+ });++ it('closes the open card instantly when another card opens', () => {+ const first = setup();+ const secondSetOpen = vi.fn();+ const second = renderHook(({ open }) => useAutoClosePopup({ open, setOpen: secondSetOpen }), {+ initialProps: { open: false },+ wrapper: first.wrapperForTest,+ });++ second.rerender({ open: true });++ expect(first.setOpen).toHaveBeenCalledWith(false);+ expect(first.result.current.instant).toBe(true);+ expect(secondSetOpen).not.toHaveBeenCalled();+ });++ it('closes on trigger press and keeps hover from reopening until the pointer leaves', () => {+ const { result, setOpen } = setup();++ act(() => result.current.triggerProps.onPointerDown());+ expect(setOpen).toHaveBeenLastCalledWith(false);+ expect(result.current.instant).toBe(true);++ setOpen.mockClear();+ act(() => result.current.onOpenChange(true));+ expect(setOpen).not.toHaveBeenCalled();++ act(() => result.current.triggerProps.onPointerLeave());+ act(() => result.current.onOpenChange(true));+ expect(setOpen).toHaveBeenCalledWith(true);+ // A normal open restores the regular exit transition.+ expect(result.current.instant).toBe(false);+ });++ it('leaves a click card alone on press, since that press opens it', () => {+ const setOpen = vi.fn();+ const { result } = renderHook(+ () => useAutoClosePopup({ open: false, setOpen, trigger: 'click' }),+ {+ wrapper: ({ children }: { children: ReactNode }) =>+ createElement(RouterProvider, {+ router: createMemoryRouter([{ element: children, path: '*' }]),+ }),+ },+ );++ act(() => result.current.triggerProps.onPointerDown());+ act(() => result.current.onOpenChange(true));++ expect(setOpen).toHaveBeenCalledTimes(1);+ expect(setOpen).toHaveBeenCalledWith(true);+ });++ it('closes instantly on navigation', async () => {+ const { navigate, result } = setup();++ await act(() => navigate('/agent/agt_coder'));++ expect(result.current.instant).toBe(true);+ });++ it('listens for nothing while the card is closed', () => {+ const { result, setOpen } = setup({ open: false });+ const list = document.createElement('div');+ document.body.append(list);+ attachTrigger(result.current.triggerProps, list);++ list.dispatchEvent(new Event('scroll'));+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));++ expect(setOpen).not.toHaveBeenCalled();+ });+});diff --git a/src/features/AgentProfileCard/useAutoClosePopup.ts b/src/features/AgentProfileCard/useAutoClosePopup.tsnew file mode 100644index 00000000000..76911c4d2ff--- /dev/null+++ b/src/features/AgentProfileCard/useAutoClosePopup.ts@@ -0,0 +1,154 @@+import {+ type FocusEvent,+ type PointerEvent,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import { useLocation } from 'react-router';++interface UseAutoClosePopupOptions {+ open: boolean;+ setOpen: (open: boolean) => void;+ /** Only a hover card closes on press: a click card opens on that very press. */+ trigger?: 'click' | 'hover';+}++/**+ * Closes a profile hover card whenever its trigger stops being where the card+ * points to. Base UI only closes a hover card on pointer leave, outside press+ * or Escape, and all three need the trigger's listeners to be alive:+ *+ * - Entering an Agent swaps the Home sidebar out and keeps it in a hidden+ * `<Activity>`. Activity tears down effects but keeps state, and the card's+ * portal lives outside the hidden layer. Base UI's listeners and its own+ * close transition both run in effects, so even `open={false}` would leave+ * the card on screen. `detached` tells the caller to drop the popover+ * entirely until the trigger is shown again.+ * - A navigation, including one that only changes the query or hash (group+ * profile tabs, history traversal), can move or replace the trigger without+ * the pointer ever leaving it.+ * - Scrolling a list moves the trigger away from a pointer that stands still.+ * - Escape: a hover-opened card never takes focus, and an editor that holds it+ * (the chat composer) stops the key before Base UI's dismiss sees it, so it+ * is caught in the capture phase and still reaches the editor.+ * - Only one card is open at a time: opening one closes the previous one, and+ * pressing a trigger (to enter that Agent) closes its card and keeps it shut+ * until the pointer leaves, so the card never lingers over the next page.+ *+ * Closes that replace the card (another card, a press, a navigation) set+ * `instant`, which the caller turns into a popup without its exit transition,+ * so the old card is gone in the same frame instead of fading out.+ */++interface ActiveCard {+ close: () => void;+}++// The card that is open right now, across every AgentProfilePopup.+let activeCard: ActiveCard | null = null;++export const useAutoClosePopup = ({+ open,+ setOpen,+ trigger = 'hover',+}: UseAutoClosePopupOptions) => {+ // Every navigation gets a new key, query- and hash-only ones included.+ const { key: locationKey } = useLocation();+ const setOpenRef = useRef(setOpen);+ setOpenRef.current = setOpen;+ const triggerRef = useRef<Element | null>(null);+ const [detached, setDetached] = useState(false);+ const [instant, setInstant] = useState(false);+ // Set by pressing the trigger; blocks hover from reopening the card until the pointer leaves.+ const pressedRef = useRef(false);++ const closeInstantly = useCallback(() => {+ setInstant(true);+ setOpenRef.current(false);+ }, []);++ // Base UI asks to open or close through here.+ const onOpenChange = useCallback((next: boolean) => {+ if (next && pressedRef.current) return;+ if (next) setInstant(false);+ setOpenRef.current(next);+ }, []);++ // Layout effects are cleaned up both when an <Activity> hides the trigger+ // and when it unmounts, and set up again when it is shown.+ useLayoutEffect(() => {+ setDetached(false);+ return () => {+ setOpenRef.current(false);+ setDetached(true);+ };+ }, []);++ const lastLocationKeyRef = useRef(locationKey);+ useEffect(() => {+ if (lastLocationKeyRef.current === locationKey) return;+ lastLocationKeyRef.current = locationKey;+ closeInstantly();+ }, [locationKey, closeInstantly]);++ useEffect(() => {+ if (!open) return;+ const self: ActiveCard = { close: closeInstantly };+ if (activeCard) activeCard.close();+ activeCard = self;+ return () => {+ if (activeCard === self) activeCard = null;+ };+ }, [open, closeInstantly]);++ useEffect(() => {+ if (!open) return;++ const handleScroll = (event: Event) => {+ const trigger = triggerRef.current;+ const target = event.target;+ if (!trigger || !(target instanceof Node)) return;+ // Scrolling inside the card itself must not close it.+ if (target.contains(trigger)) setOpenRef.current(false);+ };++ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key === 'Escape') setOpenRef.current(false);+ };++ document.addEventListener('scroll', handleScroll, { capture: true, passive: true });+ document.addEventListener('keydown', handleKeyDown, { capture: true });+ return () => {+ document.removeEventListener('scroll', handleScroll, { capture: true });+ document.removeEventListener('keydown', handleKeyDown, { capture: true });+ };+ }, [open]);++ // Passing `ref` to Popover replaces the trigger's own ref handling, so the+ // trigger element is captured from the events that can open the card.+ const triggerProps = useMemo(+ () => ({+ onFocus: (event: FocusEvent<Element>) => {+ triggerRef.current = event.currentTarget;+ },+ onPointerDown: () => {+ if (trigger !== 'hover') return;+ pressedRef.current = true;+ closeInstantly();+ },+ onPointerEnter: (event: PointerEvent<Element>) => {+ triggerRef.current = event.currentTarget;+ },+ onPointerLeave: () => {+ pressedRef.current = false;+ },+ }),+ [closeInstantly, trigger],+ );++ return { detached, instant, onOpenChange, triggerProps };+};