Skip to content

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

🐛 fix(chat-input): stop the skill detail card from blocking the uninstall menu (#18387)

Inneiae3dee1c1629
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index b16308adb71..34e3183ddc2 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -258,6 +258,15 @@ gateway/device route, then assert the complete persisted tree: original owner
user, target assistant/tool call, tool result, and target final response. Also
assert there is no owner assistant, `callAgent`, or synthetic target-user row.
+### L-E18 — 从「没有默认导入」推断某个 composer 表面是死代码
+
+**Wrong approach:** 改动技能行这类被 ActionBar 复用的组件后,grep `ActionBar/Tools` 的默认导入没有命中,就断定该表面未挂载,只验证 `+` 菜单一条路径。
+
+**Why it fails:** ActionBar 的表面不是靠直接 import 挂载的,而是靠 action key 注册表 + 各路由自己的 `leftActions` 数组启用。`ActionBar/config` 里 `tools: Tools` 一直注册着,真正决定它是否渲染的是
+`src/routes/(main)/**/MainChatInput` 里的 `leftActions`—— 群聊 composer 就启用了 `'tools'`,走的是 `PopoverContent → ToolsList` 这条与 `+` 菜单不同的组合路径。漏掉它会让一次绿色的验证只覆盖一半用户可见面。
+
+**Correct approach:** 改动任何被 ActionBar 复用的组件后,先枚举 action key 的真实启用点(grep 各路由的 `leftActions` 数组,而不是组件的 import),对每个启用该 key 的表面分别取证;确实不打算验的表面要显式标记未测。
+
## Product and interaction contracts
### L-D1 — Rebuilding a canonical surface from visual impression
@@ -516,6 +525,14 @@ server's port with `test-env.sh`'s resolved `PORT`; on a mismatch, `stop-dev` an
restart before diagnosing anything. The restarted server is then yours to stop at
teardown even though you did not start the original.
+**Same failure, third shape — files removed from the working tree still being served.**
+After a `git stash` used to capture a "before" frame, the dev server can keep serving the
+pre-stash transform: a file deleted from disk still answers **200** and the module body still
+contains the new code. Reloading the page does not help. Restart the process (and clear
+`node_modules/.vite`) before capturing, and gate the capture on a marker that cannot collide
+with unrelated identifiers — a component name like `SkillRow` also matches a CSS class such as
+`addSkillRow`, so a substring count "confirms" the wrong state.
+
---
### L-S8 — Reading a first-boot renderer crash as a defect of the change under test
@@ -573,6 +590,30 @@ directly — strip `--> statement-breakpoint` and run it with `psql -v ON_ERROR_
— and treat the collision as a local multi-worktree artifact, never as a defect of
the branch or of canary (the numbers get rebased on merge).
+### L-S10 — Judging popover/menu behaviour from a Chrome MCP tab (it is hidden)
+
+**Wrong approach:** drive the debug-proxy page through the Chrome MCP tools, click a
+popover trigger, read the DOM \~500ms later, see no popup, and conclude the trigger is
+broken — then bisect, revert a refactor, and write up a root cause from those readings.
+
+**Why it fails:** the MCP tab is not the foreground tab. Measured inside it:
+`document.visibilityState === 'hidden'`, `requestAnimationFrame` delivers **0 frames**,
+and `setInterval(16ms)` fires **once per second** (Chrome's background throttling). A
+base-ui popup still opens in its store and mounts in the DOM, but its entry transition
+never advances, so it sits at `data-starting-style` with `visibility: hidden` and zero
+size — indistinguishable from "the click did nothing". Anything else timed from that
+tab (perceived latency, "it landed 7 seconds later") is an artifact of the same
+throttling, not of the code under test.
+
+**Correct approach:** in an MCP tab, assert on **state**, not on visibility — the
+component's own store/props (`handle.store.state.open`, a probed React state), or DOM
+presence with `data-open`, never `visibility`/painted pixels or a rAF-timed measurement.
+Confirm the tab's own health first (`visibilityState`, a rAF frame count) before
+trusting any negative UI observation, and get behaviour that depends on animation or
+input timing confirmed in a foreground tab — the user's window, or a screenshot-based
+check that tolerates a frozen transition. A negative result from a hidden tab is not
+evidence of a defect.
+
## Historical source
Detailed incident narratives and retired pixel- or component-specific directions
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 8f0c4fef028..e611af96c5f 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -1327,6 +1327,25 @@ ports-file 无关。端口对上后若见 401,是快照 cookie 对本地库已
`http://localhost:<端口>/`)写进 Electron 的 cookie store,`location.reload()` 后
server-auth 200、`isUserStateInit` true。
+### 技能菜单交互 bug 依赖用户数据形态 — 前台化 MCP 窗口 + 零写入点击在生产环境复现
+
+**Situation:** 复现「+」菜单 / 技能子菜单里的行级交互缺陷 (hover 详情卡、「...」策略菜单、
+卸载确认)。本地 seeded 全栈环境跑遍手势矩阵 (连续策略切换、popover 切换、禁用、卸载弹窗、
+注入 700ms 服务端延迟) 全部存活,而用户环境一触即发。
+
+**Doesn't work:** 在本地环境穷举手势排列。触发缺陷的行形态只存在于真实账号数据 —— 例如
+过期授权的 Composio 行 (Gmail 重新授权) 走的是与 SkillRow 不同的 `PopoverLabel` 渲染路径;
+本地 seeded 账号只有 builtin 行,detail card 甚至从不挂载。也不要在后台 MCP 标签页下结论
+(L-S10):popover 冻结在 data-starting-style、坐标点击失效、计时器被钳到 1s。
+
+**Works:** 三件套。① 让用户把扩展新建的 Chrome 窗口切到前台,`document.visibilityState === 'visible'` 且 DevDock 显示 60 FPS 后再驱动 —— 前台化后的 MCP 标签页是完全可信的交互
+表面;② 生产账号上的零写入复现:策略菜单只点击**当前已勾选项**(`updateSkillPolicy` 对
+currentMode === mode 提前返回,不发请求), 确认弹窗一律 Cancel, 菜单开合本身无写入;
+③ 机制归因用页面内事件取证 (document 捕获层记录 pointer/focus 事件的目标画像:closest
+role、inDialog、isConnected, 写入 `window.__AGENT_LOGS` 环形缓冲), 关闭原因用
+`onOpenChange(details.reason)` 直接记录 —— 单靠截图无法区分 outside-press /focus-out/
+hover-out。
+
### 服务端读取本地 S3 证据会被 SSRF 拦下 — 需显式放行私有 IP
**Situation:** 验证任何「服务端把已上传的证据 / 文件再读回来」的能力时(多模态判图、
diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsx
index 48a2eafe655..7200b57f3d4 100644
--- a/src/features/ChatInput/ActionBar/Plus/index.tsx
+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx
@@ -23,7 +23,7 @@ import {
TypeIcon,
} from 'lucide-react';
import type { ReactNode } from 'react';
-import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { memo, Suspense, useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { openAttachKnowledgeModal } from '@/features/LibraryModal';
@@ -52,6 +52,7 @@ import { insertGoalTag } from '../../InputEditor/ActionTag/goalTag';
import { useChatInputStore } from '../../store';
import { type ActionDropdownMenuItems } from '../components/ActionDropdown';
import { ChatInputAction } from '../components/ChatInputAction';
+import { useDetailPopoverState } from '../components/useDetailPopoverState';
import { useControls as useKnowledgeControls } from '../Knowledge/useControls';
import { useMemoryEnabled } from '../Memory/useMemoryEnabled';
import { useControls as useToolsControls } from '../Tools/useControls';
@@ -200,52 +201,51 @@ type DropdownItemWithPopover = NonNullable<ActionDropdownMenuItems>[number] & {
popoverContent?: unknown;
};
-const CLOSE_TOOL_DETAIL_POPOVER_EVENT = 'lobe-chat-tool-detail-popover-close';
-
interface PopoverLabelProps {
+ disabled?: boolean;
label: ReactNode;
popoverContent: ReactNode;
- // Distance from the label cell's right edge. Switch-type rows reserve a
- // trailing toggle, so bump this to push the popover clear of the toggle and
- // out to the right of the whole menu instead of overlapping it.
- sideOffset?: number;
}
-const PopoverLabel = memo<PopoverLabelProps>(({ label, popoverContent, sideOffset = 10 }) => {
- const [open, setOpen] = useState(false);
- const suppressUntilRef = useRef(0);
-
- useEffect(() => {
- const close = () => {
- suppressUntilRef.current = Date.now() + 600;
- setOpen(false);
- };
- window.addEventListener(CLOSE_TOOL_DETAIL_POPOVER_EVENT, close);
-
- return () => window.removeEventListener(CLOSE_TOOL_DETAIL_POPOVER_EVENT, close);
- }, []);
-
- const handleOpenChange = useCallback((nextOpen: boolean) => {
- if (nextOpen && Date.now() < suppressUntilRef.current) return;
-
- setOpen(nextOpen);
- }, []);
+/**
+ * The detail card must anchor past the whole menu row, not the label cell:
+ * anchored to the label, it opens exactly over the item's trailing `extra`
+ * slot ("..." menu, re-authorize link, switches), and a press landing on the
+ * portal'd card is read by base-ui as an outside press that dismisses the
+ * whole submenu. The card is also rendered inert (pointer-events: none) — it
+ * is a hover information surface, so it must never swallow a press meant for
+ * the controls beneath it.
+ */
+const PopoverLabel = memo<PopoverLabelProps>(({ disabled, label, popoverContent }) => {
+ const { close, onOpenChange, open } = useDetailPopoverState(disabled);
+ const wrapperRef = useRef<HTMLSpanElement>(null);
+ const rowAnchorRef = useMemo(
+ () => ({
+ get current() {
+ const wrapper = wrapperRef.current;
+ return (wrapper?.closest('[role="menuitem"]') as HTMLElement | null) ?? wrapper;
+ },
+ }),
+ [],
+ );
return (
<Popover
arrow={false}
content={popoverContent}
+ disabled={disabled}
mouseEnterDelay={0.25}
open={open}
placement={'rightTop'}
- positionerProps={{ sideOffset }}
- styles={{ content: { padding: 0 } }}
- onOpenChange={handleOpenChange}
+ positionerProps={{ anchor: rowAnchorRef, sideOffset: 8 }}
+ styles={{ content: { padding: 0 }, root: { pointerEvents: 'none' } }}
+ onOpenChange={onOpenChange}
>
<span
+ ref={wrapperRef}
style={{ display: 'block', width: '100%' }}
- onClickCapture={() => setOpen(false)}
- onContextMenuCapture={() => setOpen(false)}
+ onClickCapture={close}
+ onContextMenuCapture={close}
>
{label}
</span>
@@ -255,13 +255,18 @@ const PopoverLabel = memo<PopoverLabelProps>(({ label, popoverContent, sideOffse
PopoverLabel.displayName = 'PopoverLabel';
-const wrapPopoverLabel = (label: ReactNode, popoverContent?: unknown) => {
+const wrapPopoverLabel = (label: ReactNode, popoverContent?: unknown, disabled?: boolean) => {
if (!popoverContent) return label;
- return <PopoverLabel label={label} popoverContent={popoverContent as ReactNode} />;
+ return (
+ <PopoverLabel disabled={disabled} label={label} popoverContent={popoverContent as ReactNode} />
+ );
};
-const stripPopoverContent = (items?: ActionDropdownMenuItems): ActionDropdownMenuItems =>
+const stripPopoverContent = (
+ items?: ActionDropdownMenuItems,
+ detailPopoverDisabled?: boolean,
+): ActionDropdownMenuItems =>
items?.map((item) => {
if (!item) return item;
if ('type' in item && item.type === 'divider') return item;
@@ -273,12 +278,12 @@ const stripPopoverContent = (items?: ActionDropdownMenuItems): ActionDropdownMen
if ('children' in nextItem && nextItem.children) {
return {
...nextItem,
- children: stripPopoverContent(nextItem.children),
+ children: stripPopoverContent(nextItem.children, detailPopoverDisabled),
} as ActionDropdownMenuItems[number];
}
if ('label' in nextItem) {
- nextItem.label = wrapPopoverLabel(nextItem.label, popoverContent);
+ nextItem.label = wrapPopoverLabel(nextItem.label, popoverContent, detailPopoverDisabled);
}
return nextItem;
@@ -344,6 +349,7 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
const closeDropdown = useCallback(() => close(), [close]);
const {
autoCount: skillAutoCount,
+ isPolicyMenuOpen: isSkillPolicyMenuOpen,
marketFooter: skillMarketFooter,
marketHeader: skillMarketHeader,
marketItems: skillItems,
@@ -468,7 +474,13 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
</div>
);
- const skillMenuItems = stripPopoverContent(skillItems as ActionDropdownMenuItems);
+ // The row detail card and the "..." policy menu anchor to the same right edge,
+ // so leaving hover live lets a neighbouring row's card open on top of the menu
+ // and swallow the click meant for it.
+ const skillMenuItems = stripPopoverContent(
+ skillItems as ActionDropdownMenuItems,
+ isSkillPolicyMenuOpen,
+ );
const uploadItems: ActionDropdownMenuItems = [
{
@@ -546,12 +558,7 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
icon: Cloud,
key: 'gateway-mode',
label: (
- <PopoverLabel
- label={renderGatewayModeLabel()}
- popoverContent={gatewayModeInfo}
- // Clear the trailing toggle so the card sits to the right of the whole menu.
- sideOffset={64}
- />
+ <PopoverLabel label={renderGatewayModeLabel()} popoverContent={gatewayModeInfo} />
),
onCheckedChange: handleToggleGatewayMode,
type: 'switch',
@@ -757,6 +764,7 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
isGatewayModeEnabled,
isMemoryEnabled,
isParamsPanelActive,
+ isSkillPolicyMenuOpen,
knowledgeEnabledCount,
setShowTypoBar,
showProviderSearch,
diff --git a/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx b/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx
index 3015e5b6f54..104b86c78c5 100644
--- a/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/ComposioServerItem.tsx
@@ -1,6 +1,7 @@
import { Flexbox, Icon, stopPropagation } from '@lobehub/ui';
import { Checkbox } from '@lobehub/ui/base-ui';
import { Loader2, SquareArrowOutUpRight } from 'lucide-react';
+import type { ReactNode } from 'react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -13,6 +14,8 @@ import { ComposioServerStatus } from '@/store/tool/slices/composioStore';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
+import { SKILL_ICON_GAP } from './constants';
+
// Polling configuration
const POLL_INTERVAL_MS = 1000; // Poll once per second
const POLL_TIMEOUT_MS = 15_000; // 15-second timeout
@@ -36,13 +39,19 @@ interface ComposioServerItemProps {
* Composio toolkit slug used to call the Composio API (e.g., 'GOOGLECALENDAR')
*/
appSlug: string;
+ /**
+ * Rendered inside the label so the row lines up with the managed skill rows;
+ * passing it through the menu's own icon slot would size and space it
+ * differently.
+ */
+ icon?: ReactNode;
identifier: string;
label: string;
server?: ComposioServer;
}
const ComposioServerItem = memo<ComposioServerItemProps>(
- ({ appSlug, identifier, label, server, agentId, agentScoped = false }) => {
+ ({ appSlug, icon, identifier, label, server, agentId, agentScoped = false }) => {
const { t } = useTranslation('setting');
const [isConnecting, setIsConnecting] = useState(false);
const [isToggling, setIsToggling] = useState(false);
@@ -364,7 +373,8 @@ const ComposioServerItem = memo<ComposioServerItemProps>(
}
}}
>
- <Flexbox horizontal align={'center'} gap={8}>
+ <Flexbox horizontal align={'center'} gap={SKILL_ICON_GAP}>
+ {icon}
{label}
</Flexbox>
{renderRightControl()}
diff --git a/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx b/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx
index 701e8479aa4..9fc778c4050 100644
--- a/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/LobehubSkillServerItem.tsx
@@ -1,6 +1,7 @@
import { Flexbox, Icon, stopPropagation } from '@lobehub/ui';
import { Checkbox } from '@lobehub/ui/base-ui';
import { Loader2, SquareArrowOutUpRight } from 'lucide-react';
+import type { ReactNode } from 'react';
import { memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,6 +12,8 @@ import { useToolStore } from '@/store/tool';
import { lobehubSkillStoreSelectors } from '@/store/tool/selectors';
import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';
+import { SKILL_ICON_GAP } from './constants';
+
const POLL_INTERVAL_MS = 1000;
const POLL_TIMEOUT_MS = 15_000;
@@ -20,6 +23,12 @@ interface LobehubSkillServerItemProps {
* Used in group profile to specify which member's plugins to toggle
*/
agentId?: string;
+ /**
+ * Rendered inside the label so the row lines up with the managed skill rows;
+ * passing it through the menu's own icon slot would size and space it
+ * differently.
+ */
+ icon?: ReactNode;
/**
* Display label for the provider
*/
@@ -30,281 +39,219 @@ interface LobehubSkillServerItemProps {
provider: string;
}
-const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(({ provider, label, agentId }) => {
- const { t } = useTranslation('setting');
- const [isConnecting, setIsConnecting] = useState(false);
- const [isToggling, setIsToggling] = useState(false);
- const [isWaitingAuth, setIsWaitingAuth] = useState(false);
- const { allowed: canCreate } = usePermission('create_content');
- const { allowed: canEdit } = usePermission('edit_own_content');
-
- const oauthWindowRef = useRef<Window | null>(null);
- const windowCheckIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
- const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
- const pollTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
-
- const server = useToolStore(lobehubSkillStoreSelectors.getServerByIdentifier(provider));
- const checkStatus = useToolStore((s) => s.checkLobehubSkillStatus);
- const getAuthorizeUrl = useToolStore((s) => s.getLobehubSkillAuthorizeUrl);
-
- // Get effective agent ID (agentId prop or current active agent)
- const activeAgentId = useAgentStore((s) => s.activeAgentId);
- const effectiveAgentId = agentId || activeAgentId || '';
-
- const cleanup = useCallback(() => {
- if (windowCheckIntervalRef.current) {
- clearInterval(windowCheckIntervalRef.current);
- windowCheckIntervalRef.current = null;
- }
- if (pollIntervalRef.current) {
- clearInterval(pollIntervalRef.current);
- pollIntervalRef.current = null;
- }
- if (pollTimeoutRef.current) {
- clearTimeout(pollTimeoutRef.current);
- pollTimeoutRef.current = null;
- }
- oauthWindowRef.current = null;
- setIsWaitingAuth(false);
- }, []);
-
- useEffect(() => {
- return () => {
- cleanup();
- };
- }, [cleanup]);
-
- useEffect(() => {
- if (server?.status === LobehubSkillStatus.CONNECTED && isWaitingAuth) {
- cleanup();
- }
- }, [server?.status, isWaitingAuth, cleanup]);
-
- const startFallbackPolling = useCallback(() => {
- if (pollIntervalRef.current) return;
-
- pollIntervalRef.current = setInterval(async () => {
- try {
- await checkStatus(provider);
- } catch (error) {
- console.error('[LobehubSkill] Failed to check status:', error);
+const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(
+ ({ provider, icon, label, agentId }) => {
+ const { t } = useTranslation('setting');
+ const [isConnecting, setIsConnecting] = useState(false);
+ const [isToggling, setIsToggling] = useState(false);
+ const [isWaitingAuth, setIsWaitingAuth] = useState(false);
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
+
+ const oauthWindowRef = useRef<Window | null>(null);
+ const windowCheckIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
+ const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
+ const pollTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const server = useToolStore(lobehubSkillStoreSelectors.getServerByIdentifier(provider));
+ const checkStatus = useToolStore((s) => s.checkLobehubSkillStatus);
+ const getAuthorizeUrl = useToolStore((s) => s.getLobehubSkillAuthorizeUrl);
+
+ // Get effective agent ID (agentId prop or current active agent)
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const effectiveAgentId = agentId || activeAgentId || '';
+
+ const cleanup = useCallback(() => {
+ if (windowCheckIntervalRef.current) {
+ clearInterval(windowCheckIntervalRef.current);
+ windowCheckIntervalRef.current = null;
}
- }, POLL_INTERVAL_MS);
-
- pollTimeoutRef.current = setTimeout(() => {
if (pollIntervalRef.current) {
clearInterval(pollIntervalRef.current);
pollIntervalRef.current = null;
}
+ if (pollTimeoutRef.current) {
+ clearTimeout(pollTimeoutRef.current);
+ pollTimeoutRef.current = null;
+ }
+ oauthWindowRef.current = null;
setIsWaitingAuth(false);
- }, POLL_TIMEOUT_MS);
- }, [checkStatus, provider]);
+ }, []);
- const startWindowMonitor = useCallback(
- (oauthWindow: Window) => {
- windowCheckIntervalRef.current = setInterval(() => {
+ useEffect(() => {
+ return () => {
+ cleanup();
+ };
+ }, [cleanup]);
+
+ useEffect(() => {
+ if (server?.status === LobehubSkillStatus.CONNECTED && isWaitingAuth) {
+ cleanup();
+ }
+ }, [server?.status, isWaitingAuth, cleanup]);
+
+ const startFallbackPolling = useCallback(() => {
+ if (pollIntervalRef.current) return;
+
+ pollIntervalRef.current = setInterval(async () => {
try {
- if (oauthWindow.closed) {
+ await checkStatus(provider);
+ } catch (error) {
+ console.error('[LobehubSkill] Failed to check status:', error);
+ }
+ }, POLL_INTERVAL_MS);
+
+ pollTimeoutRef.current = setTimeout(() => {
+ if (pollIntervalRef.current) {
+ clearInterval(pollIntervalRef.current);
+ pollIntervalRef.current = null;
+ }
+ setIsWaitingAuth(false);
+ }, POLL_TIMEOUT_MS);
+ }, [checkStatus, provider]);
+
+ const startWindowMonitor = useCallback(
+ (oauthWindow: Window) => {
+ windowCheckIntervalRef.current = setInterval(() => {
+ try {
+ if (oauthWindow.closed) {
+ if (windowCheckIntervalRef.current) {
+ clearInterval(windowCheckIntervalRef.current);
+ windowCheckIntervalRef.current = null;
+ }
+ oauthWindowRef.current = null;
+ checkStatus(provider);
+ }
+ } catch {
+ console.info(
+ '[LobehubSkill] COOP blocked window.closed access, falling back to polling',
+ );
if (windowCheckIntervalRef.current) {
clearInterval(windowCheckIntervalRef.current);
windowCheckIntervalRef.current = null;
}
- oauthWindowRef.current = null;
- checkStatus(provider);
+ startFallbackPolling();
}
- } catch {
- console.info('[LobehubSkill] COOP blocked window.closed access, falling back to polling');
- if (windowCheckIntervalRef.current) {
- clearInterval(windowCheckIntervalRef.current);
- windowCheckIntervalRef.current = null;
- }
- startFallbackPolling();
- }
- }, 500);
- },
- [checkStatus, provider, startFallbackPolling],
- );
-
- const openOAuthWindow = useCallback(
- (authorizeUrl: string) => {
- cleanup();
- setIsWaitingAuth(true);
-
- const oauthWindow = window.open(authorizeUrl, '_blank', 'width=600,height=700');
- if (oauthWindow) {
- oauthWindowRef.current = oauthWindow;
- startWindowMonitor(oauthWindow);
- } else {
- startFallbackPolling();
- }
- },
- [cleanup, startWindowMonitor, startFallbackPolling],
- );
-
- const pluginId = server ? server.identifier : '';
- const plugins = useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId))?.plugins || [];
- const checked = plugins.includes(pluginId);
- const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
-
- // Toggle plugin for the effective agent
- const togglePlugin = useCallback(
- async (pluginIdToToggle: string) => {
- if (!effectiveAgentId) return;
- const currentPlugins = plugins;
- const hasPlugin = currentPlugins.includes(pluginIdToToggle);
- const newPlugins = hasPlugin
- ? currentPlugins.filter((id) => id !== pluginIdToToggle)
- : [...currentPlugins, pluginIdToToggle];
- await updateAgentConfigById(effectiveAgentId, { plugins: newPlugins });
- },
- [effectiveAgentId, plugins, updateAgentConfigById],
- );
-
- // Listen for OAuth success message from popup window
- useEffect(() => {
- const handleMessage = async (event: MessageEvent) => {
- // Verify origin for security
- if (event.origin !== window.location.origin) return;
-
- if (event.data?.type === 'LOBEHUB_SKILL_AUTH_SUCCESS' && event.data?.provider === provider) {
- console.info('[LobehubSkill] OAuth success message received for provider:', provider);
-
- // Cleanup polling/window monitoring
+ }, 500);
+ },
+ [checkStatus, provider, startFallbackPolling],
+ );
+
+ const openOAuthWindow = useCallback(
+ (authorizeUrl: string) => {
cleanup();
+ setIsWaitingAuth(true);
- // Refresh status to get the connected state
- await checkStatus(provider);
-
- // Auto-enable the plugin after successful OAuth
- // Need to get the latest server state after checkStatus
- const latestServer = useToolStore
- .getState()
- .lobehubSkillServers?.find((s) => s.identifier === provider);
- if (latestServer?.status === LobehubSkillStatus.CONNECTED) {
- const newPluginId = latestServer.identifier;
- const currentAgentPlugins =
- agentSelectors.getAgentConfigById(effectiveAgentId)(useAgentStore.getState())
- ?.plugins || [];
- const isAlreadyEnabled = currentAgentPlugins.includes(newPluginId);
- if (canEdit && !isAlreadyEnabled) {
- console.info('[LobehubSkill] Auto-enabling plugin:', newPluginId);
- togglePlugin(newPluginId);
+ const oauthWindow = window.open(authorizeUrl, '_blank', 'width=600,height=700');
+ if (oauthWindow) {
+ oauthWindowRef.current = oauthWindow;
+ startWindowMonitor(oauthWindow);
+ } else {
+ startFallbackPolling();
+ }
+ },
+ [cleanup, startWindowMonitor, startFallbackPolling],
+ );
+
+ const pluginId = server ? server.identifier : '';
+ const plugins =
+ useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId))?.plugins || [];
+ const checked = plugins.includes(pluginId);
+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
+
+ // Toggle plugin for the effective agent
+ const togglePlugin = useCallback(
+ async (pluginIdToToggle: string) => {
+ if (!effectiveAgentId) return;
+ const currentPlugins = plugins;
+ const hasPlugin = currentPlugins.includes(pluginIdToToggle);
+ const newPlugins = hasPlugin
+ ? currentPlugins.filter((id) => id !== pluginIdToToggle)
+ : [...currentPlugins, pluginIdToToggle];
+ await updateAgentConfigById(effectiveAgentId, { plugins: newPlugins });
+ },
+ [effectiveAgentId, plugins, updateAgentConfigById],
+ );
+
+ // Listen for OAuth success message from popup window
+ useEffect(() => {
+ const handleMessage = async (event: MessageEvent) => {
+ // Verify origin for security
+ if (event.origin !== window.location.origin) return;
+
+ if (
+ event.data?.type === 'LOBEHUB_SKILL_AUTH_SUCCESS' &&
+ event.data?.provider === provider
+ ) {
+ console.info('[LobehubSkill] OAuth success message received for provider:', provider);
+
+ // Cleanup polling/window monitoring
+ cleanup();
+
+ // Refresh status to get the connected state
+ await checkStatus(provider);
+
+ // Auto-enable the plugin after successful OAuth
+ // Need to get the latest server state after checkStatus
+ const latestServer = useToolStore
+ .getState()
+ .lobehubSkillServers?.find((s) => s.identifier === provider);
+ if (latestServer?.status === LobehubSkillStatus.CONNECTED) {
+ const newPluginId = latestServer.identifier;
+ const currentAgentPlugins =
+ agentSelectors.getAgentConfigById(effectiveAgentId)(useAgentStore.getState())
+ ?.plugins || [];
+ const isAlreadyEnabled = currentAgentPlugins.includes(newPluginId);
+ if (canEdit && !isAlreadyEnabled) {
+ console.info('[LobehubSkill] Auto-enabling plugin:', newPluginId);
+ togglePlugin(newPluginId);
+ }
}
}
+ };
+
+ window.addEventListener('message', handleMessage);
+ return () => window.removeEventListener('message', handleMessage);
+ }, [canEdit, provider, cleanup, checkStatus, togglePlugin, effectiveAgentId]);
+
+ const handleConnect = async () => {
+ if (!canCreate || !canEdit) return;
+ // Only block reconnection when already connected
+ if (server?.isConnected) return;
+
+ setIsConnecting(true);
+ try {
+ // Use /oauth/callback/success as redirect URI with provider param for auto-enable
+ // Skip redirectUri on desktop (app:// protocol) since the system browser can't navigate to it
+ const redirectUri = window.location.protocol.startsWith('http')
+ ? `${window.location.origin}/oauth/callback/success?provider=${encodeURIComponent(provider)}`
+ : undefined;
+ const { authorizeUrl } = await getAuthorizeUrl(provider, { redirectUri });
+ openOAuthWindow(authorizeUrl);
+ } catch (error) {
+ console.error('[LobehubSkill] Failed to get authorize URL:', error);
+ } finally {
+ setIsConnecting(false);
}
};
- window.addEventListener('message', handleMessage);
- return () => window.removeEventListener('message', handleMessage);
- }, [canEdit, provider, cleanup, checkStatus, togglePlugin, effectiveAgentId]);
-
- const handleConnect = async () => {
- if (!canCreate || !canEdit) return;
- // Only block reconnection when already connected
- if (server?.isConnected) return;
-
- setIsConnecting(true);
- try {
- // Use /oauth/callback/success as redirect URI with provider param for auto-enable
- // Skip redirectUri on desktop (app:// protocol) since the system browser can't navigate to it
- const redirectUri = window.location.protocol.startsWith('http')
- ? `${window.location.origin}/oauth/callback/success?provider=${encodeURIComponent(provider)}`
- : undefined;
- const { authorizeUrl } = await getAuthorizeUrl(provider, { redirectUri });
- openOAuthWindow(authorizeUrl);
- } catch (error) {
- console.error('[LobehubSkill] Failed to get authorize URL:', error);
- } finally {
- setIsConnecting(false);
- }
- };
-
- const handleToggle = async () => {
- if (!canEdit || !server) return;
- setIsToggling(true);
- await togglePlugin(pluginId);
- setIsToggling(false);
- };
-
- const renderRightControl = () => {
- if (isConnecting) {
- return (
- <Flexbox horizontal align="center" gap={4} onClick={stopPropagation}>
- <Icon spin icon={Loader2} />
- </Flexbox>
- );
- }
-
- if (!server) {
- return (
- <Flexbox
- horizontal
- align="center"
- gap={4}
- style={{ cursor: canCreate && canEdit ? 'pointer' : 'not-allowed', opacity: 0.65 }}
- onClick={(e) => {
- e.stopPropagation();
- if (!canCreate || !canEdit) return;
- handleConnect();
- }}
- >
- {t('tools.lobehubSkill.connect', { defaultValue: 'Connect' })}
- <Icon icon={SquareArrowOutUpRight} size="small" />
- </Flexbox>
- );
- }
+ const handleToggle = async () => {
+ if (!canEdit || !server) return;
+ setIsToggling(true);
+ await togglePlugin(pluginId);
+ setIsToggling(false);
+ };
- switch (server.status) {
- case LobehubSkillStatus.CONNECTED: {
- if (isToggling) {
- return <Icon spin icon={Loader2} />;
- }
+ const renderRightControl = () => {
+ if (isConnecting) {
return (
- <Checkbox
- checked={checked}
- disabled={!canEdit}
- onClick={(e) => {
- e.stopPropagation();
- if (!canEdit) return;
- handleToggle();
- }}
- />
- );
- }
- case LobehubSkillStatus.CONNECTING: {
- if (isWaitingAuth) {
- return (
- <Flexbox horizontal align="center" gap={4} onClick={stopPropagation}>
- <Icon spin icon={Loader2} />
- </Flexbox>
- );
- }
- return (
- <Flexbox
- horizontal
- align="center"
- gap={4}
- style={{ cursor: canEdit ? 'pointer' : 'not-allowed', opacity: 0.65 }}
- onClick={async (e) => {
- e.stopPropagation();
- if (!canEdit) return;
- try {
- const redirectUri = window.location.protocol.startsWith('http')
- ? `${window.location.origin}/oauth/callback/success?provider=${encodeURIComponent(provider)}`
- : undefined;
- const { authorizeUrl } = await getAuthorizeUrl(provider, { redirectUri });
- openOAuthWindow(authorizeUrl);
- } catch (error) {
- console.error('[LobehubSkill] Failed to get authorize URL:', error);
- }
- }}
- >
- {t('tools.lobehubSkill.authorize', { defaultValue: 'Authorize' })}
- <Icon icon={SquareArrowOutUpRight} size="small" />
+ <Flexbox horizontal align="center" gap={4} onClick={stopPropagation}>
+ <Icon spin icon={Loader2} />
</Flexbox>
);
}
- case LobehubSkillStatus.NOT_CONNECTED: {
+
+ if (!server) {
return (
<Flexbox
horizontal
@@ -322,38 +269,109 @@ const LobehubSkillServerItem = memo<LobehubSkillServerItemProps>(({ provider, la
</Flexbox>
);
}
- case LobehubSkillStatus.ERROR: {
- return (
- <span style={{ color: 'red', fontSize: 12 }}>
- {t('tools.lobehubSkill.error', { defaultValue: 'Error' })}
- </span>
- );
- }
- default: {
- return null;
- }
- }
- };
-
- return (
- <Flexbox
- horizontal
- align={'center'}
- gap={24}
- justify={'space-between'}
- onClick={(e) => {
- e.stopPropagation();
- if (canEdit && server?.status === LobehubSkillStatus.CONNECTED) {
- handleToggle();
+
+ switch (server.status) {
+ case LobehubSkillStatus.CONNECTED: {
+ if (isToggling) {
+ return <Icon spin icon={Loader2} />;
+ }
+ return (
+ <Checkbox
+ checked={checked}
+ disabled={!canEdit}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (!canEdit) return;
+ handleToggle();
+ }}
+ />
+ );
}
- }}
- >
- <Flexbox horizontal align={'center'} gap={8}>
- {label}
+ case LobehubSkillStatus.CONNECTING: {
+ if (isWaitingAuth) {
+ return (
+ <Flexbox horizontal align="center" gap={4} onClick={stopPropagation}>
+ <Icon spin icon={Loader2} />
+ </Flexbox>
+ );
+ }
+ return (
+ <Flexbox
+ horizontal
+ align="center"
+ gap={4}
+ style={{ cursor: canEdit ? 'pointer' : 'not-allowed', opacity: 0.65 }}
+ onClick={async (e) => {
+ e.stopPropagation();
+ if (!canEdit) return;
+ try {
+ const redirectUri = window.location.protocol.startsWith('http')
+ ? `${window.location.origin}/oauth/callback/success?provider=${encodeURIComponent(provider)}`
+ : undefined;
+ const { authorizeUrl } = await getAuthorizeUrl(provider, { redirectUri });
+ openOAuthWindow(authorizeUrl);
+ } catch (error) {
+ console.error('[LobehubSkill] Failed to get authorize URL:', error);
+ }
+ }}
+ >
+ {t('tools.lobehubSkill.authorize', { defaultValue: 'Authorize' })}
+ <Icon icon={SquareArrowOutUpRight} size="small" />
+ </Flexbox>
+ );
+ }
+ case LobehubSkillStatus.NOT_CONNECTED: {
+ return (
+ <Flexbox
+ horizontal
+ align="center"
+ gap={4}
+ style={{ cursor: canCreate && canEdit ? 'pointer' : 'not-allowed', opacity: 0.65 }}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (!canCreate || !canEdit) return;
+ handleConnect();
+ }}
+ >
+ {t('tools.lobehubSkill.connect', { defaultValue: 'Connect' })}
+ <Icon icon={SquareArrowOutUpRight} size="small" />
+ </Flexbox>
+ );
+ }
+ case LobehubSkillStatus.ERROR: {
+ return (
+ <span style={{ color: 'red', fontSize: 12 }}>
+ {t('tools.lobehubSkill.error', { defaultValue: 'Error' })}
+ </span>
+ );
+ }
+ default: {
+ return null;
+ }
+ }
+ };
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={24}
+ justify={'space-between'}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (canEdit && server?.status === LobehubSkillStatus.CONNECTED) {
+ handleToggle();
+ }
+ }}
+ >
+ <Flexbox horizontal align={'center'} gap={SKILL_ICON_GAP}>
+ {icon}
+ {label}
+ </Flexbox>
+ {renderRightControl()}
</Flexbox>
- {renderRightControl()}
- </Flexbox>
- );
-});
+ );
+ },
+);
export default LobehubSkillServerItem;
diff --git a/src/features/ChatInput/ActionBar/Tools/SkillRow.tsx b/src/features/ChatInput/ActionBar/Tools/SkillRow.tsx
new file mode 100644
index 00000000000..7dfa5d157da
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Tools/SkillRow.tsx
@@ -0,0 +1,83 @@
+import { Popover } from '@lobehub/ui';
+import type { ReactNode } from 'react';
+import { memo, useRef } from 'react';
+
+import { useDetailPopoverState } from '../components/useDetailPopoverState';
+
+interface SkillRowProps {
+ className?: string;
+ /** Rich detail card shown while hovering the label cell. */
+ detailContent?: ReactNode;
+ detailDisabled?: boolean;
+ label: ReactNode;
+ labelClassName?: string;
+ onContextMenu?: () => void;
+ trailing: ReactNode;
+ trailingClassName?: string;
+}
+
+/**
+ * The hover detail card is anchored to the whole row but triggered only by the
+ * label cell, so moving right onto the "..." button leaves the trigger and lets
+ * the card go — the two used to share one hover, which is why a card could land
+ * on top of the policy menu and swallow the click meant for it. The card is
+ * also inert (pointer-events: none): a press landing on the portal'd card is
+ * read by base-ui as an outside press that dismisses the enclosing menu.
+ */
+const SkillRow = memo<SkillRowProps>(
+ ({
+ className,
+ detailContent,
+ detailDisabled,
+ label,
+ labelClassName,
+ onContextMenu,
+ trailing,
+ trailingClassName,
+ }) => {
+ const rowRef = useRef<HTMLSpanElement>(null);
+ const { onOpenChange, open } = useDetailPopoverState(detailDisabled);
+
+ const labelCell = <span className={labelClassName}>{label}</span>;
+
+ return (
+ <span
+ className={className}
+ ref={rowRef}
+ onContextMenu={
+ onContextMenu &&
+ ((event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ onContextMenu();
+ })
+ }
+ >
+ {detailContent ? (
+ <Popover
+ arrow={false}
+ content={detailContent}
+ disabled={detailDisabled}
+ mouseEnterDelay={0.3}
+ open={open}
+ placement={'rightTop'}
+ positionerProps={{ anchor: rowRef, sideOffset: 8 }}
+ styles={{ content: { padding: 0 }, root: { pointerEvents: 'none' } }}
+ onOpenChange={onOpenChange}
+ >
+ {labelCell}
+ </Popover>
+ ) : (
+ labelCell
+ )}
+ <span data-tool-trailing className={trailingClassName}>
+ {trailing}
+ </span>
+ </span>
+ );
+ },
+);
+
+SkillRow.displayName = 'SkillRow';
+
+export default SkillRow;
diff --git a/src/features/ChatInput/ActionBar/Tools/ToolsList.tsx b/src/features/ChatInput/ActionBar/Tools/ToolsList.tsx
index f58804d47ed..95e1e509531 100644
--- a/src/features/ChatInput/ActionBar/Tools/ToolsList.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/ToolsList.tsx
@@ -3,12 +3,11 @@ import { Flexbox, Icon, Popover, Text } from '@lobehub/ui';
import { Divider } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
import type { ReactNode } from 'react';
-import { Fragment, isValidElement, memo, useCallback, useEffect, useRef, useState } from 'react';
+import { Fragment, isValidElement, memo } from 'react';
+import { useDetailPopoverState } from '../components/useDetailPopoverState';
import { useScrollSignal } from './ScrollSignalContext';
-const CLOSE_TOOL_DETAIL_POPOVER_EVENT = 'lobe-chat-tool-detail-popover-close';
-
export const toolsListStyles = createStaticStyles(({ css }) => ({
groupLabel: css`
padding-block: 12px 4px;
@@ -76,39 +75,11 @@ const RegularItem = memo<{
index: number;
item: ToolItemData;
}>(({ detailPopoverDisabled, item, index }) => {
- const [open, setOpen] = useState(false);
- const suppressUntilRef = useRef(0);
+ const { close, onOpenChange, open } = useDetailPopoverState(detailPopoverDisabled);
// Close hover popover whenever the surrounding list scrolls — avoids the
// detail panel hovering in mid-air after its anchor row has moved away.
- useScrollSignal(
- useCallback(() => {
- setOpen(false);
- }, []),
- );
-
- // Close hover popover when a policy menu (or other consumer) signals it —
- // prevents the detail panel from overlapping the policy menu opened from the "..." button.
- useEffect(() => {
- const close = () => {
- suppressUntilRef.current = Date.now() + 600;
- setOpen(false);
- };
- window.addEventListener(CLOSE_TOOL_DETAIL_POPOVER_EVENT, close);
- return () => window.removeEventListener(CLOSE_TOOL_DETAIL_POPOVER_EVENT, close);
- }, []);
-
- useEffect(() => {
- if (detailPopoverDisabled) setOpen(false);
- }, [detailPopoverDisabled]);
-
- const handleOpenChange = useCallback(
- (nextOpen: boolean) => {
- if (nextOpen && (detailPopoverDisabled || Date.now() < suppressUntilRef.current)) return;
- setOpen(nextOpen);
- },
- [detailPopoverDisabled],
- );
+ useScrollSignal(close);
const iconNode = item.icon ? (
isValidElement(item.icon) ? (
@@ -134,6 +105,9 @@ const RegularItem = memo<{
if (!item.popoverContent) return row;
+ // The detail card is a hover information surface: keep it inert
+ // (pointer-events: none) so a press can never land on the portal'd card and
+ // be read as an outside press that dismisses the surrounding popover.
return (
<Popover
arrow={false}
@@ -143,8 +117,8 @@ const RegularItem = memo<{
open={open}
placement={'rightTop'}
positionerProps={{ sideOffset: 8 }}
- styles={{ content: { padding: 0 } }}
- onOpenChange={handleOpenChange}
+ styles={{ content: { padding: 0 }, root: { pointerEvents: 'none' } }}
+ onOpenChange={onOpenChange}
>
{row}
</Popover>
diff --git a/src/features/ChatInput/ActionBar/Tools/constants.ts b/src/features/ChatInput/ActionBar/Tools/constants.ts
new file mode 100644
index 00000000000..40df6770acd
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Tools/constants.ts
@@ -0,0 +1,7 @@
+export const SKILL_ICON_SIZE = 18;
+
+export const SKILL_ICON_GAP = 14;
+
+// Trailing icon buttons share one box so their glyphs land on the same optical
+// column; 20px is also what keeps a row at the menu item's default 32px height.
+export const SKILL_TRAILING_CONTROL_SIZE = 20;
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index bf484ea332f..00cebee11b9 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -54,18 +54,18 @@ import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types'
import { useAgentId } from '../../hooks/useAgentId';
import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
+import { closeToolDetailPopovers } from '../components/useDetailPopoverState';
import ComposioServerItem from './ComposioServerItem';
import ComposioSkillIcon from './ComposioSkillIcon';
+import { SKILL_ICON_GAP, SKILL_ICON_SIZE, SKILL_TRAILING_CONTROL_SIZE } from './constants';
import LobehubSkillIcon from './LobehubSkillIcon';
import LobehubSkillServerItem from './LobehubSkillServerItem';
import MarketAgentSkillPopoverContent from './MarketAgentSkillPopoverContent';
import MarketSkillIcon from './MarketSkillIcon';
+import SkillRow from './SkillRow';
import ToolItem from './ToolItem';
import ToolItemDetailPopover from './ToolItemDetailPopover';
-const SKILL_ICON_SIZE = 18;
-const CLOSE_TOOL_DETAIL_POPOVER_EVENT = 'lobe-chat-tool-detail-popover-close';
-
const officialTag = (
<Tooltip placement={'top'} title={'LobeHub'}>
<Tag color={'success'} icon={<Icon icon={BadgeCheck} />} size={'small'} />
@@ -108,8 +108,8 @@ const styles = createStaticStyles(({ css }) => ({
align-items: center;
justify-content: center;
- width: 24px;
- height: 24px;
+ width: ${SKILL_TRAILING_CONTROL_SIZE}px;
+ height: ${SKILL_TRAILING_CONTROL_SIZE}px;
color: ${cssVar.colorTextTertiary};
`,
@@ -123,8 +123,24 @@ const styles = createStaticStyles(({ css }) => ({
`,
activationGroupTitleBlock: css`
display: flex;
- gap: 8px;
+ gap: ${SKILL_ICON_GAP}px;
+ align-items: center;
+ min-width: 0;
+ `,
+ activationGroupIcon: css`
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+
+ width: ${SKILL_ICON_SIZE}px;
+ `,
+ activationGroupTitleBody: css`
+ display: flex;
+ flex: 0 1 auto;
+ gap: 6px;
align-items: center;
+
min-width: 0;
`,
activationGroupTitleText: css`
@@ -173,13 +189,17 @@ const styles = createStaticStyles(({ css }) => ({
align-items: center;
justify-content: center;
- width: 24px;
- height: 24px;
+ /* Connector rows hand this button to the menu's extra slot, a plain block
+ wrapper — without vertical-align its strut adds descender space below the
+ button and pushes those rows taller than the rest. */
+ width: ${SKILL_TRAILING_CONTROL_SIZE}px;
+ height: ${SKILL_TRAILING_CONTROL_SIZE}px;
padding: 0;
border: 0;
border-radius: 6px;
color: ${cssVar.colorTextTertiary};
+ vertical-align: top;
background: transparent;
@@ -308,6 +328,15 @@ const styles = createStaticStyles(({ css }) => ({
toolLabel: css`
display: flex;
flex: 1;
+ gap: ${SKILL_ICON_GAP}px;
+ align-items: center;
+
+ min-width: 0;
+ `,
+ toolLabelBody: css`
+ overflow: hidden;
+ display: flex;
+ flex: 0 1 auto;
gap: 6px;
align-items: center;
@@ -374,10 +403,8 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorFillQuaternary};
`,
addSkillRow: css`
- cursor: pointer;
-
display: flex;
- gap: 8px;
+ gap: ${SKILL_ICON_GAP}px;
align-items: center;
width: calc(100% + 24px);
@@ -491,9 +518,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
);
const openSkillPolicyMenu = useCallback((id: string) => {
- if (typeof window !== 'undefined') {
- window.dispatchEvent(new Event(CLOSE_TOOL_DETAIL_POPOVER_EVENT));
- }
+ closeToolDetailPopovers();
setPolicyOpenId(id);
}, []);
@@ -656,11 +681,10 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
className={cx(styles.policyButton)}
disabled={!canEdit}
type="button"
+ onPointerEnter={closeToolDetailPopovers}
onClick={(event) => {
event.stopPropagation();
- if (typeof window !== 'undefined') {
- window.dispatchEvent(new Event(CLOSE_TOOL_DETAIL_POPOVER_EVENT));
- }
+ closeToolDetailPopovers();
}}
onContextMenu={(event) => {
event.preventDefault();
@@ -669,14 +693,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
}}
onPointerDown={(event) => {
event.stopPropagation();
- if (typeof window !== 'undefined') {
- window.dispatchEvent(new Event(CLOSE_TOOL_DETAIL_POPOVER_EVENT));
- }
- }}
- onPointerEnter={() => {
- if (typeof window !== 'undefined') {
- window.dispatchEvent(new Event(CLOSE_TOOL_DETAIL_POPOVER_EVENT));
- }
+ closeToolDetailPopovers();
}}
>
<Icon icon={MoreHorizontal} size={15} />
@@ -695,28 +712,34 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
badge?: ReactNode,
icon?: ReactNode,
extraTag?: ReactNode,
+ detailContent?: ReactNode,
) => (
- <span
+ <SkillRow
className={cx(styles.toolRow)}
- onContextMenu={(event) => {
- event.preventDefault();
- event.stopPropagation();
- openSkillPolicyMenu(id);
- }}
- >
- <span className={cx(styles.toolLabel)}>
- {icon}
- <span className={cx(styles.toolLabelText)}>{label}</span>
- {extraTag}
- </span>
- <span
- data-tool-trailing
- className={cx(styles.toolTrailing, policyOpenId === id && styles.toolTrailingVisible)}
- >
- {badge && <span className={cx(styles.typeTag)}>{badge}</span>}
- {action}
- </span>
- </span>
+ detailContent={detailContent}
+ detailDisabled={policyOpenId !== null}
+ labelClassName={cx(styles.toolLabel)}
+ label={
+ <>
+ {icon}
+ <span className={cx(styles.toolLabelBody)}>
+ <span className={cx(styles.toolLabelText)}>{label}</span>
+ {extraTag}
+ </span>
+ </>
+ }
+ trailing={
+ <>
+ {badge && <span className={cx(styles.typeTag)}>{badge}</span>}
+ {action}
+ </>
+ }
+ trailingClassName={cx(
+ styles.toolTrailing,
+ policyOpenId === id && styles.toolTrailingVisible,
+ )}
+ onContextMenu={() => openSkillPolicyMenu(id)}
+ />
),
[openSkillPolicyMenu, policyOpenId],
);
@@ -757,8 +780,8 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
badge,
icon,
extraTag,
+ popoverContent,
),
- popoverContent,
searchText: searchText || String(title || id),
}) as SkillMenuItem,
[renderPolicyMenu, renderToolLabel],
@@ -940,6 +963,7 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
<ComposioServerItem
agentId={agentId}
appSlug={type.appSlug}
+ icon={icon}
identifier={type.identifier}
label={type.label}
server={server}
@@ -965,7 +989,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
undefined,
true,
),
- icon,
key: removableId,
label: (
<span
@@ -984,7 +1007,6 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
}
return {
- icon,
key: type.identifier,
label: serverItem,
popoverContent,
@@ -1049,11 +1071,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
}
return {
- icon,
key: provider.id, // Use provider.id as key, consistent with pluginId
label: (
<LobehubSkillServerItem
agentId={agentId}
+ icon={icon}
label={provider.label}
provider={provider.id}
/>
@@ -1519,9 +1541,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
}}
>
<div className={cx(styles.activationGroupTitleBlock)}>
- {icon}
- <span className={cx(styles.activationGroupTitleText)}>{title}</span>
- {typeof count === 'number' && <span className={cx(styles.count)}>{count}</span>}
+ <span className={cx(styles.activationGroupIcon)}>{icon}</span>
+ <span className={cx(styles.activationGroupTitleBody)}>
+ <span className={cx(styles.activationGroupTitleText)}>{title}</span>
+ {typeof count === 'number' && <span className={cx(styles.count)}>{count}</span>}
+ </span>
</div>
<div className={cx(styles.activationGroupActions)}>
{autoSwitch && (
diff --git a/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx b/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
index 7ff1baa46d4..319c20a1842 100644
--- a/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
+++ b/src/features/ChatInput/ActionBar/components/ActionDropdown.tsx
@@ -33,6 +33,8 @@ import {
import DebugNode from '@/components/DebugNode';
import { useIsMobile } from '@/hooks/useIsMobile';
+import { type MenuOpenChangeDetails, shouldVetoMenuClose } from './menuCloseVeto';
+
const styles = createStaticStyles(({ css, cssVar }) => ({
dropdownMenu: css`
.ant-avatar {
@@ -229,8 +231,12 @@ const ActionDropdown = memo<ActionDropdownProps>(
const handleOpenChange = useCallback(
(nextOpen: boolean, details: Parameters<NonNullable<typeof onOpenChange>>[1]) => {
- if (!nextOpen && (details as { reason?: string })?.reason === 'sibling-open') {
- (details as { cancel?: () => void })?.cancel?.();
+ if (
+ !nextOpen &&
+ ((details as MenuOpenChangeDetails)?.reason === 'sibling-open' ||
+ shouldVetoMenuClose(details as MenuOpenChangeDetails))
+ ) {
+ (details as MenuOpenChangeDetails)?.cancel?.();
return;
}
onOpenChange?.(nextOpen, details);
@@ -286,9 +292,19 @@ const ActionDropdown = memo<ActionDropdownProps>(
// Any item carrying a `children` key is a submenu (children may be optional);
// route them all here so plain items never inherit a submenu's click signature.
if ('children' in item) {
+ const itemOnOpenChange = (
+ item as { onOpenChange?: (open: boolean, details?: MenuOpenChangeDetails) => void }
+ ).onOpenChange;
return {
...item,
children: item.children ? decorateMenuItems(item.children) : item.children,
+ onOpenChange: (open: boolean, details?: MenuOpenChangeDetails) => {
+ if (!open && shouldVetoMenuClose(details)) {
+ details?.cancel?.();
+ return;
+ }
+ itemOnOpenChange?.(open, details);
+ },
type: 'submenu',
// `children` is re-widened to the full item union; cast back to satisfy
// the mixed rc-menu / Base UI submenu types in `BaseMenuItemType`.
diff --git a/src/features/ChatInput/ActionBar/components/menuCloseVeto.test.ts b/src/features/ChatInput/ActionBar/components/menuCloseVeto.test.ts
new file mode 100644
index 00000000000..ae68c72be6f
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/components/menuCloseVeto.test.ts
@@ -0,0 +1,62 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { describe, expect, it } from 'vitest';
+
+import { shouldVetoMenuClose } from './menuCloseVeto';
+
+const pressOn = (
+ target: EventTarget | null,
+ reason: string,
+ relatedTarget?: EventTarget | null,
+) => {
+ const event =
+ relatedTarget === undefined
+ ? new Event('pointerdown')
+ : new FocusEvent('focusout', { relatedTarget: relatedTarget ?? undefined });
+ if (target) Object.defineProperty(event, 'target', { value: target });
+ return { event, reason };
+};
+
+describe('shouldVetoMenuClose', () => {
+ const buildDialog = (role: 'dialog' | 'alertdialog') => {
+ const dialog = document.createElement('div');
+ dialog.setAttribute('role', role);
+ const button = document.createElement('button');
+ dialog.append(button);
+ document.body.append(dialog);
+ return { button, dialog };
+ };
+
+ it('vetoes an outside-press whose target sits inside a dialog overlay', () => {
+ const { button } = buildDialog('dialog');
+ expect(shouldVetoMenuClose(pressOn(button, 'outside-press'))).toBe(true);
+ });
+
+ it('vetoes an outside-press inside an alertdialog (uninstall confirm)', () => {
+ const { button } = buildDialog('alertdialog');
+ expect(shouldVetoMenuClose(pressOn(button, 'outside-press'))).toBe(true);
+ });
+
+ it('vetoes a focus-out whose focus lands inside a dialog overlay', () => {
+ const { button } = buildDialog('dialog');
+ expect(shouldVetoMenuClose(pressOn(document.body, 'focus-out', button))).toBe(true);
+ });
+
+ it('does not veto a press on the page background', () => {
+ const outside = document.createElement('div');
+ document.body.append(outside);
+ expect(shouldVetoMenuClose(pressOn(outside, 'outside-press'))).toBe(false);
+ });
+
+ it('does not veto escape-key or item-press closes', () => {
+ const { button } = buildDialog('dialog');
+ expect(shouldVetoMenuClose(pressOn(button, 'escape-key'))).toBe(false);
+ expect(shouldVetoMenuClose(pressOn(button, 'item-press'))).toBe(false);
+ });
+
+ it('does not veto when details are missing', () => {
+ expect(shouldVetoMenuClose(undefined)).toBe(false);
+ expect(shouldVetoMenuClose({ reason: 'outside-press' })).toBe(false);
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/components/menuCloseVeto.ts b/src/features/ChatInput/ActionBar/components/menuCloseVeto.ts
new file mode 100644
index 00000000000..ce6c2717d76
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/components/menuCloseVeto.ts
@@ -0,0 +1,28 @@
+export interface MenuOpenChangeDetails {
+ cancel?: () => void;
+ event?: Event;
+ reason?: string;
+}
+
+/**
+ * Rows in the chat-input menus open companion surfaces that portal outside the
+ * menu DOM — the per-row skill policy popover, its uninstall confirm in the
+ * global modal host, detail cards. base-ui resolves a press or focus move
+ * landing on such a surface as an outside interaction and dismisses the whole
+ * menu chain, so a user acting inside the companion loses the menu underneath.
+ * A close caused by a press/focus inside any dialog-role overlay must be
+ * vetoed, for the root menu and every submenu alike.
+ */
+export const shouldVetoMenuClose = (details: MenuOpenChangeDetails | undefined): boolean => {
+ const reason = details?.reason;
+ if (reason !== 'outside-press' && reason !== 'focus-out') return false;
+ const event = details?.event;
+ const nodes: (EventTarget | null)[] = [event?.target ?? null];
+ if (event && 'relatedTarget' in event) {
+ nodes.push((event as FocusEvent).relatedTarget);
+ }
+ return nodes.some(
+ (node) =>
+ node instanceof Element && node.closest('[role="dialog"],[role="alertdialog"]') !== null,
+ );
+};
diff --git a/src/features/ChatInput/ActionBar/components/useDetailPopoverState.test.ts b/src/features/ChatInput/ActionBar/components/useDetailPopoverState.test.ts
new file mode 100644
index 00000000000..3a5e9a059cb
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/components/useDetailPopoverState.test.ts
@@ -0,0 +1,63 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { closeToolDetailPopovers, useDetailPopoverState } from './useDetailPopoverState';
+
+describe('useDetailPopoverState', () => {
+ it('opens on hover by default', () => {
+ const { result } = renderHook(() => useDetailPopoverState());
+
+ act(() => result.current.onOpenChange(true));
+
+ expect(result.current.open).toBe(true);
+ });
+
+ it('closes and suppresses reopening right after a policy menu takes over', () => {
+ const { result } = renderHook(() => useDetailPopoverState());
+
+ act(() => result.current.onOpenChange(true));
+ act(() => closeToolDetailPopovers());
+
+ expect(result.current.open).toBe(false);
+
+ act(() => result.current.onOpenChange(true));
+
+ expect(result.current.open).toBe(false);
+ });
+
+ // Regression: the "..." policy menu anchors to the same row edge as the detail
+ // popover, so a detail card reopening on top of it swallows the click meant for
+ // the menu — the uninstall confirm modal never appeared. The suppression window
+ // above expires after 600ms, so `disabled` has to hold the interlock on its own
+ // for as long as the policy menu stays open.
+ it('never reopens while disabled, even after the suppression window expires', () => {
+ const { rerender, result } = renderHook(
+ ({ disabled }: { disabled: boolean }) => useDetailPopoverState(disabled),
+ { initialProps: { disabled: false } },
+ );
+
+ act(() => result.current.onOpenChange(true));
+ expect(result.current.open).toBe(true);
+
+ rerender({ disabled: true });
+ expect(result.current.open).toBe(false);
+
+ act(() => result.current.onOpenChange(true));
+ expect(result.current.open).toBe(false);
+ });
+
+ it('allows hover again once the policy menu closes', () => {
+ const { rerender, result } = renderHook(
+ ({ disabled }: { disabled: boolean }) => useDetailPopoverState(disabled),
+ { initialProps: { disabled: true } },
+ );
+
+ act(() => result.current.onOpenChange(true));
+ expect(result.current.open).toBe(false);
+
+ rerender({ disabled: false });
+ act(() => result.current.onOpenChange(true));
+
+ expect(result.current.open).toBe(true);
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/components/useDetailPopoverState.ts b/src/features/ChatInput/ActionBar/components/useDetailPopoverState.ts
new file mode 100644
index 00000000000..b1dca291aa1
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/components/useDetailPopoverState.ts
@@ -0,0 +1,51 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+export const CLOSE_TOOL_DETAIL_POPOVER_EVENT = 'lobe-chat-tool-detail-popover-close';
+
+const REOPEN_SUPPRESS_MS = 600;
+
+export const closeToolDetailPopovers = () => {
+ if (typeof window === 'undefined') return;
+
+ window.dispatchEvent(new Event(CLOSE_TOOL_DETAIL_POPOVER_EVENT));
+};
+
+/**
+ * Hover-detail popovers of a skill row anchor to the same right edge as the row's
+ * "..." policy menu, so an open detail card lands on top of the policy menu and
+ * eats the click meant for it. `disabled` is the hard interlock the caller sets
+ * while a policy menu is open; the event-driven suppression window only covers
+ * the moment the menu opens, and a hover that starts after it expires would
+ * otherwise reopen the card over the menu.
+ */
+export const useDetailPopoverState = (disabled?: boolean) => {
+ const [open, setOpen] = useState(false);
+ const suppressUntilRef = useRef(0);
+
+ const close = useCallback(() => setOpen(false), []);
+
+ useEffect(() => {
+ const handleClose = () => {
+ suppressUntilRef.current = Date.now() + REOPEN_SUPPRESS_MS;
+ setOpen(false);
+ };
+ window.addEventListener(CLOSE_TOOL_DETAIL_POPOVER_EVENT, handleClose);
+
+ return () => window.removeEventListener(CLOSE_TOOL_DETAIL_POPOVER_EVENT, handleClose);
+ }, []);
+
+ useEffect(() => {
+ if (disabled) setOpen(false);
+ }, [disabled]);
+
+ const onOpenChange = useCallback(
+ (nextOpen: boolean) => {
+ if (nextOpen && (disabled || Date.now() < suppressUntilRef.current)) return;
+
+ setOpen(nextOpen);
+ },
+ [disabled],
+ );
+
+ return { close, onOpenChange, open };
+};