🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(conversation): global human-approval notification island (#16390)
Arvin Xu5bb04374ebb7
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 812d4265a12..c3494ce072c 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -186,6 +186,15 @@"extendParams.urlContext.title": "Extract Webpage Link Content","floatingChatPanel.collapse": "Collapse chat","floatingChatPanel.expand": "Expand chat",+ "globalApproval.collapse": "Collapse",+ "globalApproval.goToConversation": "Open conversation",+ "globalApproval.moreCount_one": "{{count}} more pending",+ "globalApproval.moreCount_other": "{{count}} more pending",+ "globalApproval.pendingCount_one": "{{count}} approval pending",+ "globalApproval.pendingCount_other": "{{count}} approvals pending",+ "globalApproval.subtitle": "Waiting for your approval",+ "globalApproval.title": "Approval needed",+ "globalApproval.userRequestLabel": "Request","followUpPlaceholder": "Follow up.","followUpPlaceholderHeterogeneous": "Follow up.","gatewayMode.beta": "Beta",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 18af05c2433..0b04656c11e 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -186,6 +186,15 @@"extendParams.urlContext.title": "提取网页链接内容","floatingChatPanel.collapse": "收起聊天","floatingChatPanel.expand": "展开聊天",+ "globalApproval.collapse": "收起",+ "globalApproval.goToConversation": "打开会话",+ "globalApproval.moreCount_one": "还有 {{count}} 个待审批",+ "globalApproval.moreCount_other": "还有 {{count}} 个待审批",+ "globalApproval.pendingCount_one": "{{count}} 项待审批",+ "globalApproval.pendingCount_other": "{{count}} 项待审批",+ "globalApproval.subtitle": "等待你的审批",+ "globalApproval.title": "需要审批",+ "globalApproval.userRequestLabel": "用户请求","followUpPlaceholder": "继续跟进。","followUpPlaceholderHeterogeneous": "继续跟进。","gatewayMode.beta": "Beta",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 3a423fa4039..62ecc22e101 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -589,6 +589,15 @@ export default {'selectedAgents': 'Selected agents','floatingChatPanel.collapse': 'Collapse chat','floatingChatPanel.expand': 'Expand chat',+ 'globalApproval.collapse': 'Collapse',+ 'globalApproval.goToConversation': 'Open conversation',+ 'globalApproval.moreCount_one': '{{count}} more pending',+ 'globalApproval.moreCount_other': '{{count}} more pending',+ 'globalApproval.pendingCount_one': '{{count}} approval pending',+ 'globalApproval.pendingCount_other': '{{count}} approvals pending',+ 'globalApproval.subtitle': 'Waiting for your approval',+ 'globalApproval.title': 'Approval needed',+ 'globalApproval.userRequestLabel': 'Request','followUpPlaceholder': 'Follow up.','followUpPlaceholderHeterogeneous': 'Follow up.','sendPlaceholder': 'Ask, create, or start a task, <hotkey><hotkey/>',diff --git a/src/features/GlobalApprovalNotification/ApprovalCard.tsx b/src/features/GlobalApprovalNotification/ApprovalCard.tsxnew file mode 100644index 00000000000..41baf4b858b--- /dev/null+++ b/src/features/GlobalApprovalNotification/ApprovalCard.tsx@@ -0,0 +1,193 @@+'use client';++import { AGENT_CHAT_TOPIC_URL, GROUP_CHAT_TOPIC_URL, GROUP_CHAT_URL } from '@lobechat/const';+import { type UIChatMessage } from '@lobechat/types';+import { ActionIcon, Avatar } from '@lobehub/ui';+import { ArrowUpRight } from 'lucide-react';+import { memo, useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router';++import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { ConversationProvider } from '@/features/Conversation';+import InterventionContent from '@/features/Conversation/InterventionBar/InterventionContent';+import InterventionTabBar from '@/features/Conversation/InterventionBar/InterventionTabBar';+import { type ConversationContext } from '@/features/Conversation/types';+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';+import { useOperationState } from '@/hooks/useOperationState';+import { useAgentStore } from '@/store/agent';+import { agentSelectors } from '@/store/agent/selectors';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++import { styles } from './styles';+import { type GlobalApprovalGroup } from './useGlobalPendingApprovals';++interface ApprovalCardProps {+ group: GlobalApprovalGroup;+}++/**+ * A single conversation's approval card. Mounts an isolated+ * `ConversationProvider` bound to the run's context so the reused+ * `InterventionContent` (with its built-in approve / reject, edit, and custom+ * intervention UIs) operates on the right conversation without the user having+ * to switch into it.+ */+const ApprovalCard = memo<ApprovalCardProps>(({ group }) => {+ const { context, interventions } = group;+ const { t } = useTranslation('chat');+ const navigate = useNavigate();+ const workspaceSlug = useActiveWorkspaceSlug();++ const chatKey = useMemo(() => messageMapKey(context), [context]);+ const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);+ const replaceMessages = useChatStore((s) => s.replaceMessages);+ const handleMessagesChange = useCallback(+ (next: UIChatMessage[], ctx: ConversationContext) => {+ replaceMessages(next, { context: ctx });+ },+ [replaceMessages],+ );++ const operationState = useOperationState(context);+ const meta = useAgentStore(agentSelectors.getAgentMetaById(context.agentId));++ // Topic title tells the user *which* conversation this approval belongs to.+ // Read agent-scoped (not active-scoped) so a non-active conversation resolves.+ const topicTitle = useChatStore((s) =>+ context.topicId+ ? topicSelectors+ .getTopicsByAgentId(context.agentId)(s)+ ?.find((tp) => tp.id === context.topicId)?.title+ : undefined,+ );++ const [actionsPortalTarget, setActionsPortalTarget] = useState<HTMLDivElement | null>(null);+ const [activeId, setActiveId] = useState<string | null>(null);++ // Keep the active tab pinned to its toolCallId; fall back to the first when+ // the previously-active intervention is resolved and drops out.+ const activeIndex = useMemo(() => {+ if (activeId) {+ const idx = interventions.findIndex((i) => i.toolCallId === activeId);+ if (idx >= 0) return idx;+ }+ return 0;+ }, [interventions, activeId]);++ const handleTabChange = useCallback(+ (index: number) => {+ setActiveId(interventions[index]?.toolCallId ?? null);+ },+ [interventions],+ );++ const handleGoToConversation = useCallback(() => {+ // Group conversations route under /group/<groupId>; agent runs under+ // /agent/<agentId>/<topicId>. Routing a group approval through the agent URL+ // would land on the agent's 1:1 chat instead of the paused group topic.+ let path: string | undefined;+ if (context.groupId) {+ path = context.topicId+ ? GROUP_CHAT_TOPIC_URL(context.groupId, context.topicId)+ : GROUP_CHAT_URL(context.groupId);+ } else if (context.topicId) {+ path = AGENT_CHAT_TOPIC_URL(context.agentId, context.topicId);+ }+ if (!path) return;+ navigate(buildWorkspaceAwarePath(path, workspaceSlug));+ }, [context.agentId, context.groupId, context.topicId, navigate, workspaceSlug]);++ const canOpenConversation = !!(context.groupId || context.topicId);++ const activeIntervention = interventions[activeIndex];++ // The user request that led to this tool call — shown above the tool so it's+ // clear *what* is being approved. Walk back from the intervention's turn+ // anchor to the nearest user message.+ const userRequest = useMemo(() => {+ if (!messages?.length || !activeIntervention) return '';+ const anchorId = activeIntervention.assistantGroupId ?? activeIntervention.toolMessageId;+ let idx = messages.findIndex((m) => m.id === anchorId);+ if (idx < 0) idx = messages.length - 1;+ for (let i = idx; i >= 0; i -= 1) {+ const m = messages[i];+ if (m.role === 'user' && typeof m.content === 'string' && m.content.trim()) {+ return m.content.trim();+ }+ }+ return '';+ }, [messages, activeIntervention]);++ if (!activeIntervention) return null;++ return (+ <ConversationProvider+ skipFetch+ context={context}+ hasInitMessages={!!messages}+ messages={messages}+ operationState={operationState}+ onMessagesChange={handleMessagesChange}+ >+ <div className={styles.card}>+ <div className={styles.header}>+ <Avatar+ avatar={meta.avatar}+ background={meta.backgroundColor}+ size={28}+ title={meta.title}+ />+ <div className={styles.headerMeta}>+ <div className={styles.headerTitle}>+ {topicTitle || meta.title || t('globalApproval.title')}+ </div>+ <div className={styles.headerSubtitle}>+ {meta.title ? `${meta.title} · ` : ''}+ {t('globalApproval.subtitle')}+ </div>+ </div>+ {canOpenConversation && (+ <ActionIcon+ icon={ArrowUpRight}+ size="small"+ title={t('globalApproval.goToConversation')}+ onClick={handleGoToConversation}+ />+ )}+ </div>++ {userRequest && (+ <div className={styles.userRequest}>+ <span className={styles.userRequestLabel}>{t('globalApproval.userRequestLabel')}</span>+ <span className={styles.userRequestText}>{userRequest}</span>+ </div>+ )}++ {interventions.length > 1 && (+ <InterventionTabBar+ activeIndex={activeIndex}+ interventions={interventions}+ onTabChange={handleTabChange}+ />+ )}++ <div className={styles.content}>+ <InterventionContent+ actionsPortalTarget={actionsPortalTarget}+ intervention={activeIntervention}+ key={activeIntervention.toolCallId}+ />+ </div>++ <div className={styles.actions} ref={setActionsPortalTarget} />+ </div>+ </ConversationProvider>+ );+});++ApprovalCard.displayName = 'ApprovalCard';++export default ApprovalCard;diff --git a/src/features/GlobalApprovalNotification/index.tsx b/src/features/GlobalApprovalNotification/index.tsxnew file mode 100644index 00000000000..bdb6bcf78bb--- /dev/null+++ b/src/features/GlobalApprovalNotification/index.tsx@@ -0,0 +1,114 @@+'use client';++import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';+import { ActionIcon } from '@lobehub/ui';+import { ChevronUp } from 'lucide-react';+import { AnimatePresence, m } from 'motion/react';+import { memo, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { isDesktop } from '@/const/version';++import ApprovalCard from './ApprovalCard';+import { styles } from './styles';+import { useGlobalPendingApprovals } from './useGlobalPendingApprovals';++const SPRING = { damping: 30, stiffness: 320, type: 'spring' } as const;++// Push below the desktop title bar; the web build has no title bar.+const TOP_OFFSET = isDesktop ? TITLE_BAR_HEIGHT + 8 : 16;++/**+ * GlobalApprovalNotification+ *+ * A "dynamic island" that drops in from the top center whenever a locally-driven+ * agent run in a non-active conversation is waiting for human approval. It lets+ * the user approve / reject inline — or jump to the conversation — without+ * leaving the current page. Renders nothing while idle.+ */+const GlobalApprovalNotification = memo(() => {+ const { t } = useTranslation('chat');+ const groups = useGlobalPendingApprovals();+ const [collapsed, setCollapsed] = useState(false);++ // Auto-expand whenever a fresh batch of approvals arrives after being idle.+ const prevCount = useRef(0);+ useEffect(() => {+ if (groups.length > prevCount.current) setCollapsed(false);+ prevCount.current = groups.length;+ }, [groups.length]);++ const hasApprovals = groups.length > 0;+ // Only ONE card is actionable at a time: the reused `ApprovalActions`+ // registers window-level Enter/1/2 shortcuts, so mounting a card per group+ // would let a single Enter submit every pending approval at once. Extra+ // approvals queue behind a count and surface as each one resolves.+ const top = groups[0];+ const extraCount = groups.length - 1;++ return (+ <div className={styles.wrapper} style={{ '--global-approval-top': `${TOP_OFFSET}px` } as any}>+ <AnimatePresence mode="popLayout">+ {hasApprovals &&+ (collapsed ? (+ <m.div+ layout+ animate={{ opacity: 1, scale: 1, y: 0 }}+ className={styles.pill}+ exit={{ opacity: 0, scale: 0.9, y: -16 }}+ initial={{ opacity: 0, scale: 0.9, y: -16 }}+ key="pill"+ transition={SPRING}+ onClick={() => setCollapsed(false)}+ >+ <span className={styles.pillDot} />+ {t('globalApproval.pendingCount', { count: groups.length })}+ </m.div>+ ) : (+ <m.div+ layout+ animate={{ opacity: 1, scale: 1, y: 0 }}+ className={styles.stack}+ exit={{ opacity: 0, scale: 0.96, y: -16 }}+ initial={{ opacity: 0, scale: 0.96, y: -16 }}+ key="stack"+ transition={SPRING}+ >+ <m.div layout style={{ alignSelf: 'flex-end', pointerEvents: 'auto' }}>+ <ActionIcon+ icon={ChevronUp}+ size="small"+ title={t('globalApproval.collapse')}+ onClick={() => setCollapsed(true)}+ />+ </m.div>+ <AnimatePresence mode="popLayout">+ {top && (+ <m.div+ layout+ animate={{ opacity: 1, scale: 1, y: 0 }}+ exit={{ opacity: 0, scale: 0.96, y: -16 }}+ initial={{ opacity: 0, scale: 0.96, y: -16 }}+ key={top.key}+ style={{ pointerEvents: 'auto', width: '100%' }}+ transition={SPRING}+ >+ <ApprovalCard group={top} />+ </m.div>+ )}+ </AnimatePresence>+ {extraCount > 0 && (+ <div className={styles.moreHint}>+ {t('globalApproval.moreCount', { count: extraCount })}+ </div>+ )}+ </m.div>+ ))}+ </AnimatePresence>+ </div>+ );+});++GlobalApprovalNotification.displayName = 'GlobalApprovalNotification';++export default GlobalApprovalNotification;diff --git a/src/features/GlobalApprovalNotification/styles.ts b/src/features/GlobalApprovalNotification/styles.tsnew file mode 100644index 00000000000..30ca11879ac--- /dev/null+++ b/src/features/GlobalApprovalNotification/styles.ts@@ -0,0 +1,159 @@+import { createStaticStyles } from 'antd-style';++export const styles = createStaticStyles(({ css, cssVar }) => ({+ // Footer hosting the approve / reject actions (portal target). Hidden until+ // the Intervention component fills it.+ actions: css`+ padding-block: 8px 12px;+ padding-inline: 12px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ background: color-mix(in srgb, ${cssVar.colorBgElevated} 92%, ${cssVar.colorFillSecondary});++ &:empty {+ display: none;+ }+ `,+ card: css`+ overflow: hidden;+ display: flex;+ flex-direction: column;++ width: 100%;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgElevated};+ box-shadow: ${cssVar.boxShadowSecondary};++ pointer-events: auto;+ `,+ content: css`+ overflow-y: auto;+ flex: 1;+ min-height: 0;+ max-height: 42vh;+ padding-block: 6px 8px;+ padding-inline: 12px;+ `,+ header: css`+ display: flex;+ gap: 8px;+ align-items: center;++ padding-block: 8px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ headerMeta: css`+ overflow: hidden;+ flex: 1;+ min-width: 0;+ `,+ headerSubtitle: css`+ overflow: hidden;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ headerTitle: css`+ overflow: hidden;+ font-size: 13px;+ font-weight: 500;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ // "+N more pending" hint shown when several conversations are waiting; only+ // the top card is actionable at once.+ moreHint: css`+ align-self: center;++ padding-block: 2px;++ font-size: 12px;+ color: ${cssVar.colorTextTertiary};++ pointer-events: auto;+ `,+ // Collapsed "dynamic island" pill.+ pill: css`+ cursor: pointer;++ display: flex;+ gap: 8px;+ align-items: center;++ height: 36px;+ padding-inline: 14px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 999px;++ font-size: 13px;+ color: ${cssVar.colorText};++ background: ${cssVar.colorBgElevated};+ box-shadow: ${cssVar.boxShadowSecondary};++ pointer-events: auto;+ `,+ pillDot: css`+ flex-shrink: 0;+ width: 7px;+ height: 7px;+ border-radius: 999px;+ background: ${cssVar.colorPrimary};+ `,+ stack: css`+ display: flex;+ flex-direction: column;+ gap: 10px;+ width: 100%;+ `,+ // The user request that triggered the tool call — context for the approval.+ userRequest: css`+ display: flex;+ gap: 6px;+ align-items: baseline;++ padding-block: 8px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ background: ${cssVar.colorFillQuaternary};+ `,+ userRequestLabel: css`+ flex-shrink: 0;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ userRequestText: css`+ display: -webkit-box;+ overflow: hidden;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;++ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;+ `,+ // Top-center fixed wrapper. The wrapper ignores pointer events so it never+ // blocks the page; only the cards / pill re-enable them.+ wrapper: css`+ pointer-events: none;++ position: fixed;+ z-index: 1000;+ inset-block-start: var(--global-approval-top, 16px);+ inset-inline-start: 50%;++ display: flex;+ flex-direction: column;+ align-items: center;++ width: min(420px, 92vw);++ transform: translateX(-50%);+ `,+}));diff --git a/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.test.ts b/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.test.tsnew file mode 100644index 00000000000..e95ea5650a7--- /dev/null+++ b/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.test.ts@@ -0,0 +1,164 @@+import { type UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { type Operation } from '@/store/chat/slices/operation/types';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++import { collectGlobalApprovals } from './useGlobalPendingApprovals';++// A standalone tool message that `getPendingInterventions` recognizes as pending.+const pendingToolMessage = (id: string, toolCallId: string): UIChatMessage =>+ ({+ id,+ plugin: { apiName: 'runCommand', arguments: '{}', identifier: 'lobe-local-system' },+ pluginIntervention: { status: 'pending' },+ role: 'tool',+ tool_call_id: toolCallId,+ }) as unknown as UIChatMessage;++const op = (+ context: Operation['context'],+ type: Operation['type'] = 'execServerAgentRuntime',+): Operation => ({ context, type }) as unknown as Operation;++// A Claude Code (heterogeneous) intervention: the executor stamps the canonical+// `intervention.status='pending'` onto the parent assistant's `tools[]` (mirrored+// from the tool message), which `getPendingInterventions` reads via the+// children-block path. Identifier is `claude-code`.+const ccAssistantWithPendingTool = (assistantId: string, toolMsgId: string): UIChatMessage =>+ ({+ children: [+ {+ tools: [+ {+ apiName: 'AskUserQuestion',+ arguments: '{}',+ id: 'call_cc_1',+ identifier: 'claude-code',+ intervention: { status: 'pending' },+ result_msg_id: toolMsgId,+ },+ ],+ },+ ],+ id: assistantId,+ role: 'assistant',+ }) as unknown as UIChatMessage;++describe('collectGlobalApprovals', () => {+ it('surfaces a pending bucket whose context is resolvable from an operation', () => {+ const ctx = { agentId: 'agt_a', topicId: 'tpc_1' };+ const key = messageMapKey(ctx);++ const groups = collectGlobalApprovals(+ { [key]: [pendingToolMessage('msg_1', 'call_1')] },+ { op_1: op(ctx) },+ null,+ );++ expect(groups).toHaveLength(1);+ expect(groups[0].key).toBe(key);+ expect(groups[0].context).toEqual(ctx);+ expect(groups[0].interventions).toHaveLength(1);+ expect(groups[0].interventions[0].toolMessageId).toBe('msg_1');+ });++ it('excludes the conversation currently on screen (active key)', () => {+ const ctx = { agentId: 'agt_a', topicId: 'tpc_1' };+ const key = messageMapKey(ctx);++ const groups = collectGlobalApprovals(+ { [key]: [pendingToolMessage('msg_1', 'call_1')] },+ { op_1: op(ctx) },+ key, // active+ );++ expect(groups).toHaveLength(0);+ });++ it('skips buckets that resolve to neither an operation nor message fields', () => {+ const ctx = { agentId: 'agt_a', topicId: 'tpc_1' };+ const key = messageMapKey(ctx);++ // Pending message exists, but no operation pins the bucket AND the message+ // carries no coordinates to reconstruct from → cannot mount.+ const groups = collectGlobalApprovals(+ { [key]: [pendingToolMessage('msg_1', 'call_1')] },+ {},+ null,+ );++ expect(groups).toHaveLength(0);+ });++ it('falls back to message fields when the parked run operation is gone', () => {+ // A run parked for approval completes (and later GCs) its operation while+ // the tool stays pending — the bucket must stay visible via the message's+ // own agent/topic coordinates, verified to reproduce the same key.+ const ctx = { agentId: 'agt_a', topicId: 'tpc_1' };+ const key = messageMapKey(ctx);+ const msg = {+ agentId: 'agt_a',+ id: 'msg_1',+ plugin: { apiName: 'runCommand', arguments: '{}', identifier: 'lobe-local-system' },+ pluginIntervention: { status: 'pending' },+ role: 'tool',+ tool_call_id: 'call_1',+ topicId: 'tpc_1',+ } as unknown as UIChatMessage;++ const groups = collectGlobalApprovals({ [key]: [msg] }, {}, null);++ expect(groups).toHaveLength(1);+ expect(groups[0].context).toEqual({ agentId: 'agt_a', threadId: undefined, topicId: 'tpc_1' });+ });++ it('skips buckets without any pending intervention', () => {+ const ctx = { agentId: 'agt_a', topicId: 'tpc_1' };+ const key = messageMapKey(ctx);+ const resolved = {+ id: 'msg_1',+ plugin: { apiName: 'runCommand', arguments: '{}', identifier: 'lobe-local-system' },+ pluginIntervention: { status: 'approved' },+ role: 'tool',+ tool_call_id: 'call_1',+ } as unknown as UIChatMessage;++ const groups = collectGlobalApprovals({ [key]: [resolved] }, { op_1: op(ctx) }, null);++ expect(groups).toHaveLength(0);+ });++ it('resolves thread-scope buckets via the run operation context', () => {+ const ctx = { agentId: 'agt_a', threadId: 'thd_1', topicId: 'tpc_1' };+ const key = messageMapKey(ctx);++ const groups = collectGlobalApprovals(+ { [key]: [pendingToolMessage('msg_1', 'call_1')] },+ { op_1: op(ctx) },+ null,+ );++ expect(groups).toHaveLength(1);+ expect(groups[0].context).toEqual(ctx);+ });++ it('surfaces a Claude Code (hetero) wait-for-human in a thread-scope bucket', () => {+ // CC runs in a Thread; the parked intervention lives on the assistant's+ // tools[] and the run keeps a live `execHeterogeneousAgent` operation whose+ // context resolves the thread bucket.+ const ctx = { agentId: 'agt_cc', threadId: 'thd_1', topicId: 'tpc_1' };+ const key = messageMapKey(ctx);++ const groups = collectGlobalApprovals(+ { [key]: [ccAssistantWithPendingTool('asst_cc', 'msg_cc_tool')] },+ { op_cc: op(ctx, 'execHeterogeneousAgent') },+ null,+ );++ expect(groups).toHaveLength(1);+ expect(groups[0].context).toEqual(ctx);+ expect(groups[0].interventions[0].identifier).toBe('claude-code');+ expect(groups[0].interventions[0].toolMessageId).toBe('msg_cc_tool');+ });+});diff --git a/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.ts b/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.tsnew file mode 100644index 00000000000..6f38274a98c--- /dev/null+++ b/src/features/GlobalApprovalNotification/useGlobalPendingApprovals.ts@@ -0,0 +1,117 @@+import { type UIChatMessage } from '@lobechat/types';+import { useMemo } from 'react';+import { useShallow } from 'zustand/react/shallow';++import {+ getPendingInterventions,+ type PendingIntervention,+} from '@/features/Conversation/store/slices/data/pendingInterventions';+import { type ConversationContext } from '@/features/Conversation/types';+import { useChatStore } from '@/store/chat';+import { displayMessageSelectors } from '@/store/chat/selectors';+import { type Operation } from '@/store/chat/slices/operation/types';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++/**+ * One conversation's worth of pending approvals, ready to be surfaced in the+ * global notification. Grouped per context so a single card can mount one+ * `ConversationProvider` and tab between multiple pending tools.+ */+export interface GlobalApprovalGroup {+ /** Authoritative context resolved from the run that owns the bucket. */+ context: ConversationContext;+ interventions: PendingIntervention[];+ /** `messageMapKey(context)` — stable identity for animation keys. */+ key: string;+}++/**+ * Best-effort context recovery from a bucket's own messages, used when no live+ * operation pins the bucket (a parked run's `execAgentRuntime` op completes once+ * it hits `waiting_for_human` and is GC'd ~30s later, while the tool message+ * stays `pending`). We only trust a reconstruction that reproduces the exact+ * bucket key, so group/page scopes — whose key can't be rebuilt from message+ * fields — are skipped rather than mounted against the wrong bucket.+ */+const reconstructContextFromMessages = (+ messages: UIChatMessage[],+ key: string,+): ConversationContext | undefined => {+ const m = messages.find((msg) => msg.agentId && msg.agentId !== 'supervisor');+ if (!m?.agentId) return undefined;++ const context: ConversationContext = {+ agentId: m.agentId,+ threadId: m.threadId ?? undefined,+ topicId: m.topicId ?? undefined,+ };+ return messageMapKey(context) === key ? context : undefined;+};++/**+ * Pure aggregation behind {@link useGlobalPendingApprovals}. Kept side-effect+ * free so the bucket → context resolution (the tricky part) is unit-testable+ * without a store.+ *+ * The bucket → context mapping is recovered first from this client's operations+ * (whose captured `context` reproduces the exact `messageMapKey` the run used,+ * staying correct for group / thread / page scopes), then falls back to the+ * bucket's own messages so a parked approval stays visible after its operation+ * is garbage-collected.+ */+export const collectGlobalApprovals = (+ dbMessagesMap: Record<string, UIChatMessage[]>,+ operations: Record<string, Operation>,+ activeKey: string | null,+): GlobalApprovalGroup[] => {+ // Build the authoritative bucketKey → context map from in-flight runs.+ const contextByKey = new Map<string, ConversationContext>();+ for (const op of Object.values(operations)) {+ const ctx = op.context;+ if (!ctx?.agentId) continue;+ const key = messageMapKey(ctx as ConversationContext);+ if (!contextByKey.has(key)) contextByKey.set(key, ctx as ConversationContext);+ }++ const groups: GlobalApprovalGroup[] = [];+ for (const [key, messages] of Object.entries(dbMessagesMap)) {+ // Skip the conversation already on screen — InterventionBar owns it.+ if (key === activeKey) continue;+ if (!messages?.length) continue;++ const interventions = getPendingInterventions(messages);+ if (interventions.length === 0) continue;++ // Resolve a context we can mount a ConversationProvider against (operation+ // first, then message-field fallback). Without it we can't read the bucket.+ const context = contextByKey.get(key) ?? reconstructContextFromMessages(messages, key);+ if (!context) continue;++ groups.push({ context, interventions, key });+ }++ return groups;+};++/**+ * Aggregate pending human-approval requests across **all locally-driven runs**,+ * excluding the conversation the user is currently viewing (the in-place+ * `InterventionBar` already handles that one).+ */+export const useGlobalPendingApprovals = (): GlobalApprovalGroup[] => {+ const { dbMessagesMap, operations } = useChatStore(+ useShallow((s) => ({+ dbMessagesMap: s.dbMessagesMap,+ operations: s.operations,+ })),+ );+ // Active conversation's bucket key — built from the full scoped context+ // (agent / topic / thread / group) so a pending approval in the on-screen+ // group/thread conversation is excluded, not duplicated.+ const activeKey = useChatStore(displayMessageSelectors.currentDisplayChatKey);++ return useMemo(+ () => collectGlobalApprovals(dbMessagesMap, operations, activeKey),+ [dbMessagesMap, operations, activeKey],+ );+};diff --git a/src/routes/(main)/_layout/index.tsx b/src/routes/(main)/_layout/index.tsxindex 96e7d9402fb..e9aa741ef90 100644--- a/src/routes/(main)/_layout/index.tsx+++ b/src/routes/(main)/_layout/index.tsx@@ -39,6 +39,9 @@ import RegisterHotkeys from './RegisterHotkeys';import { styles } from './style';const CloudBanner = dynamic(() => import('@/features/AlertBanner/CloudBanner'));+const GlobalApprovalNotification = dynamic(+ () => import('@/features/GlobalApprovalNotification'),+);const Layout: FC = () => {const { isPWA } = usePlatform();@@ -90,6 +93,7 @@ const Layout: FC = () => {<HotkeyHelperPanel /><RegisterHotkeys /><CmdkLazy />+ <GlobalApprovalNotification /></Suspense></WorkspaceContextSlot></HotkeysProvider>