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.

6.9 KB
Raw Blame
'use client';

import { goalClarificationIslandKey } from '@lobechat/const/goal';
import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';
import { toast } from '@lobehub/ui';
import { AnimatePresence } from 'motion/react';
import * as m from 'motion/react-m';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';

import { isDesktop } from '@/const/version';
import { usePermission } from '@/hooks/usePermission';

import ApprovalCard from './ApprovalCard';
import GoalClarificationCard from './GoalClarificationCard';
import GoalDecisionCard from './GoalDecisionCard';
import { styles } from './styles';
import { useApprovalIslandCollapse } from './useApprovalIslandCollapse';
import { useGlobalPendingApprovals } from './useGlobalPendingApprovals';
import { useIslandDismissals } from './useIslandDismissals';
import { usePendingGoalClarifications } from './usePendingGoalClarifications';
import { usePendingGoalDecisions } from './usePendingGoalDecisions';

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();
  // A goal waiting on its clarification round asks through the same island.
  // Run approvals go first: a run is blocked mid-turn, a goal has not started.
  const goalGroups = usePendingGoalClarifications();
  // Then the gates a running goal stopped on, then finished goals awaiting
  // sign-off β€” each blocks less than the one before it.
  const goalItems = usePendingGoalDecisions();
  // Goal asks the user waved off leave the island but stay in the Home inbox,
  // so they are never lost β€” a run approval has no such fallback and stays.
  // The server leaves dismissed asks out of both lists, on every client.
  const { allowed: canAnswerGoals } = usePermission('create_content');
  const dismissKey = useIslandDismissals(canAnswerGoals);
  // Confirm only once the server kept it; on failure the card comes back.
  const dismiss = async (key: string) => {
    try {
      await dismissKey(key);
      toast.info({ placement: 'top', title: t('globalApproval.dismissed') });
    } catch (error) {
      console.error('[island] failed to dismiss', error);
      toast.error({ placement: 'top', title: t('globalApproval.dismissFailed') });
    }
  };
  const total = groups.length + goalGroups.length + goalItems.length;
  const [collapsed, setCollapsed] = useApprovalIslandCollapse(total);

  const hasApprovals = total > 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 topGoal = top ? undefined : goalGroups[0];
  const topGoalItem = top || topGoal ? undefined : goalItems[0];
  const extraCount = total - 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: total })}
            </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}
            >
              <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} onCollapse={() => setCollapsed(true)} />
                  </m.div>
                )}
                {topGoal && (
                  <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={`goal:${topGoal.goalId}`}
                    style={{ pointerEvents: 'auto', width: '100%' }}
                    transition={SPRING}
                  >
                    <GoalClarificationCard
                      group={topGoal}
                      onCollapse={() => setCollapsed(true)}
                      onDismiss={() => dismiss(goalClarificationIslandKey(topGoal))}
                    />
                  </m.div>
                )}
                {topGoalItem && (
                  <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={topGoalItem.key}
                    style={{ pointerEvents: 'auto', width: '100%' }}
                    transition={SPRING}
                  >
                    <GoalDecisionCard
                      item={topGoalItem}
                      onCollapse={() => setCollapsed(true)}
                      onDismiss={() => dismiss(topGoalItem.key)}
                    />
                  </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;