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.

⚑️ perf: cut agent-route render work β€” popup-scoped menus and memo-stable topic rows (#17604)

Inneif410ccd4c1d2
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index e7d8c121b3e..2570e38b839 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -124,6 +124,37 @@ Client and server agent runtimes can produce the same visible result. Prove the
runtime with a server-only artifact: operation row, queue step, or enabled
main/server log namespace. Renderer state alone is not sufficient.
+### A new module needs a renderer reload, not HMR, before probing the fix
+
+**Situation:** verifying a source fix in the running Electron dev instance
+(`electron-dev.sh`) right after editing.
+
+**Doesn't work:** editing a component and probing a few seconds later. When the
+edit adds a **new module** (extracting a hook into its own file), the desktop
+Vite renderer can keep serving the previous module graph, so the probe reports
+the old behavior. Read as "the fix does not work" β€” a false negative that looks
+exactly like a logic bug in the change under test.
+
+**Works:** force a full renderer navigation (`app-probe.sh goto <route>`) after
+adding or moving a module, then re-probe. Confirm the new code is live by a
+structural signal (a renamed component in the fiber chain, a new class in the
+computed cascade) before concluding anything about behavior.
+
+### Reading a transitioned CSS property immediately after focus/hover
+
+**Situation:** asserting that a `:focus-within` / `:hover` rule reveals a
+control.
+
+**Doesn't work:** `getComputedStyle(el).opacity` read in the same tick as the
+focus call, or in a separate `agent-browser eval` that races the re-render which
+mounts the control. Both return the pre-transition `0` while the rule is in fact
+matching.
+
+**Works:** focus and read inside one `eval`, wait past the transition duration,
+and assert the untransitioned property too (`width`) plus
+`el.matches('<selector>:focus-within')` so a mid-transition value cannot be
+mistaken for a non-matching rule.
+
### Locale regression tests and desktop resource scanning
**Situation:** a locale-copy change needs a focused regression assertion while
diff --git a/src/components/ImperativeMount/index.tsx b/src/components/ImperativeMount/index.tsx
new file mode 100644
index 00000000000..0a49b904db8
--- /dev/null
+++ b/src/components/ImperativeMount/index.tsx
@@ -0,0 +1,94 @@
+'use client';
+
+import { Fragment, memo, type ReactNode, useSyncExternalStore } from 'react';
+
+/**
+ * Imperative mounting for surfaces base-ui's modal stack doesn't cover.
+ *
+ * `createModal` only renders a Modal shell, so anything shaped differently β€” a
+ * Drawer, a sheet β€” had no imperative entry and callers fell back to owning an
+ * `open` state. That breaks down whenever the trigger lives somewhere that
+ * unmounts (a dropdown popup closes and takes the drawer's state with it).
+ *
+ * Here the caller supplies the whole surface and only receives its open/close
+ * lifecycle, so an existing self-contained component can be driven as-is.
+ */
+interface MountContext {
+ close: () => void;
+ open: boolean;
+}
+
+interface MountEntry {
+ close: () => void;
+ id: number;
+ open: boolean;
+ render: (ctx: MountContext) => ReactNode;
+}
+
+/** Grace period so the surface can play its exit transition before unmounting. */
+const EXIT_GRACE_MS = 500;
+
+let seed = 0;
+let stack: MountEntry[] = [];
+
+const listeners = new Set<() => void>();
+const EMPTY: MountEntry[] = [];
+
+const notify = () => listeners.forEach((listener) => listener());
+
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+
+ return () => {
+ listeners.delete(listener);
+ };
+};
+
+const getSnapshot = () => stack;
+const getServerSnapshot = () => EMPTY;
+
+const destroy = (id: number) => {
+ const next = stack.filter((entry) => entry.id !== id);
+ if (next.length === stack.length) return;
+
+ stack = next;
+ notify();
+};
+
+export const mountImperative = (render: (ctx: MountContext) => ReactNode) => {
+ const id = seed++;
+
+ const close = () => {
+ let found = false;
+ stack = stack.map((entry) => {
+ if (entry.id !== id || !entry.open) return entry;
+ found = true;
+ return { ...entry, open: false };
+ });
+ if (!found) return;
+
+ notify();
+ setTimeout(() => destroy(id), EXIT_GRACE_MS);
+ };
+
+ stack = [...stack, { close, id, open: true, render }];
+ notify();
+
+ return { close };
+};
+
+const ImperativeMountHost = memo(() => {
+ const entries = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
+
+ return (
+ <>
+ {entries.map((entry) => (
+ <Fragment key={entry.id}>{entry.render({ close: entry.close, open: entry.open })}</Fragment>
+ ))}
+ </>
+ );
+});
+
+ImperativeMountHost.displayName = 'ImperativeMountHost';
+
+export default ImperativeMountHost;
diff --git a/src/components/RenameModal/index.tsx b/src/components/RenameModal/index.tsx
index 22043c406d9..9806f4ae66e 100644
--- a/src/components/RenameModal/index.tsx
+++ b/src/components/RenameModal/index.tsx
@@ -51,6 +51,7 @@ const RenameModalContent = memo<RenameModalContentProps>(
</Text>
) : null}
<Input
+ autoFocus
ref={inputRef}
value={value}
onChange={(e) => setValue(e.target.value)}
diff --git a/src/features/AgentBreadcrumb/index.tsx b/src/features/AgentBreadcrumb/index.tsx
index f2f53339a3f..5f506e27fb4 100644
--- a/src/features/AgentBreadcrumb/index.tsx
+++ b/src/features/AgentBreadcrumb/index.tsx
@@ -10,11 +10,11 @@ import { Link, useLocation } from 'react-router';
import urlJoin from 'url-join';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
-import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import {
buildPrefixedAgentRoutePath,
parseAgentPathname,
-} from '@/routes/(main)/agent/_layout/Sidebar/utils/agentPathname';
+} from '@/features/AgentSidebar/utils/agentPathname';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Body.tsx b/src/features/AgentSidebar/Body.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Body.tsx
rename to src/features/AgentSidebar/Body.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Content.tsx b/src/features/AgentSidebar/Content.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Content.tsx
rename to src/features/AgentSidebar/Content.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Agent/SwitchPanel.tsx b/src/features/AgentSidebar/Header/Agent/SwitchPanel.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Header/Agent/SwitchPanel.tsx
rename to src/features/AgentSidebar/Header/Agent/SwitchPanel.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Agent/index.tsx b/src/features/AgentSidebar/Header/Agent/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Header/Agent/index.tsx
rename to src/features/AgentSidebar/Header/Agent/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx b/src/features/AgentSidebar/Header/Nav.test.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Header/Nav.test.tsx
rename to src/features/AgentSidebar/Header/Nav.test.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx b/src/features/AgentSidebar/Header/Nav.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Header/Nav.tsx
rename to src/features/AgentSidebar/Header/Nav.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Header/index.tsx b/src/features/AgentSidebar/Header/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Header/index.tsx
rename to src/features/AgentSidebar/Header/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Task/StatusGroup.tsx b/src/features/AgentSidebar/Task/StatusGroup.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Task/StatusGroup.tsx
rename to src/features/AgentSidebar/Task/StatusGroup.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Task/TaskItem.test.tsx b/src/features/AgentSidebar/Task/TaskItem.test.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Task/TaskItem.test.tsx
rename to src/features/AgentSidebar/Task/TaskItem.test.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Task/TaskItem.tsx b/src/features/AgentSidebar/Task/TaskItem.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Task/TaskItem.tsx
rename to src/features/AgentSidebar/Task/TaskItem.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Task/index.tsx b/src/features/AgentSidebar/Task/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Task/index.tsx
rename to src/features/AgentSidebar/Task/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/Actions.tsx b/src/features/AgentSidebar/Topic/Actions.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/Actions.tsx
rename to src/features/AgentSidebar/Topic/Actions.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx b/src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/Content.tsx
rename to src/features/AgentSidebar/Topic/AllTopicsDrawer/Content.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx b/src/features/AgentSidebar/Topic/AllTopicsDrawer/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/AllTopicsDrawer/index.tsx
rename to src/features/AgentSidebar/Topic/AllTopicsDrawer/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/Filter.tsx b/src/features/AgentSidebar/Topic/Filter.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/Filter.tsx
rename to src/features/AgentSidebar/Topic/Filter.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Actions.tsx b/src/features/AgentSidebar/Topic/List/Item/Actions.tsx
similarity index 65%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Actions.tsx
rename to src/features/AgentSidebar/Topic/List/Item/Actions.tsx
index be1dce25cf0..521c1c293ff 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Actions.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/Actions.tsx
@@ -1,15 +1,13 @@
-import type { DropdownItem } from '@lobehub/ui';
import { ActionIcon, DropdownMenu } from '@lobehub/ui';
import { MoreHorizontalIcon } from 'lucide-react';
import { memo } from 'react';
import { useOverlayDropdownPortalProps } from '@/features/NavPanel/OverlayContainer';
-interface ActionProps {
- dropdownMenu: DropdownItem[] | (() => DropdownItem[]);
-}
+import { type TopicItemDropdownMenuProps, useTopicItemDropdownMenu } from './useDropdownMenu';
-const Actions = memo<ActionProps>(({ dropdownMenu }) => {
+const Actions = memo<TopicItemDropdownMenuProps>(({ fav, id, status, title }) => {
+ const { dropdownMenu } = useTopicItemDropdownMenu({ fav, id, status, title });
const dropdownPortalProps = useOverlayDropdownPortalProps();
return (
diff --git a/src/features/AgentSidebar/Topic/List/Item/ContextMenu.tsx b/src/features/AgentSidebar/Topic/List/Item/ContextMenu.tsx
new file mode 100644
index 00000000000..cd50be72b66
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/List/Item/ContextMenu.tsx
@@ -0,0 +1,34 @@
+import { ContextMenuTrigger } from '@lobehub/ui/base-ui';
+import { memo, type PropsWithChildren, useCallback, useEffect, useRef } from 'react';
+
+import { type TopicItemDropdownMenuProps, useTopicItemDropdownMenu } from './useDropdownMenu';
+
+/**
+ * Hosts the row's menu hook outside the row's memo boundary.
+ *
+ * `useTopicItemDropdownMenu` reaches `useNavigate`, which subscribes to
+ * react-router's contexts β€” so wherever it is called re-renders on every
+ * navigation. Calling it here keeps that re-render to this shell: `children`
+ * arrives as an already-built element, so React bails out on the row subtree.
+ *
+ * The items thunk is pinned to a stable identity for the same reason β€” a fresh
+ * one would flow into `cloneElement` below and break the row's memo anyway.
+ */
+const TopicItemContextMenu = memo<PropsWithChildren<TopicItemDropdownMenuProps>>(
+ ({ children, fav, id, status, title }) => {
+ const { dropdownMenu } = useTopicItemDropdownMenu({ fav, id, status, title });
+
+ const menuRef = useRef(dropdownMenu);
+ useEffect(() => {
+ menuRef.current = dropdownMenu;
+ }, [dropdownMenu]);
+
+ const items = useCallback(() => menuRef.current(), []);
+
+ return <ContextMenuTrigger items={items}>{children}</ContextMenuTrigger>;
+ },
+);
+
+TopicItemContextMenu.displayName = 'TopicItemContextMenu';
+
+export default TopicItemContextMenu;
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/MetaHoverCard.test.tsx b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/MetaHoverCard.test.tsx
rename to src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/MetaHoverCard.tsx b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/MetaHoverCard.tsx
rename to src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
similarity index 97%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
rename to src/features/AgentSidebar/Topic/List/Item/index.test.tsx
index 1aa3a03478d..3cf2a081eb2 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
@@ -17,6 +17,7 @@ const topicMetaCardMock = vi.hoisted(() => ({
}));
vi.mock('@lobehub/ui', () => ({
+ ContextMenuTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<div {...props}>{children}</div>
),
@@ -35,6 +36,9 @@ vi.mock('@lobehub/ui', () => ({
}));
vi.mock('antd-style', () => ({
+ // `ContextMenuTrigger` comes from the base-ui barrel, which pulls in
+ // ScrollArea's global style at import time.
+ createGlobalStyle: () => () => null,
createStaticStyles: () => ({
dotContainer: 'dotContainer',
neonDot: 'neonDot',
@@ -115,10 +119,8 @@ vi.mock('@/store/chat', () => ({
selector: (state: {
prefetchMessages: typeof prefetchMessagesMock;
topicLoadingIds: string[];
- topicRenamingId: string;
}) => unknown,
- ) =>
- selector({ prefetchMessages: prefetchMessagesMock, topicLoadingIds: [], topicRenamingId: '' }),
+ ) => selector({ prefetchMessages: prefetchMessagesMock, topicLoadingIds: [] }),
}));
vi.mock('@/store/chat/selectors', () => ({
operationSelectors: {
@@ -148,9 +150,6 @@ vi.mock('./metaCardData', () => ({
vi.mock('./Actions', () => ({
default: () => null,
}));
-vi.mock('./Editing', () => ({
- default: () => null,
-}));
vi.mock('./useDropdownMenu', () => ({
useTopicItemDropdownMenu: () => ({ dropdownMenu: [] }),
}));
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
similarity index 83%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
rename to src/features/AgentSidebar/Topic/List/Item/index.tsx
index c1ec27cea44..5b6b19aaf57 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -9,8 +9,8 @@ import { Flexbox, Icon, Popover, Skeleton, Tag, Text, Tooltip } from '@lobehub/u
import { createStaticStyles, cssVar, useTheme } from 'antd-style';
import dayjs from 'dayjs';
import { HashIcon, MessageSquareDashed } from 'lucide-react';
-import type { CSSProperties, DragEvent } from 'react';
-import { memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react';
+import type { CSSProperties, DragEvent, RefObject } from 'react';
+import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
@@ -37,10 +37,9 @@ import { useElectronStore } from '@/store/electron';
import { useTopicNavigation } from '../../hooks/useTopicNavigation';
import ThreadList from '../../TopicListContent/ThreadList';
import Actions from './Actions';
-import Editing from './Editing';
+import TopicItemContextMenu from './ContextMenu';
import { getPullRequestState, getTopicMetaCard, PR_STATE_VISUAL } from './metaCardData';
import MetaHoverCard from './MetaHoverCard';
-import { useTopicItemDropdownMenu } from './useDropdownMenu';
// 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
@@ -150,8 +149,32 @@ interface TopicItemProps {
userId?: string;
}
-const TopicItem = memo<TopicItemProps>(
- ({ id, title, fav, active, threadId, metadata, status, showWorkingDirectory, userId }) => {
+type TopicNavigationActions = Pick<
+ ReturnType<typeof useTopicNavigation>,
+ 'focusTopicPopup' | 'navigateToTopic'
+>;
+
+interface TopicItemRowProps extends TopicItemProps {
+ defaultTopicActive: boolean;
+ isTopicActive: boolean;
+ navRef: RefObject<TopicNavigationActions>;
+ showThreadList: boolean;
+}
+
+const TopicItemRow = memo<TopicItemRowProps>(
+ ({
+ id,
+ title,
+ fav,
+ metadata,
+ status,
+ showWorkingDirectory,
+ userId,
+ defaultTopicActive,
+ isTopicActive,
+ navRef,
+ showThreadList,
+ }) => {
const { t } = useTranslation('topic');
const { isDarkMode } = useTheme();
const activeAgentId = useAgentStore((s) => s.activeAgentId);
@@ -182,10 +205,7 @@ const TopicItem = memo<TopicItemProps>(
return buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug);
}, [activeAgentId, activeWorkspaceSlug, id]);
- const [editing, isLoading] = useChatStore((s) => [
- id ? s.topicRenamingId === id : false,
- id ? s.topicLoadingIds.includes(id) : false,
- ]);
+ const isLoading = useChatStore((s) => (id ? s.topicLoadingIds.includes(id) : false));
const isUnreadCompleted = useChatStore(
id ? operationSelectors.isTopicUnreadCompleted(id) : () => false,
@@ -204,21 +224,6 @@ const TopicItem = memo<TopicItemProps>(
: () => false,
);
- const {
- focusTopicPopup,
- navigateToTopic,
- isInAgentSubRoute,
- isInTopicContextRoute,
- routeTopicId,
- urlTopicId,
- } = useTopicNavigation();
- const isRouteTopicActive = Boolean(id && routeTopicId === id && isInTopicContextRoute);
- const isTopicActive = Boolean(
- (active || isRouteTopicActive) && !threadId && (!isInAgentSubRoute || isRouteTopicActive),
- );
-
- const shouldShowThreadList = Boolean(id && id === urlTopicId);
-
const handleDragStart = useCallback(
(event: DragEvent) => {
if (!id) return;
@@ -228,43 +233,28 @@ const TopicItem = memo<TopicItemProps>(
[id, title],
);
- const toggleEditing = useCallback(
- (visible?: boolean) => {
- useChatStore.setState({ topicRenamingId: visible && id ? id : '' });
- },
- [id],
- );
-
const handleClick = useCallback(() => {
- if (editing) return;
if (isDesktop) {
cancelPendingSingleClick();
pendingSingleClickTimer = setTimeout(() => {
pendingSingleClickTimer = null;
- void navigateToTopic(id);
+ void navRef.current.navigateToTopic(id);
}, 250);
} else {
- void navigateToTopic(id);
+ void navRef.current.navigateToTopic(id);
}
- }, [editing, id, navigateToTopic]);
+ }, [id, navRef]);
const handleDoubleClick = useCallback(async () => {
if (!id || !activeAgentId || !isDesktop) return;
cancelPendingSingleClick();
- if (await focusTopicPopup(id)) {
- void navigateToTopic(id, { skipPopupFocus: true });
+ if (await navRef.current.focusTopicPopup(id)) {
+ void navRef.current.navigateToTopic(id, { skipPopupFocus: true });
return;
}
addTab(buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug));
- void navigateToTopic(id);
- }, [id, activeAgentId, activeWorkspaceSlug, addTab, focusTopicPopup, navigateToTopic]);
-
- const { dropdownMenu } = useTopicItemDropdownMenu({
- fav,
- id,
- status,
- title,
- });
+ void navRef.current.navigateToTopic(id);
+ }, [id, activeAgentId, activeWorkspaceSlug, addTab, navRef]);
const isFailed = status === 'failed';
const isRunning = status === 'running';
@@ -324,7 +314,7 @@ const TopicItem = memo<TopicItemProps>(
if (!id) {
return (
<NavItem
- active={Boolean(active && !isInAgentSubRoute && !isInTopicContextRoute)}
+ active={defaultTopicActive}
slots={{ titlePrefix: draftPrefix }}
titleColor={cssVar.colorText}
icon={
@@ -467,23 +457,23 @@ const TopicItem = memo<TopicItemProps>(
);
const navItem = (
- <NavItem
- actions={<Actions dropdownMenu={dropdownMenu} />}
- active={isTopicActive}
- contextMenuItems={dropdownMenu}
- description={workingDirectoryNode}
- disabled={editing}
- draggable={!editing}
- extra={<RunningElapsedTime agentId={activeAgentId} topicId={id} />}
- href={href}
- icon={leadingIconNode}
- slots={{ titlePrefix: draftPrefix }}
- title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}
- titleColor={cssVar.colorText}
- onClick={handleClick}
- onDoubleClick={() => void handleDoubleClick()}
- onDragStart={handleDragStart}
- />
+ <TopicItemContextMenu fav={fav} id={id} status={status} title={title}>
+ <NavItem
+ draggable
+ actions={() => <Actions fav={fav} id={id} status={status} title={title} />}
+ active={isTopicActive}
+ description={workingDirectoryNode}
+ extra={<RunningElapsedTime agentId={activeAgentId} topicId={id} />}
+ href={href}
+ icon={leadingIconNode}
+ slots={{ titlePrefix: draftPrefix }}
+ title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}
+ titleColor={cssVar.colorText}
+ onClick={handleClick}
+ onDoubleClick={() => void handleDoubleClick()}
+ onDragStart={handleDragStart}
+ />
+ </TopicItemContextMenu>
);
return (
@@ -502,8 +492,7 @@ const TopicItem = memo<TopicItemProps>(
) : (
navItem
)}
- <Editing id={id} title={title} toggleEditing={toggleEditing} />
- {shouldShowThreadList && (
+ {showThreadList && (
<Suspense
fallback={
<Flexbox gap={8} paddingBlock={8} paddingInline={24} width={'100%'}>
@@ -520,4 +509,49 @@ const TopicItem = memo<TopicItemProps>(
},
);
+TopicItemRow.displayName = 'TopicItemRow';
+
+/**
+ * Route awareness is resolved here rather than inside the row so that a
+ * navigation re-renders only this thin shell. `useTopicNavigation` subscribes to
+ * the pathname *and* to the chat store, so keeping it in the row made every
+ * visible topic re-render its whole subtree twice per topic switch β€” with no
+ * prop change to show for it. The row now takes plain booleans and bails out.
+ *
+ * The callbacks go through a ref because their identity changes on every
+ * navigation; passing them as props would defeat the row's memo.
+ */
+const TopicItem = memo<TopicItemProps>((props) => {
+ const { active, id, threadId } = props;
+ const {
+ focusTopicPopup,
+ navigateToTopic,
+ isInAgentSubRoute,
+ isInTopicContextRoute,
+ routeTopicId,
+ urlTopicId,
+ } = useTopicNavigation();
+
+ const navRef = useRef<TopicNavigationActions>({ focusTopicPopup, navigateToTopic });
+ useEffect(() => {
+ navRef.current = { focusTopicPopup, navigateToTopic };
+ }, [focusTopicPopup, navigateToTopic]);
+
+ const isRouteTopicActive = Boolean(id && routeTopicId === id && isInTopicContextRoute);
+
+ return (
+ <TopicItemRow
+ {...props}
+ defaultTopicActive={Boolean(active && !isInAgentSubRoute && !isInTopicContextRoute)}
+ navRef={navRef}
+ showThreadList={Boolean(id && id === urlTopicId)}
+ isTopicActive={Boolean(
+ (active || isRouteTopicActive) && !threadId && (!isInAgentSubRoute || isRouteTopicActive),
+ )}
+ />
+ );
+});
+
+TopicItem.displayName = 'TopicItem';
+
export default TopicItem;
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/metaCardData.ts b/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/metaCardData.ts
rename to src/features/AgentSidebar/Topic/List/Item/metaCardData.ts
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.test.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx
rename to src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.test.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
similarity index 99%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
rename to src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
index 0c7a60195f6..14cf13a114c 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -41,7 +41,7 @@ import { useElectronStore } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import { isForbiddenError } from '@/utils/forbiddenError';
-interface TopicItemDropdownMenuProps {
+export interface TopicItemDropdownMenuProps {
fav?: boolean;
id?: string;
status?: ChatTopicStatus | null;
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.test.tsx b/src/features/AgentSidebar/Topic/List/index.test.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.test.tsx
rename to src/features/AgentSidebar/Topic/List/index.test.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.tsx b/src/features/AgentSidebar/Topic/List/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/List/index.tsx
rename to src/features/AgentSidebar/Topic/List/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/ToggleGroups.tsx b/src/features/AgentSidebar/Topic/ToggleGroups.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/ToggleGroups.tsx
rename to src/features/AgentSidebar/Topic/ToggleGroups.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/index.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/statusCounts.test.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/statusCounts.test.ts
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/statusCounts.test.ts
rename to src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/statusCounts.test.ts
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/statusCounts.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/statusCounts.ts
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByProjectMode/statusCounts.ts
rename to src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/statusCounts.ts
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByStatusMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByStatusMode/index.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/FlatMode/index.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/GroupedAccordion.tsx b/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/GroupedAccordion.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/SearchResult/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/SearchResult/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/SearchResult/index.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/SearchResult/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/Actions.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/Actions.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/Actions.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/Actions.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Editing.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/Editing.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/Editing.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/Editing.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/ThreadList/index.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/ThreadList/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent/index.tsx
rename to src/features/AgentSidebar/Topic/TopicListContent/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/TopicSearchBar/index.tsx b/src/features/AgentSidebar/Topic/TopicSearchBar/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/TopicSearchBar/index.tsx
rename to src/features/AgentSidebar/Topic/TopicSearchBar/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useAgentTopicGroupMode.ts b/src/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode.ts
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useAgentTopicGroupMode.ts
rename to src/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode.ts
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts b/src/features/AgentSidebar/Topic/hooks/useThreadNavigation.ts
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useThreadNavigation.ts
rename to src/features/AgentSidebar/Topic/hooks/useThreadNavigation.ts
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx b/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.test.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.test.tsx
rename to src/features/AgentSidebar/Topic/hooks/useTopicNavigation.test.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts b/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.ts
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useTopicNavigation.ts
rename to src/features/AgentSidebar/Topic/hooks/useTopicNavigation.ts
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/index.tsx b/src/features/AgentSidebar/Topic/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/index.tsx
rename to src/features/AgentSidebar/Topic/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.test.tsx b/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
similarity index 88%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
rename to src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
index 827c4275da2..48424a9167f 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
+++ b/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
@@ -110,7 +110,7 @@ vi.mock('@/store/global/selectors', () => ({
}));
const getMenuItem = (
- items: NonNullable<ReturnType<typeof useTopicActionsDropdownMenu>>,
+ items: NonNullable<ReturnType<ReturnType<typeof useTopicActionsDropdownMenu>>>,
key: string,
) => items.find((item) => item && 'key' in item && item.key === key);
@@ -138,17 +138,17 @@ describe('useTopicActionsDropdownMenu', () => {
const { result } = renderHook(() => useTopicActionsDropdownMenu());
- expect(getMenuItem(result.current!, 'import')).toMatchObject({ disabled: true });
- expect(getMenuItem(result.current!, 'archiveMergedPullRequests')).toMatchObject({
+ expect(getMenuItem(result.current()!, 'import')).toMatchObject({ disabled: true });
+ expect(getMenuItem(result.current()!, 'archiveMergedPullRequests')).toMatchObject({
disabled: true,
});
- expect(getMenuItem(result.current!, 'deleteUnstarred')).toMatchObject({ disabled: true });
- expect(getMenuItem(result.current!, 'deleteAll')).toMatchObject({ disabled: true });
+ expect(getMenuItem(result.current()!, 'deleteUnstarred')).toMatchObject({ disabled: true });
+ expect(getMenuItem(result.current()!, 'deleteAll')).toMatchObject({ disabled: true });
});
it('keeps the personal delete-all copy', () => {
const { result } = renderHook(() => useTopicActionsDropdownMenu());
- const item = getMenuItem(result.current!, 'deleteAll');
+ const item = getMenuItem(result.current()!, 'deleteAll');
expect(item).toMatchObject({ label: 'actions.removeAll' });
if (item && 'onClick' in item) item.onClick?.({} as never);
@@ -164,7 +164,7 @@ describe('useTopicActionsDropdownMenu', () => {
workspaceMock.activeWorkspaceId = 'workspace-1';
const { result } = renderHook(() => useTopicActionsDropdownMenu());
- const item = getMenuItem(result.current!, 'deleteAll');
+ const item = getMenuItem(result.current()!, 'deleteAll');
expect(item).toMatchObject({ label: 'actions.removeAllOwn' });
if (item && 'onClick' in item) item.onClick?.({} as never);
@@ -174,7 +174,7 @@ describe('useTopicActionsDropdownMenu', () => {
title: 'actions.removeAllOwn',
}),
);
- expect(getMenuItem(result.current!, 'deleteAllWorkspace')).toBeUndefined();
+ expect(getMenuItem(result.current()!, 'deleteAllWorkspace')).toBeUndefined();
await confirmModalMock.mock.calls[0][0].onOk();
expect(removeSessionTopicsMock).toHaveBeenCalledWith('own');
});
@@ -202,10 +202,13 @@ describe('useTopicActionsDropdownMenu', () => {
];
const { result } = renderHook(() => useTopicActionsDropdownMenu());
- const ownItem = getMenuItem(result.current!, 'deleteAll');
- const workspaceArchiveItem = getMenuItem(result.current!, 'archiveMergedPullRequestsWorkspace');
- const workspaceUnstarredItem = getMenuItem(result.current!, 'deleteUnstarredWorkspace');
- const workspaceItem = getMenuItem(result.current!, 'deleteAllWorkspace');
+ const ownItem = getMenuItem(result.current()!, 'deleteAll');
+ const workspaceArchiveItem = getMenuItem(
+ result.current()!,
+ 'archiveMergedPullRequestsWorkspace',
+ );
+ const workspaceUnstarredItem = getMenuItem(result.current()!, 'deleteUnstarredWorkspace');
+ const workspaceItem = getMenuItem(result.current()!, 'deleteAllWorkspace');
expect(ownItem).toMatchObject({ label: 'actions.removeAllOwn' });
if (ownItem && 'onClick' in ownItem) ownItem.onClick?.({} as never);
@@ -283,8 +286,8 @@ describe('useTopicActionsDropdownMenu', () => {
];
const { result } = renderHook(() => useTopicActionsDropdownMenu());
- const archiveItem = getMenuItem(result.current!, 'archiveMergedPullRequests');
- const deleteUnstarredItem = getMenuItem(result.current!, 'deleteUnstarred');
+ const archiveItem = getMenuItem(result.current()!, 'archiveMergedPullRequests');
+ const deleteUnstarredItem = getMenuItem(result.current()!, 'deleteUnstarred');
expect(archiveItem).toMatchObject({ label: 'actions.archiveMergedPullRequestsOwn' });
if (archiveItem && 'onClick' in archiveItem) await archiveItem.onClick?.({} as never);
@@ -304,8 +307,8 @@ describe('useTopicActionsDropdownMenu', () => {
});
await confirmModalMock.mock.calls[0][0].onOk();
expect(removeUnstarredTopicMock).toHaveBeenCalledWith({ onlyOwn: true });
- expect(getMenuItem(result.current!, 'archiveMergedPullRequestsWorkspace')).toBeUndefined();
- expect(getMenuItem(result.current!, 'deleteUnstarredWorkspace')).toBeUndefined();
+ expect(getMenuItem(result.current()!, 'archiveMergedPullRequestsWorkspace')).toBeUndefined();
+ expect(getMenuItem(result.current()!, 'deleteUnstarredWorkspace')).toBeUndefined();
});
it('archives only unfinished topics whose pull requests are merged', async () => {
@@ -343,7 +346,7 @@ describe('useTopicActionsDropdownMenu', () => {
];
const { result } = renderHook(() => useTopicActionsDropdownMenu());
- const item = getMenuItem(result.current!, 'archiveMergedPullRequests');
+ const item = getMenuItem(result.current()!, 'archiveMergedPullRequests');
expect(item && 'onClick' in item).toBe(true);
if (item && 'onClick' in item) await item.onClick?.({} as never);
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/useDropdownMenu.tsx
similarity index 98%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.tsx
rename to src/features/AgentSidebar/Topic/useDropdownMenu.tsx
index 3346f39b9c1..5b45fd7fe8c 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/useDropdownMenu.tsx
+++ b/src/features/AgentSidebar/Topic/useDropdownMenu.tsx
@@ -5,7 +5,7 @@ import { confirmModal } from '@lobehub/ui/base-ui';
import { App, Upload } from 'antd';
import { css, cx } from 'antd-style';
import { Archive, HardDriveDownload, Hash, Import, LucideCheck, Trash } from 'lucide-react';
-import { useCallback, useMemo } from 'react';
+import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
@@ -37,7 +37,7 @@ type TopicMaintenanceScope = 'own' | 'workspace';
export const useTopicActionsDropdownMenu = (
options: UseTopicActionsDropdownMenuOptions = {},
-): MenuProps['items'] => {
+): (() => MenuProps['items']) => {
const { t } = useTranslation(['topic', 'common']);
const { message, modal } = App.useApp();
const { onUploadClose } = options;
@@ -128,7 +128,7 @@ export const useTopicActionsDropdownMenu = (
const enableHeteroSessionImport = useUserStore(labPreferSelectors.enableHeteroSessionImport);
- return useMemo(() => {
+ return useCallback((): MenuProps['items'] => {
const pageSizeOptions = [20, 40, 60, 100];
const pageSizeItems = pageSizeOptions.map((size) => ({
icon: topicPageSize === size ? <Icon icon={LucideCheck} /> : <div />,
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/useFilterMenu.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.tsx
similarity index 94%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/useFilterMenu.tsx
rename to src/features/AgentSidebar/Topic/useFilterMenu.tsx
index 765884b921b..bcf1b6c09bb 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/useFilterMenu.tsx
+++ b/src/features/AgentSidebar/Topic/useFilterMenu.tsx
@@ -1,7 +1,7 @@
import { Icon } from '@lobehub/ui';
import type { DropdownItem } from '@lobehub/ui/base-ui';
import { LucideCheck } from 'lucide-react';
-import { useMemo } from 'react';
+import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useUserStore } from '@/store/user';
@@ -10,7 +10,7 @@ import type { TopicGroupMode, TopicSortBy } from '@/types/topic';
import { useAgentTopicGroupMode } from './hooks/useAgentTopicGroupMode';
-export const useTopicFilterDropdownMenu = (): DropdownItem[] => {
+export const useTopicFilterDropdownMenu = (): (() => DropdownItem[]) => {
const { t } = useTranslation('topic');
const { topicGroupMode, updateTopicGroupMode } = useAgentTopicGroupMode();
@@ -20,7 +20,7 @@ export const useTopicFilterDropdownMenu = (): DropdownItem[] => {
s.updatePreference,
]);
- return useMemo(() => {
+ return useCallback(() => {
const groupModes: TopicGroupMode[] = ['byStatus', 'byTime', 'byProject', 'flat'];
const sortByOptions: TopicSortBy[] = ['createdAt', 'updatedAt'];
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/utils/topicGroupMode.test.ts b/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/utils/topicGroupMode.test.ts
rename to src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/utils/topicGroupMode.ts b/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/Topic/utils/topicGroupMode.ts
rename to src/features/AgentSidebar/Topic/utils/topicGroupMode.ts
diff --git a/src/routes/(main)/agent/_layout/Sidebar/index.tsx b/src/features/AgentSidebar/index.tsx
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/index.tsx
rename to src/features/AgentSidebar/index.tsx
diff --git a/src/routes/(main)/agent/_layout/Sidebar/utils/agentPathname.test.ts b/src/features/AgentSidebar/utils/agentPathname.test.ts
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/utils/agentPathname.test.ts
rename to src/features/AgentSidebar/utils/agentPathname.test.ts
diff --git a/src/routes/(main)/agent/_layout/Sidebar/utils/agentPathname.ts b/src/features/AgentSidebar/utils/agentPathname.ts
similarity index 100%
rename from src/routes/(main)/agent/_layout/Sidebar/utils/agentPathname.ts
rename to src/features/AgentSidebar/utils/agentPathname.ts
diff --git a/src/features/AgentTopicManager/TopicListView.tsx b/src/features/AgentTopicManager/TopicListView.tsx
index 2175dc4bc81..0e6db44b0ed 100644
--- a/src/features/AgentTopicManager/TopicListView.tsx
+++ b/src/features/AgentTopicManager/TopicListView.tsx
@@ -8,9 +8,9 @@ import { FolderIcon, MoreHorizontal, Star } from 'lucide-react';
import { Fragment, memo, type MouseEvent, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import { useTopicItemDropdownMenu } from '@/features/AgentSidebar/Topic/List/Item/useDropdownMenu';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useActivityTime } from '@/hooks/useActivityTime';
-import { useTopicItemDropdownMenu } from '@/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu';
import type { ChatTopic } from '@/types/topic';
import StatusDot from './StatusDot';
diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsx
index 1d0ec682b9f..c1455e1b334 100644
--- a/src/features/ChatInput/ActionBar/Plus/index.tsx
+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx
@@ -285,7 +285,7 @@ const stripPopoverContent = (items?: ActionDropdownMenuItems): ActionDropdownMen
return nextItem;
}) ?? [];
-const PlusAction = memo(() => {
+const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuItems => {
const { t } = useTranslation('chat');
const { t: tEditor } = useTranslation('editor');
const { t: tSetting } = useTranslation('setting');
@@ -294,7 +294,6 @@ const PlusAction = memo(() => {
const agentId = useAgentId();
const { canConfigureResource } = useChatInputResourceAccess();
const { updateAgentChatConfig } = useUpdateAgentConfig();
- const [dropdownOpen, setDropdownOpen] = useState(false);
// Topic acceptance (lab): a "new acceptance item" entry in the "+" menu, so a
// topic's checklist starts from here instead of an always-on strip above the
@@ -340,18 +339,17 @@ const PlusAction = memo(() => {
);
const enableFC = useModelSupportToolUse(model, provider);
const handleOpenKnowledge = useCallback(() => {
- setDropdownOpen(false);
+ close();
openAttachKnowledgeModal();
- }, []);
+ }, [close]);
const {
enabledCount: knowledgeEnabledCount,
footer: knowledgeFooter,
items: knowledgeItems,
} = useKnowledgeControls({ openAttachKnowledgeModal: handleOpenKnowledge });
- const closeDropdown = useCallback(() => setDropdownOpen(false), []);
+ const closeDropdown = useCallback(() => close(), [close]);
const {
autoCount: skillAutoCount,
- editPluginDrawer: skillEditPluginDrawer,
marketFooter: skillMarketFooter,
marketHeader: skillMarketHeader,
marketItems: skillItems,
@@ -402,16 +400,16 @@ const PlusAction = memo(() => {
);
const handleToggleParams = useCallback(() => {
- setDropdownOpen(false);
+ close();
if (isParamsPanelActive) {
toggleRightPanel(false);
return;
}
setWorkingSidebarTab('params');
toggleRightPanel(true);
- }, [isParamsPanelActive, setWorkingSidebarTab, toggleRightPanel]);
+ }, [close, isParamsPanelActive, setWorkingSidebarTab, toggleRightPanel]);
- const items: ActionDropdownMenuItems = useMemo(() => {
+ const items = useMemo<ActionDropdownMenuItems>(() => {
const renderActive = (label: string, active: boolean) =>
active ? (
<div className={cx(activeLabel)}>
@@ -498,7 +496,7 @@ const PlusAction = memo(() => {
);
return false;
}
- setDropdownOpen(false);
+ close();
editor?.focus();
await upload([file], agentId);
return false;
@@ -778,25 +776,32 @@ const PlusAction = memo(() => {
skillMarketFooter,
skillMarketHeader,
upload,
+ close,
]);
+ return items;
+};
+
+/**
+ * The trigger stays hook-free: every store subscription and the whole item tree
+ * live in `usePlusMenuItems`, which ActionDropdown only invokes from inside the
+ * popup β€” so opening a conversation no longer pays for a menu nobody opened.
+ */
+const PlusAction = memo(() => {
+ const { t } = useTranslation('chat');
+
return (
- <>
- <ChatInputAction
- icon={PlusIcon}
- open={dropdownOpen}
- size={{ blockSize: 32, borderRadius: 16, size: 18 }}
- title={t('plus.tooltip')}
- tooltipProps={{ placement: 'top' }}
- dropdown={{
- menu: { items },
- minWidth: 220,
- placement: 'topLeft',
- }}
- onOpenChange={setDropdownOpen}
- />
- {skillEditPluginDrawer}
- </>
+ <ChatInputAction
+ icon={PlusIcon}
+ size={{ blockSize: 32, borderRadius: 16, size: 18 }}
+ title={t('plus.tooltip')}
+ tooltipProps={{ placement: 'top' }}
+ dropdown={{
+ menu: { useItems: usePlusMenuItems },
+ minWidth: 220,
+ placement: 'topLeft',
+ }}
+ />
);
});
diff --git a/src/features/ChatInput/ActionBar/Tools/index.tsx b/src/features/ChatInput/ActionBar/Tools/index.tsx
index fe72eda0ca7..cae545dbc21 100644
--- a/src/features/ChatInput/ActionBar/Tools/index.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/index.tsx
@@ -13,7 +13,7 @@ import { useControls } from './useControls';
const Tools = memo(() => {
const { t } = useTranslation('setting');
- const { marketItems, editPluginDrawer, pinnedCount, autoCount, isPolicyMenuOpen } = useControls();
+ const { marketItems, pinnedCount, autoCount, isPolicyMenuOpen } = useControls();
const agentId = useAgentId();
const { model, provider } = useEffectiveModel(agentId);
@@ -54,7 +54,6 @@ const Tools = memo(() => {
},
}}
/>
- {editPluginDrawer}
</Suspense>
);
});
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index 2f4ba21adae..bf484ea332f 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -30,8 +30,8 @@ import type { ReactNode } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { CustomConnectorModal } from '@/features/Connectors';
-import DevModal from '@/features/PluginDevModal';
+import { openConnectorEditDrawer } from '@/features/Connectors/CustomConnectorModal/imperative';
+import { openPluginEditDrawer } from '@/features/PluginDevModal/imperative';
import { createSkillStoreModal } from '@/features/SkillStore';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useCheckPluginsIsInstalled } from '@/hooks/useCheckPluginsIsInstalled';
@@ -380,11 +380,7 @@ const styles = createStaticStyles(({ css }) => ({
gap: 8px;
align-items: center;
- /* width: 320px + margin-inline: -12px anchors the submenu to 320px so it
- matches the attachment submenu, and lets the row break out of the footer's
- 12px inline padding to span full width; padding-inline: 12px then re-aligns
- the icon/text to the same column as the menu rows above. */
- width: 320px;
+ width: calc(100% + 24px);
min-height: 32px;
margin-inline: -12px;
padding-inline: 12px;
@@ -431,25 +427,15 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
uninstallPlugin,
removeComposioConnection,
deleteAgentSkill,
- installCustomPlugin,
- updateNewCustomPlugin,
uninstallBuiltinTool,
deleteConnector,
] = useToolStore((s) => [
s.uninstallCustomPlugin,
s.removeComposioConnection,
s.deleteAgentSkill,
- s.installCustomPlugin,
- s.updateNewCustomPlugin,
s.uninstallBuiltinTool,
s.deleteConnector,
]);
- const [editingPluginId, setEditingPluginId] = useState<string | null>(null);
- const [editingConnectorDbId, setEditingConnectorDbId] = useState<string | null>(null);
- const editingCustomPlugin = useToolStore(
- pluginSelectors.getCustomPluginById(editingPluginId ?? ''),
- isEqual,
- );
const [checked, togglePlugin, setPluginMode] = useAgentStore((s) => [
// Pinned identifiers only (getAgentPluginsById already excludes disabled).
agentByIdSelectors.getAgentPluginsById(agentId)(s),
@@ -1322,7 +1308,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
return createManagedSkillItem({
badge: <Icon icon={McpIcon} size={12} />,
- configureConfig: { onConfigure: () => setEditingConnectorDbId(connector.id) },
+ configureConfig: { onConfigure: () => openConnectorEditDrawer(connector.id) },
deleteConfig: {
displayName: title,
onDelete: async () => {
@@ -1423,7 +1409,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
return createManagedSkillItem({
badge: isMcp ? <Icon icon={McpIcon} size={12} /> : undefined,
configureConfig: isCustom
- ? { onConfigure: () => setEditingPluginId(item.identifier) }
+ ? { onConfigure: () => openPluginEditDrawer(item.identifier) }
: undefined,
deleteConfig: {
displayName: item.title ?? item.identifier,
@@ -2015,39 +2001,8 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
t,
]);
- const editPluginDrawer = (
- <>
- <DevModal
- mode={'edit'}
- open={!!editingPluginId}
- value={editingCustomPlugin}
- onValueChange={updateNewCustomPlugin}
- onDelete={() => {
- if (!canEdit) return;
- if (editingPluginId) uninstallPlugin(editingPluginId);
- setEditingPluginId(null);
- }}
- onOpenChange={(open) => {
- if (!open) setEditingPluginId(null);
- }}
- onSave={async (devPlugin) => {
- if (!canEdit) return;
- await installCustomPlugin(devPlugin);
- setEditingPluginId(null);
- }}
- />
- <CustomConnectorModal
- connectorId={editingConnectorDbId ?? undefined}
- open={!!editingConnectorDbId}
- onClose={() => setEditingConnectorDbId(null)}
- onEditSuccess={() => setEditingConnectorDbId(null)}
- />
- </>
- );
-
return {
autoCount: allAutoItems.length,
- editPluginDrawer,
installedPluginItems,
isPolicyMenuOpen: policyOpenId !== null,
marketFooter,
diff --git a/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx b/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
index 67f5e827443..7ff1baa46d4 100644
--- a/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
+++ b/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
@@ -74,10 +74,23 @@ const SubmenuScrollStyle = createGlobalStyle`
overflow: hidden auto;
overscroll-behavior: contain;
+ /* The popup is shrink-to-fit, so one long item title would otherwise widen
+ the whole submenu. Bound the container and let rows fill it β€” the
+ min-width:0 chain below turns the overflow into an ellipsis. */
+ max-width: min(90vw, 400px);
max-height: min(50vh, 640px);
padding-block-end: 4px;
}
+ /* The skill submenu (the one with the search header) has collapsible groups,
+ so shrink-to-fit makes it resize every time a group opens or closes β€”
+ measured 243px collapsed vs 400px expanded, the jump driven by whichever
+ title happens to be longest. Pin the width so the container stays put and
+ the rows ellipsize into it. */
+ [data-submenu] > [role='menu']:has(.lobe-skill-submenu-search) {
+ width: min(90vw, 400px);
+ }
+
/* base-ui menu-item internal containers are flex by default but don't set
min-width:0, which blocks descendant text-overflow:ellipsis from working.
Force min-width:0 down the chain so long titles can truncate. */
@@ -137,11 +150,35 @@ export type ActionDropdownMenuItem = MenuItemType;
*/
export type ActionDropdownMenuItems = BaseMenuItemType[];
+interface MenuItemsHostProps {
+ close: () => void;
+ decorate: (items: ActionDropdownMenuItems) => ActionDropdownMenuItems;
+ useItems: (ctx: { close: () => void }) => ActionDropdownMenuItems;
+}
+
+/**
+ * Rendered inside the popup, which Base UI only mounts while the menu is open β€”
+ * so `useItems` and everything it subscribes to stays off the trigger's mount path.
+ */
+const MenuItemsHost = memo<MenuItemsHostProps>(({ close, decorate, useItems }) => {
+ const items = useItems({ close });
+
+ return <>{renderDropdownMenuItems(decorate(items ?? []))}</>;
+});
+
+MenuItemsHost.displayName = 'ActionDropdownMenuItemsHost';
+
type ActionDropdownMenu = Omit<
Pick<MenuProps<ActionDropdownMenuItem>, 'className' | 'onClick' | 'style'>,
'items'
> & {
- items: ActionDropdownMenuItems | (() => ActionDropdownMenuItems);
+ items?: ActionDropdownMenuItems | (() => ActionDropdownMenuItems);
+ /**
+ * Hook form of `items`, invoked from inside the popup so it only runs while the
+ * menu is open. Use this when building the items needs hooks (store subscriptions,
+ * SWR, local state) that would otherwise run on every mount of the trigger.
+ */
+ useItems?: (ctx: { close: () => void }) => ActionDropdownMenuItems;
};
export interface ActionDropdownProps extends Omit<DropdownMenuProps, 'items'> {
@@ -290,7 +327,13 @@ const ActionDropdown = memo<ActionDropdownProps>(
[menu],
);
+ const closePopup = useCallback(() => {
+ onOpenChange?.(false, { reason: 'item-press' } as never);
+ if (open === undefined) setUncontrolledOpen(false);
+ }, [onOpenChange, open]);
+
const renderedItems = useMemo(() => {
+ if (menu.useItems) return null;
if (!prefetch && !isOpen) return menuItemsRef.current;
const sourceItems = typeof menu.items === 'function' ? menu.items() : menu.items;
const nextItems = renderDropdownMenuItems(decorateMenuItems(sourceItems ?? []));
@@ -301,10 +344,16 @@ const ActionDropdown = memo<ActionDropdownProps>(
}, [decorateMenuItems, isOpen, menu, prefetch]);
const menuContent = useMemo(() => {
- if (!popupRender) return renderedItems;
+ const body = menu.useItems ? (
+ <MenuItemsHost close={closePopup} decorate={decorateMenuItems} useItems={menu.useItems} />
+ ) : (
+ renderedItems
+ );
+
+ if (!popupRender) return body;
- return popupRender(renderedItems ?? null);
- }, [popupRender, renderedItems]);
+ return popupRender(body ?? null);
+ }, [closePopup, decorateMenuItems, menu.useItems, popupRender, renderedItems]);
const resolvedPopupClassName = useMemo<DropdownMenuPopupProps['className']>(() => {
const popupClassName = popupProps?.className;
diff --git a/src/features/ChatInput/ControlBar/ApprovalMode.tsx b/src/features/ChatInput/ControlBar/ApprovalMode.tsx
index 989fea0ce2a..4836041a1c5 100644
--- a/src/features/ChatInput/ControlBar/ApprovalMode.tsx
+++ b/src/features/ChatInput/ControlBar/ApprovalMode.tsx
@@ -96,8 +96,8 @@ const ModeSelector = memo(() => {
[disabled],
);
- const menuItems = useMemo<MenuProps['items']>(
- () => [
+ const menuItems = useCallback(
+ (): MenuProps['items'] => [
{
extra: approvalMode === 'auto-run' ? <Icon icon={Check} /> : undefined,
key: 'auto-run',
diff --git a/src/features/Connectors/CustomConnectorModal/imperative.tsx b/src/features/Connectors/CustomConnectorModal/imperative.tsx
new file mode 100644
index 00000000000..1af55b0ba00
--- /dev/null
+++ b/src/features/Connectors/CustomConnectorModal/imperative.tsx
@@ -0,0 +1,15 @@
+'use client';
+
+import { mountImperative } from '@/components/ImperativeMount';
+
+import CustomConnectorModal from '.';
+
+export const openConnectorEditDrawer = (connectorId: string) =>
+ mountImperative(({ close, open }) => (
+ <CustomConnectorModal
+ connectorId={connectorId}
+ open={open}
+ onClose={close}
+ onEditSuccess={close}
+ />
+ ));
diff --git a/src/features/NavPanel/components/NavItem.tsx b/src/features/NavPanel/components/NavItem.tsx
index e87e66742a6..32a08d215cd 100644
--- a/src/features/NavPanel/components/NavItem.tsx
+++ b/src/features/NavPanel/components/NavItem.tsx
@@ -3,12 +3,14 @@
import { type BlockProps, type GenericItemType, type IconProps } from '@lobehub/ui';
import { Block, Center, ContextMenuTrigger, Flexbox, Icon, Text } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
-import { type ReactNode } from 'react';
+import { type FocusEvent, type PointerEvent, type ReactNode } from 'react';
import { memo } from 'react';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { isModifierClick } from '@/utils/navigation';
+import { type LazyActions, useLazyActions } from './useLazyActions';
+
const ACTION_CLASS_NAME = 'nav-item-actions';
const styles = createStaticStyles(({ css }) => ({
@@ -23,7 +25,8 @@ const styles = createStaticStyles(({ css }) => ({
opacity: 0;
transition: opacity 0.2s ${cssVar.motionEaseOut};
- &:has([data-popup-open]) {
+ &:has([data-popup-open]),
+ &:focus-within {
width: unset;
opacity: 1;
}
@@ -44,7 +47,15 @@ export interface NavItemSlots {
}
export interface NavItemProps extends Omit<BlockProps, 'children' | 'title'> {
- actions?: ReactNode;
+ /**
+ * Pass a thunk to defer mounting until the row is first pointed at or focused.
+ * Actions are invisible until `:hover` anyway, and an overlay-bearing action (a
+ * dropdown, a popover) costs a dozen fibers per row β€” enough to matter in a
+ * list. Focus counts as well as the pointer: a keyboard user tabs to the row
+ * and must still find the actions in the tab order. Once mounted it stays
+ * mounted, so an open popup survives the pointer leaving the row.
+ */
+ actions?: LazyActions;
active?: boolean;
contextMenuItems?: GenericItemType[] | (() => GenericItemType[]);
/**
@@ -90,8 +101,25 @@ const NavItem = memo<NavItemProps>(
extra,
slots,
style,
+ onFocus,
+ onPointerEnter,
...rest
}) => {
+ const { mount: mountLazyActions, node: renderedActions } = useLazyActions(actions);
+
+ const handlePointerEnter = (e: PointerEvent<HTMLDivElement>) => {
+ mountLazyActions();
+ onPointerEnter?.(e);
+ };
+
+ // Focus, not just the pointer: a keyboard user reaches the row by tabbing,
+ // which never fires `pointerenter`. Without this the actions would be absent
+ // from the tab order entirely rather than merely invisible.
+ const handleFocus = (e: FocusEvent<HTMLDivElement>) => {
+ mountLazyActions();
+ onFocus?.(e);
+ };
+
const iconColor = active ? cssVar.colorText : cssVar.colorTextDescription;
const textColor = titleColor ?? (active ? cssVar.colorText : cssVar.colorTextSecondary);
const variant = active ? 'filled' : 'borderless';
@@ -139,6 +167,8 @@ const NavItem = memo<NavItemProps>(
}}
{...linkProps}
{...rest}
+ onFocus={handleFocus}
+ onPointerEnter={handlePointerEnter}
>
{icon && (
<Center
@@ -202,7 +232,7 @@ const NavItem = memo<NavItemProps>(
e.stopPropagation();
}}
>
- {actions}
+ {renderedActions}
</Flexbox>
)}
</Flexbox>
diff --git a/src/features/NavPanel/components/useLazyActions.test.ts b/src/features/NavPanel/components/useLazyActions.test.ts
new file mode 100644
index 00000000000..467c9fb3cdf
--- /dev/null
+++ b/src/features/NavPanel/components/useLazyActions.test.ts
@@ -0,0 +1,50 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useLazyActions } from './useLazyActions';
+
+describe('useLazyActions', () => {
+ it('passes a plain node straight through', () => {
+ const { result } = renderHook(() => useLazyActions('actions'));
+
+ expect(result.current.node).toBe('actions');
+ });
+
+ it('does not evaluate a thunk before it is mounted', () => {
+ const actions = vi.fn(() => 'actions');
+ const { result } = renderHook(() => useLazyActions(actions));
+
+ expect(result.current.node).toBeNull();
+ expect(actions).not.toHaveBeenCalled();
+ });
+
+ it('evaluates the thunk once mounted', () => {
+ const actions = vi.fn(() => 'actions');
+ const { result } = renderHook(() => useLazyActions(actions));
+
+ act(() => result.current.mount());
+
+ expect(result.current.node).toBe('actions');
+ });
+
+ // The row is reachable by pointer and by keyboard; NavItem calls `mount` from
+ // both `pointerenter` and `focus`, so a keyboard user still finds the actions
+ // in the tab order instead of them being absent entirely.
+ it('stays mounted once mounted, whichever interaction triggered it', () => {
+ const actions = vi.fn(() => 'actions');
+ const { result, rerender } = renderHook(() => useLazyActions(actions));
+
+ act(() => result.current.mount());
+ rerender();
+
+ expect(result.current.node).toBe('actions');
+ });
+
+ it('is a no-op for a plain node', () => {
+ const { result } = renderHook(() => useLazyActions('actions'));
+
+ act(() => result.current.mount());
+
+ expect(result.current.node).toBe('actions');
+ });
+});
diff --git a/src/features/NavPanel/components/useLazyActions.ts b/src/features/NavPanel/components/useLazyActions.ts
new file mode 100644
index 00000000000..e560380d886
--- /dev/null
+++ b/src/features/NavPanel/components/useLazyActions.ts
@@ -0,0 +1,26 @@
+'use client';
+
+import { type ReactNode, useCallback, useState } from 'react';
+
+export type LazyActions = ReactNode | (() => ReactNode);
+
+/**
+ * Defers a row's action slot until the row is first pointed at or focused.
+ *
+ * `mount` is idempotent and one-way: once the actions exist they stay, so an
+ * open dropdown survives the pointer leaving the row. A plain node passes
+ * straight through β€” only the thunk form is deferred.
+ */
+export const useLazyActions = (actions?: LazyActions) => {
+ const isLazy = typeof actions === 'function';
+ const [mounted, setMounted] = useState(false);
+
+ const mount = useCallback(() => {
+ if (isLazy) setMounted(true);
+ }, [isLazy]);
+
+ return {
+ mount,
+ node: isLazy ? (mounted ? actions() : null) : actions,
+ };
+};
diff --git a/src/features/NavPanel/index.test.tsx b/src/features/NavPanel/index.test.tsx
index 9b4ecd792b6..39a9eba6bd5 100644
--- a/src/features/NavPanel/index.test.tsx
+++ b/src/features/NavPanel/index.test.tsx
@@ -43,7 +43,7 @@ vi.mock('@/routes/(main)/settings/_layout/SidebarContent', () => ({
default: () => <div>Personal settings sidebar</div>,
}));
-vi.mock('@/routes/(main)/agent/_layout/Sidebar/Content', () => ({
+vi.mock('@/features/AgentSidebar/Content', () => ({
default: () => <div>Agent sidebar</div>,
}));
diff --git a/src/features/NavPanel/index.tsx b/src/features/NavPanel/index.tsx
index 45f51e02244..1b4fa6d696a 100644
--- a/src/features/NavPanel/index.tsx
+++ b/src/features/NavPanel/index.tsx
@@ -5,11 +5,11 @@ import { memo, useLayoutEffect, useRef, useSyncExternalStore } from 'react';
import { useLocation } from 'react-router';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import AgentSidebarContent from '@/features/AgentSidebar/Content';
import PageSidebarContent from '@/features/Pages/PageLayout/SidebarContent';
import WorkspaceSettingsSideBarContent from '@/features/WorkspaceSetting/SideBar/Content';
import ImageSidebarContent from '@/routes/(main)/(create)/image/_layout/Sidebar/Content';
import VideoSidebarContent from '@/routes/(main)/(create)/video/_layout/Sidebar/Content';
-import AgentSidebarContent from '@/routes/(main)/agent/_layout/Sidebar/Content';
import CommunitySidebarContent from '@/routes/(main)/community/_layout/Sidebar/Content';
import EvalSidebarContent from '@/routes/(main)/eval/_layout/Sidebar/Content';
import GroupSidebarContent from '@/routes/(main)/group/_layout/Sidebar/Content';
diff --git a/src/features/PluginDevModal/imperative.tsx b/src/features/PluginDevModal/imperative.tsx
new file mode 100644
index 00000000000..248e4ea57c3
--- /dev/null
+++ b/src/features/PluginDevModal/imperative.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import isEqual from 'fast-deep-equal';
+import { memo } from 'react';
+
+import { mountImperative } from '@/components/ImperativeMount';
+import { usePermission } from '@/hooks/usePermission';
+import { useToolStore } from '@/store/tool';
+import { pluginSelectors } from '@/store/tool/selectors';
+
+import DevModal from '.';
+
+interface PluginEditDrawerProps {
+ identifier: string;
+ onClose: () => void;
+ open: boolean;
+}
+
+const PluginEditDrawer = memo<PluginEditDrawerProps>(({ identifier, onClose, open }) => {
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const value = useToolStore(pluginSelectors.getCustomPluginById(identifier), isEqual);
+ const [uninstallPlugin, installCustomPlugin, updateNewCustomPlugin] = useToolStore((s) => [
+ s.uninstallCustomPlugin,
+ s.installCustomPlugin,
+ s.updateNewCustomPlugin,
+ ]);
+
+ return (
+ <DevModal
+ mode={'edit'}
+ open={open}
+ value={value}
+ onValueChange={updateNewCustomPlugin}
+ onDelete={() => {
+ if (!canEdit) return;
+ uninstallPlugin(identifier);
+ onClose();
+ }}
+ onOpenChange={(next) => {
+ if (!next) onClose();
+ }}
+ onSave={async (devPlugin) => {
+ if (!canEdit) return;
+ await installCustomPlugin(devPlugin);
+ onClose();
+ }}
+ />
+ );
+});
+
+PluginEditDrawer.displayName = 'PluginEditDrawer';
+
+export const openPluginEditDrawer = (identifier: string) =>
+ mountImperative(({ close, open }) => (
+ <PluginEditDrawer identifier={identifier} open={open} onClose={close} />
+ ));
diff --git a/src/hooks/useFetchChatTopics.ts b/src/hooks/useFetchChatTopics.ts
index 16bad8c2b71..82d9a5ebf3a 100644
--- a/src/hooks/useFetchChatTopics.ts
+++ b/src/hooks/useFetchChatTopics.ts
@@ -1,6 +1,6 @@
import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';
+import { useAgentTopicGroupMode } from '@/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode';
import { useFetchTopics } from '@/hooks/useFetchTopics';
-import { useAgentTopicGroupMode } from '@/routes/(main)/agent/_layout/Sidebar/Topic/hooks/useAgentTopicGroupMode';
import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsx
index d60d5e75193..aaafea585ce 100644
--- a/src/layout/SPAGlobalProvider/index.tsx
+++ b/src/layout/SPAGlobalProvider/index.tsx
@@ -32,6 +32,7 @@ const ContextMenuHost = lazy(() =>
import('@lobehub/ui').then((m) => ({ default: m.ContextMenuHost })),
);
const DevDock = lazy(() => import('@/features/DevDock'));
+const ImperativeMountHost = lazy(() => import('@/components/ImperativeMount'));
const devDockLayoutStyle: CSSProperties = {
alignItems: 'center',
@@ -73,6 +74,7 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
<BaseModalHost />
<ToastHost />
<ContextMenuHost />
+ <ImperativeMountHost />
</Suspense>
</LazyMotion>
</DragUploadProvider>
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/Editing.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/Editing.tsx
deleted file mode 100644
index d76ce3e5688..00000000000
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/Editing.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { memo, useCallback } from 'react';
-
-import InlineRename from '@/components/InlineRename';
-import { useChatStore } from '@/store/chat';
-
-interface EditingProps {
- id: string;
- title: string;
- toggleEditing: (visible?: boolean) => void;
-}
-
-const Editing = memo<EditingProps>(({ id, title, toggleEditing }) => {
- const [editing, updateTopicTitle] = useChatStore((s) => [
- s.topicRenamingId === id,
- s.updateTopicTitle,
- ]);
-
- const handleSave = useCallback(
- async (newTitle: string) => {
- await updateTopicTitle(id, newTitle);
- },
- [id, updateTopicTitle],
- );
-
- return (
- <InlineRename
- open={editing}
- title={title}
- onOpenChange={(open) => toggleEditing(open)}
- onSave={handleSave}
- />
- );
-});
-
-export default Editing;
diff --git a/src/routes/(main)/agent/_layout/index.test.tsx b/src/routes/(main)/agent/_layout/index.test.tsx
index dd8db519791..7b42c4a0dcc 100644
--- a/src/routes/(main)/agent/_layout/index.test.tsx
+++ b/src/routes/(main)/agent/_layout/index.test.tsx
@@ -28,7 +28,9 @@ vi.mock('@/const/version', () => ({ isDesktop: false }));
vi.mock('@/hooks/useInitAgentConfig', () => ({ useInitAgentConfig: vi.fn() }));
vi.mock('@/features/ProtocolUrlHandler', () => ({ default: () => null }));
vi.mock('./RegisterHotkeys', () => ({ default: () => null }));
-vi.mock('./Sidebar', () => ({ default: () => <div data-testid="agent-layout-sidebar" /> }));
+vi.mock('@/features/AgentSidebar', () => ({
+ default: () => <div data-testid="agent-layout-sidebar" />,
+}));
vi.mock('@/routes/(main)/agent/_layout/AgentIdSync', () => ({
default: () => <div data-testid="agent-layout-agent-id-sync" />,
}));
diff --git a/src/routes/(main)/agent/_layout/index.tsx b/src/routes/(main)/agent/_layout/index.tsx
index ca4d98a609d..d3627c15ff5 100644
--- a/src/routes/(main)/agent/_layout/index.tsx
+++ b/src/routes/(main)/agent/_layout/index.tsx
@@ -4,13 +4,13 @@ import { Outlet } from 'react-router';
import { isDesktop } from '@/const/version';
import { AgentNotFoundGuard } from '@/features/AgentNotFound';
+import AgentSidebar from '@/features/AgentSidebar';
import ProtocolUrlHandler from '@/features/ProtocolUrlHandler';
import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
import AgentIdSync from '@/routes/(main)/agent/_layout/AgentIdSync';
import PortalAutoCollapse from './PortalAutoCollapse';
import RegisterHotkeys from './RegisterHotkeys';
-import Sidebar from './Sidebar';
import { styles } from './style';
const Layout: FC = () => {
@@ -18,7 +18,7 @@ const Layout: FC = () => {
return (
<>
- <Sidebar />
+ <AgentSidebar />
<Flexbox className={styles.mainContainer} flex={1} height={'100%'}>
{/* Keep the sidebar interactive when the routed agent is gone (deleted
or made private) β€” only the content area collapses to the 404 card. */}
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
index 957062df355..cfc9ecd69a0 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
@@ -111,9 +111,9 @@ describe('Conversation header action menu', () => {
const { result } = renderHook(() => useMenu());
- const popupItem = result.current.menuItems.find(
- (item) => isActionItem(item) && item.key === 'openInPopupWindow',
- );
+ const popupItem = result.current
+ .menuItems()
+ .find((item) => isActionItem(item) && item.key === 'openInPopupWindow');
expect(popupItem).toBeDefined();
if (!isActionItem(popupItem)) {
@@ -133,9 +133,9 @@ describe('Conversation header action menu', () => {
const { result } = renderHook(() => useMenu());
- const popupItem = result.current.menuItems.find(
- (item) => isActionItem(item) && item.key === 'openInPopupWindow',
- );
+ const popupItem = result.current
+ .menuItems()
+ .find((item) => isActionItem(item) && item.key === 'openInPopupWindow');
expect(popupItem).toBeUndefined();
});
@@ -145,9 +145,9 @@ describe('Conversation header action menu', () => {
const { result } = renderHook(() => useMenu());
- const topicInfoItem = result.current.menuItems.find(
- (item) => isActionItem(item) && item.key === 'topic-info',
- );
+ const topicInfoItem = result.current
+ .menuItems()
+ .find((item) => isActionItem(item) && item.key === 'topic-info');
expect(topicInfoItem).toBeUndefined();
expect(result.current.menuHeader).toBeDefined();
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
index 959352b223c..8b2adcb6ef3 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.tsx
@@ -65,7 +65,7 @@ const TopicInfoHeader = ({ authorName, title, updatedAtLabel }: TopicInfoHeaderP
</Block>
);
-export const useMenu = (): { menuHeader?: ReactNode; menuItems: DropdownItem[] } => {
+export const useMenu = (): { menuHeader?: ReactNode; menuItems: () => DropdownItem[] } => {
const { t } = useTranslation(['chat', 'topic', 'common', 'file']);
const { message } = App.useApp();
const { pathname } = useLocation();
@@ -209,7 +209,7 @@ export const useMenu = (): { menuHeader?: ReactNode; menuItems: DropdownItem[] }
);
}, [activeTopic?.updatedAt, authorInfo?.fullName, topicId, t]);
- const menuItems = useMemo<DropdownItem[]>(() => {
+ const menuItems = useCallback((): DropdownItem[] => {
const items: DropdownItem[] = [];
if (topicId) {
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
index 31f183db1f7..8cf9a5e4ea6 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
@@ -285,12 +285,13 @@ vi.mock('@lobehub/ui/base-ui', async () => {
onOpenChangeComplete,
}: {
children: ReactNode;
- items: any[];
+ items: any[] | (() => any[]);
onOpenChangeComplete?: (open: boolean) => void;
}) => {
const [open, setOpen] = useState(false);
- const menuItems = items.flatMap((item) => item.children ?? []);
- dropdownMenuState.items = items;
+ const resolvedItems = typeof items === 'function' ? items() : items;
+ const menuItems = resolvedItems.flatMap((item) => item.children ?? []);
+ dropdownMenuState.items = resolvedItems;
dropdownMenuState.onOpenChangeComplete = onOpenChangeComplete;
return (
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
index bf5a6973547..d5713490243 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
@@ -637,7 +637,7 @@ const AgentWorkingSidebar = memo(() => {
);
const reviewTwoPane = activeTab === 'review' && reviewAvailable && showReviewTree;
const displayWidth = reviewTwoPane ? Math.max(storedWidth, TWO_PANE_MIN_WIDTH) : storedWidth;
- const openMenuItems = useMemo<DropdownItem[]>(() => {
+ const openMenuItems = useCallback((): DropdownItem[] => {
const itemOf = (key: string): DropdownItem | undefined => {
const tab = availableTabs.get(key);
if (!tab) return undefined;
diff --git a/src/routes/(mobile)/chat/features/Topic/index.tsx b/src/routes/(mobile)/chat/features/Topic/index.tsx
index 8f04ce397a6..c6408e82423 100644
--- a/src/routes/(mobile)/chat/features/Topic/index.tsx
+++ b/src/routes/(mobile)/chat/features/Topic/index.tsx
@@ -1,7 +1,7 @@
import { Flexbox } from '@lobehub/ui';
-import TopicListContent from '@/routes/(main)/agent/_layout/Sidebar/Topic/TopicListContent';
-import TopicSearchBar from '@/routes/(main)/agent/_layout/Sidebar/Topic/TopicSearchBar';
+import TopicListContent from '@/features/AgentSidebar/Topic/TopicListContent';
+import TopicSearchBar from '@/features/AgentSidebar/Topic/TopicSearchBar';
import TopicModal from './features/TopicModal';