Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

33.8 KB
Raw Blame
/**
 * MessageActionBar
 * ---------------------------------------------------------------------------
 * Action bar for chat messages (V1.2 spec).
 *
 * Layout:
 *   - Bar gap 2px, align-items: center
 *   - Order is `align`-driven:
 *       align="left"  → [CopyBtn][ForkBtn][EditBtn][MoreMenu][TimeText][CostText]
 *       align="right" → [TimeText][CopyBtn][ForkBtn][EditBtn][MoreMenu] (user)
 *   - Action buttons are 24×24; More uses a pill trigger and a 12px menu
 *     containing message deep-link copy and single-message deletion.
 *   - Icon lucide 14×14, color #737373 (Light) / #a3a3a3 (Dark)
 *     hover color #262626 (Light) / #ffffff (Dark)
 *   - Time text 12px Inter normal, color INVERTED from icon (#a3a3a3 / #737373)
 *
 * Visibility (controlled by parent hover container unless the Bot-only
 * simplified mode keeps the bar visible):
 *   - visible=true  → opacity 1 (mounted, no fade-in per spec)
 *   - visible=false → opacity 0 + pointer-events-none, parent owns 200ms
 *     debounce + 150ms fade-out lifecycle
 *
 * Copy click:
 *   - Writes copyText to clipboard, swaps icon to Check.
 *   - Bar does NOT auto-fade — appearance/disappearance is driven entirely by
 *     hover. Check icon resets to Copy when hover leaves (next hover-in shows
 *     the default Copy icon again).
 */

import { useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';
import {
  Check,
  Copy,
  Ellipsis,
  Link2,
  MessageSquarePlus,
  MessagesSquare,
  SmilePlus,
  Pencil,
  Share,
  Split,
  Trash2,
  Undo2,
  Volume2,
  Square,
} from 'lucide-react';
import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';
import { cn } from '@/lib/utils';
import { MENU_ITEM_CLASS } from '@/features/cc-agent/sidebar/menuStyles';
import { CHAT_COLOR_TRANSITION_CLASS, CHAT_ICON_BUTTON_CLASS } from './chatChrome';
import { MessageReadAloudContext } from './MessageReadAloudContext';
import { ChatReplyIcon } from './ChatReplyIcon';
import { Spinner } from '@/components/ui/spinner';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Tip, Tooltip } from '@/components/ui/tooltip';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { toast } from '@/lib/toast';
import { formatAbsolute, useRelativeTime } from '@/hooks/useRelativeTime';
import { SHARE_EXCLUDE_ATTR } from '@/lib/shareConversationImage';
import { formatCompactTokens, formatTurnCostMoney } from '@/lib/usageFormat';
import { buildTurnUsageTooltipLines } from '@/lib/turnUsageTooltip';
import type { TurnUsageDetails } from '../../../shared/turnUsageDetails';
import {
  legacyUsdMoney,
  type RegionalMoney,
} from '../../../shared/regionalMoney';

interface MessageActionBarProps {
  createdAt?: string;
  /** Plaintext that will hit the clipboard on copy click. */
  copyText: string;
  /** Message deep link (`cindy://session/<id>?message=<clientId>`) copied by
   *  the More menu's "copy current conversation link" item. */
  copyLinkText?: string;
  /** Visual alignment + order only; callbacks determine available actions. */
  align: 'left' | 'right';
  /** Whether the parent message is currently hovered. Drives the entire
   *  fade lifecycle internally so quick re-enters don't replay from 0. */
  hovered: boolean;
  /** 伙伴对话专属精简态:操作栏常显,隐藏费用和 Fork,并把引用入口外显为“回复”。 */
  simplifiedBotConversation?: boolean;
  /** Only completed companion replies opt in; ordinary task/user messages do not. */
  readAloudMessage?: { sessionId: string; messageId: string };
  /**
   * 贴在气泡旁的紧凑栏(群聊):外露引用回复、话题、表情和更多;复制、分享为图片与准确
   * 时间收进更多菜单,让整栏窄到能放在气泡外侧。话题保持外露:关闭话题面板后焦点要回到
   * 打开它的按钮上,菜单项做不到。
   */
  compact?: boolean;
  /** When provided, render a Fork button (user messages fork *before* the
   *  question; assistant messages fork *through* the reply's turn — the
   *  parent decides whether to wire it). Returning a promise keeps the
   *  loading state alive until resolve/reject. The bar dims to opacity 0.6 +
   *  pointer-events:none for the duration; the Fork icon is replaced with a
   *  spinning Loader2. */
  onFork?: () => Promise<void>;
  /** Insert this message's anchored conversation link into the active composer. */
  onAddToChat?: () => void;
  /** 进入「分享为图片」选择模式并预选本条。放在复制按钮右边(产品指定位置)。 */
  onShareAsImage?: () => void;
  /** Thread replies use the same toolbar geometry as private-chat replies. */
  replyAction?: { onClick: () => void; label: string; count?: number };
  /** Quote this message into the current timeline's composer (group 引用回复); never opens a Thread. */
  quoteAction?: { onClick: () => void; label: string };
  /** Extra More-menu items owned by the caller, listed before link copy. */
  menuActions?: Array<{ key: string; label: string; icon: ReactNode; onSelect: () => void; disabled?: boolean }>;
  /** The caller owns reaction persistence; the toolbar owns its trigger and placement. */
  reactionAction?: { label: string; open: boolean; onOpenChange: (open: boolean) => void; disabled?: boolean; content: ReactNode };
  /** When provided, the More menu exposes single-message deletion. The
   *  parent owns confirmation + persistence; the promise keeps the action
   *  bar disabled until the flow resolves. */
  onDelete?: () => Promise<void>;
  /** When provided, render an Edit (Pencil) button (last user message only).
   *  Click is fire-and-forget — the parent owns the inline edit lifecycle. */
  onEdit?: () => void;
  /** When provided, render a Rewind (Undo2) button (user messages only).
   *  Click is fire-and-forget — the parent owns the dialog lifecycle and
   *  signals the loading state via `rewindInFlight`. */
  onRewind?: () => void;
  /** External "rewind in flight" signal — controls icon swap (Undo2 → Loader2)
   *  and bar dim. Owned by the parent because the in-flight period spans the
   *  Preview Dialog's open lifetime + commit, which the bar doesn't manage. */
  rewindInFlight?: boolean;
  /** Per-turn 费用 (USD) — 仅该轮最后一条 assistant 有值, 时间旁显示。 */
  turnMoney?: RegionalMoney;
  turnCostUsd?: number;
  turnCostIsEstimate?: boolean;
  /** User-visible cumulative cost for the surrounding user round. */
  userTurnMoney?: RegionalMoney;
  userTurnCostUsd?: number;
  userTurnCostIsEstimate?: boolean;
  /** Per-turn token/cache 明细。旧消息没有时 tooltip 保持旧文案。 */
  turnUsageDetails?: TurnUsageDetails;
}

// Total time the bar lingers after hover-leave before opacity drops to 0.
// Acts as a debounce — quick re-enters within this window cancel the fade
// without resetting opacity, so the bar stays steady at full visibility.
const LEAVE_DEBOUNCE_MS = 250;

const actionButtonClass = cn(
  CHAT_ICON_BUTTON_CLASS,
  'group h-6 w-6 border-none bg-transparent',
  'enabled:hover:bg-[var(--cmd-palette-item-hover)]',
);
const actionIconClass = cn(
  CHAT_COLOR_TRANSITION_CLASS,
  'text-[var(--cmd-palette-item-meta)] group-hover:text-[var(--msg-assistant-text)]',
);

export function MessageActionBar({
  createdAt,
  copyText,
  copyLinkText,
  align,
  hovered,
  simplifiedBotConversation = false,
  readAloudMessage,
  compact = false,
  onFork,
  onAddToChat,
  onShareAsImage,
  replyAction,
  quoteAction,
  menuActions,
  reactionAction,
  onDelete,
  onEdit,
  onRewind,
  rewindInFlight = false,
  turnMoney,
  turnCostUsd,
  turnCostIsEstimate = false,
  userTurnMoney,
  userTurnCostUsd,
  userTurnCostIsEstimate = false,
  turnUsageDetails,
}: MessageActionBarProps) {
  const { t } = useTranslation();
  const readAloud = useContext(MessageReadAloudContext);
  const [copied, setCopied] = useState(false);
  const [forking, setForking] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  // Radix restores focus to the trigger when a menu closes. Programmatic
  // focus restoration is treated as `:focus-visible` by Chromium even when
  // the user opened/closed the menu with a pointer, leaving an unwanted blue
  // ring behind. Track the latest menu interaction modality so pointer flows
  // can skip restoration while keyboard flows keep their focus indicator.
  const menuInteractionFromPointerRef = useRef(false);
  // Fork has its own visible button. Menu-owned actions still dim and block
  // the whole bar; Fork keeps the More trigger available while it runs.
  const inFlight = forking || deleting || rewindInFlight;
  const moreInFlight = deleting || rewindInFlight;
  // `visible` is the actual opacity driver. It tracks `hovered` with a
  // trailing debounce so the bar fades out smoothly (CSS handles the
  // opacity interpolation from current value, not from 1).
  const [visible, setVisible] = useState(hovered);
  const leaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (hovered) {
      // Hover enter — kill any pending fade-out and snap to visible.
      // CSS transition naturally interpolates from whatever opacity the
      // element currently sits at (mid-fade values are fine).
      if (leaveTimerRef.current) {
        clearTimeout(leaveTimerRef.current);
        leaveTimerRef.current = null;
      }
      setVisible(true);
      return;
    }
    // Hover leave — schedule fade after debounce, but don't change opacity yet.
    if (leaveTimerRef.current) clearTimeout(leaveTimerRef.current);
    leaveTimerRef.current = setTimeout(() => {
      setVisible(false);
      leaveTimerRef.current = null;
    }, LEAVE_DEBOUNCE_MS);
    return () => {
      if (leaveTimerRef.current) {
        clearTimeout(leaveTimerRef.current);
        leaveTimerRef.current = null;
      }
    };
  }, [hovered]);

  // Reset the copy icon on the *next* hover-enter, not on hover-leave.
  // Resetting at leave-time would visually swap ✓ → Copy mid-fade-out
  // (looks like the icon "snapped back"). By tying the reset to the rising
  // edge of `hovered`, the bar fades out still showing ✓, then the next
  // hover starts cleanly with the default Copy icon.
  const prevHoveredRef = useRef(hovered);
  useEffect(() => {
    if (hovered && !prevHoveredRef.current && copied) {
      setCopied(false);
    }
    prevHoveredRef.current = hovered;
  }, [hovered, copied]);

  const handleCopy = useCallback(
    async (e: React.MouseEvent) => {
      e.stopPropagation();
      try {
        await navigator.clipboard.writeText(copyText);
        setCopied(true);
      } catch {
        // Clipboard may be unavailable; fail silently — UX falls back to
        // the user noticing nothing happened.
      }
    },
    [copyText],
  );

  const handleFork = useCallback(
    async () => {
      if (!onFork || forking) return;
      setForking(true);
      try {
        await onFork();
      } catch {
        // useForkAtMessage already maps the error to a user-facing toast.
      } finally {
        // Reset regardless of outcome — caller toasts on failure, and on
        // success we usually navigate away anyway so unmount handles it.
        setForking(false);
      }
    },
    [onFork, forking],
  );

  const handleCopyLink = useCallback(
    async () => {
      if (!copyLinkText) return;
      try {
        await navigator.clipboard.writeText(copyLinkText);
        toast.success(t('chat.messageActionBar.linkCopied'));
      } catch {
        toast.warning(t('chat.messageActionBar.copyLinkFailed'));
      }
    },
    [copyLinkText, t],
  );

  const handleCopyFromMenu = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(copyText);
      toast.success(t('chat.messageActionBar.copied'));
    } catch {
      // Same silent fallback as the visible copy button.
    }
  }, [copyText, t]);

  const handleDelete = useCallback(async () => {
    if (!onDelete || deleting) return;
    setDeleting(true);
    try {
      await onDelete();
    } catch {
      // useDeleteMessage already maps persistence failures to a user-facing toast.
    } finally {
      setDeleting(false);
    }
  }, [deleting, onDelete]);

  const relText = useRelativeTime(createdAt, { hovered });
  const absText = formatAbsolute(createdAt);
  const Icon = copied ? Check : Copy;

  const copyBtn = (
    <Tooltip.Root key="copy">
      <Tooltip.Trigger asChild>
        <button
          type="button"
          onClick={handleCopy}
          disabled={moreInFlight}
          className={actionButtonClass}
          aria-label={t('chat.messageActionBar.copy')}
        >
          <Icon
            size={14}
            strokeWidth={2}
            className={cn(
              'text-[var(--cmd-palette-item-meta)]',
              !copied && 'group-hover:text-[var(--msg-assistant-text)]',
              CHAT_COLOR_TRANSITION_CLASS,
            )}
          />
        </button>
      </Tooltip.Trigger>
      <Tooltip.Content>{t('chat.messageActionBar.copy')}</Tooltip.Content>
    </Tooltip.Root>
  );

  // 分享为图片 — 紧贴复制右侧。点击进入选择模式并预选本条,后续勾选与出口都在
  // 底部操作条上完成(ShareSelectionBar),所以这里是纯 fire-and-forget。
  const shareBtn = onShareAsImage && (
    <Tooltip.Root key="share">
      <Tooltip.Trigger asChild>
        <button
          type="button"
          onClick={(e) => {
            e.stopPropagation();
            onShareAsImage();
          }}
          disabled={inFlight}
          className={actionButtonClass}
          aria-label={t('chat.shareImage.entry')}
        >
          {/* iOS 同款分享形状(托盘 + 上箭头,对应 SF Symbols 的
              square.and.arrow.up);lucide 的 Share2 是三点连线的通用款,不用。 */}
          <Share
            size={14}
            strokeWidth={2}
            className={actionIconClass}
          />
        </button>
      </Tooltip.Trigger>
      <Tooltip.Content>{t('chat.shareImage.entry')}</Tooltip.Content>
    </Tooltip.Root>
  );

  const forkBtn = !simplifiedBotConversation && onFork && (
    <Tooltip.Root key="fork">
      <Tooltip.Trigger asChild>
        <button
          type="button"
          onClick={(e) => {
            e.stopPropagation();
            void handleFork();
          }}
          disabled={inFlight}
          className={actionButtonClass}
          aria-label={t('chat.messageActionBar.fork')}
        >
          {forking ? (
            <Spinner size={14} strokeWidth={2} className="text-[var(--cmd-palette-item-meta)]" />
          ) : (
            <Split
              size={14}
              strokeWidth={2}
              className={actionIconClass}
            />
          )}
        </button>
      </Tooltip.Trigger>
      <Tooltip.Content>{t('chat.messageActionBar.fork')}</Tooltip.Content>
    </Tooltip.Root>
  );

  const replyBtn = (replyAction || (simplifiedBotConversation && onAddToChat)) && (
    <Tooltip.Root key="reply">
      <Tooltip.Trigger asChild>
        <button
          type="button"
          onClick={(event) => {
            event.stopPropagation();
            (replyAction?.onClick ?? onAddToChat)?.();
          }}
          disabled={inFlight}
          className={cn(actionButtonClass, replyAction?.count && 'w-auto min-w-6 gap-1 px-1')}
          aria-label={replyAction?.label ?? t('chat.messageActionBar.reply')}
        >
          {replyAction ? <MessagesSquare size={14} strokeWidth={2} className={actionIconClass} />
            : <ChatReplyIcon size={14} strokeWidth={2} className={actionIconClass} />}
          {!!replyAction?.count && <span className={cn('text-12 tabular-nums', actionIconClass)}>{replyAction.count}</span>}
        </button>
      </Tooltip.Trigger>
      <Tooltip.Content>{replyAction?.label ?? t('chat.messageActionBar.reply')}</Tooltip.Content>
    </Tooltip.Root>
  );

  // 伙伴私聊开了话题按钮时,原来的「回复」(把这条消息引用进输入框)挪到引用位,两者并存。
  const botReplyBtn = !quoteAction && replyAction && simplifiedBotConversation && onAddToChat && (
    <Tooltip.Root key="bot-reply">
      <Tooltip.Trigger asChild>
        <button
          type="button"
          onClick={(event) => {
            event.stopPropagation();
            onAddToChat();
          }}
          disabled={inFlight}
          className={actionButtonClass}
          aria-label={t('chat.messageActionBar.reply')}
        >
          <ChatReplyIcon size={14} strokeWidth={2} className={actionIconClass} />
        </button>
      </Tooltip.Trigger>
      <Tooltip.Content>{t('chat.messageActionBar.reply')}</Tooltip.Content>
    </Tooltip.Root>
  );

  const quoteBtn = quoteAction && (
    <Tip key="quote" text={quoteAction.label}>
      <button
        type="button"
        onClick={(event) => {
          event.stopPropagation();
          quoteAction.onClick();
        }}
        disabled={inFlight}
        className={actionButtonClass}
        aria-label={quoteAction.label}
      >
        <ChatReplyIcon size={14} strokeWidth={2} className={actionIconClass} />
      </button>
    </Tip>
  );

  const reactionBtn = reactionAction && (
    <Popover key="reaction" open={reactionAction.open} onOpenChange={reactionAction.onOpenChange}>
      <Tip text={reactionAction.label}>
        <PopoverTrigger asChild>
          <button type="button" className={actionButtonClass} disabled={inFlight || reactionAction.disabled}
            aria-label={reactionAction.label} onClick={event => event.stopPropagation()}>
            <SmilePlus size={14} strokeWidth={2} className={actionIconClass} />
          </button>
        </PopoverTrigger>
      </Tip>
      <PopoverContent align={align === 'right' ? 'end' : 'start'} className="z-[80] w-fit p-2" aria-label={reactionAction.label}>
        {reactionAction.content}
      </PopoverContent>
    </Popover>
  );

  const timeText = relText && (
    <Tooltip.Root key="time">
      <Tooltip.Trigger asChild>
        <time
          dateTime={createdAt}
          className={cn(
            'inline-flex h-6 items-center text-12 font-normal whitespace-nowrap',
            // Optical adjustment: nudge time text down 0.5px so its visual
            // mid-line aligns with the lucide Copy icon glyph center.
            'relative top-[0.5px]',
            // 视觉分组:user 侧(right)时间在最左、后面跟 4 个操作图标
            // ([copy][fork][edit][more],彼此 gap-0.5=2px 是一组)。时间与图标组
            // 之间额外 +6px(共 8px),让"元信息 | 操作组"两段读起来是独立分组
            // —— 与 assistant 侧 costText 的 ml-1.5 同一间距语言。
            align === 'right' && 'mr-1.5',
            'text-[var(--settings-section-desc)] cursor-default',
          )}
        >
          {relText}
        </time>
      </Tooltip.Trigger>
      {absText && (
        <Tooltip.Content>
          <span className="whitespace-pre-line">{absText}</span>
        </Tooltip.Content>
      )}
    </Tooltip.Root>
  );

  // 用户轮累计优先;没有新字段的历史消息继续显示原始 SDK 分段成本。
  const effectiveTurnMoney =
    turnMoney ??
    (typeof turnCostUsd === 'number' && turnCostUsd > 0
      ? legacyUsdMoney(turnCostUsd)
      : undefined);
  const effectiveUserTurnMoney =
    userTurnMoney ??
    (typeof userTurnCostUsd === 'number' && userTurnCostUsd > 0
      ? legacyUsdMoney(userTurnCostUsd)
      : undefined);
  const displayedMoney = effectiveUserTurnMoney ?? effectiveTurnMoney;
  const displayedCostIsEstimate = effectiveUserTurnMoney
    ? userTurnCostIsEstimate
    : turnCostIsEstimate;
  const isUserTurnTotal = effectiveUserTurnMoney != null;

  // 费用 — 样式与 timeText 完全一致(12px + 同色 + 0.5px 光学修正)。
  // 仅 assistant(align='left')会拿到值;估算值(Codex 折算)表达为 token 价值。
  const turnCostTooltipNode =
    displayedMoney && displayedMoney.amount > 0 && turnUsageDetails ? (
      <span className="whitespace-pre-line">
        {buildTurnUsageTooltipLines({
          details: turnUsageDetails,
          t,
          money: displayedMoney,
          isEstimate: displayedCostIsEstimate,
          ...(isUserTurnTotal ? { title: t('chat.messageActionBar.userTurnCostDetailsTitle') } : {}),
        }).join('\n')}
      </span>
    ) : (
      t(
        displayedCostIsEstimate
          ? 'chat.messageActionBar.turnCostEstimated'
          : 'chat.messageActionBar.turnCost',
      )
    );

  // 时间戳之后那一格的排版口径:与 timeText 同为 12px 次要文本 + 0.5px 光学修正;
  // bar 的 gap-0.5(2px)对两段相邻文本太挤,额外 6px 左距(共 8px)让「时间 | 用量」
  // 读成两个独立信息组。金额与 token 回退共用同一套 —— 换的是内容,不是位置。
  const metaTextClassName = cn(
    'inline-flex h-6 items-center text-12 font-normal whitespace-nowrap',
    'relative top-[0.5px]',
    'ml-1.5',
    'text-[var(--settings-section-desc)] cursor-default',
  );

  const costText = displayedMoney && displayedMoney.amount > 0 && (
    <Tooltip.Root key="cost">
      <Tooltip.Trigger asChild>
        <span className={metaTextClassName}>
          {displayedCostIsEstimate
            ? t('chat.messageActionBar.turnCostEstimatedValue', {
                cost: formatTurnCostMoney(displayedMoney),
              })
            : formatTurnCostMoney(displayedMoney)}
        </span>
      </Tooltip.Trigger>
      <Tooltip.Content>
        {turnCostTooltipNode}
      </Tooltip.Content>
    </Tooltip.Root>
  );

  // 金额缺席时的回退:显示本轮 token 总量。成因可能是网关目录整体不下发价格、
  // 模型不在价表、或订阅估值也 miss —— 对用户都一样,这一格不该因此空着。
  // 钱算不出来不代表用量算不出来:明细由 main 在 turn 结束时落库,与金额同源。
  const tokensText = !(displayedMoney && displayedMoney.amount > 0) &&
    turnUsageDetails &&
    turnUsageDetails.totalTokens > 0 && (
      <Tooltip.Root key="tokens">
        <Tooltip.Trigger asChild>
          <span className={metaTextClassName}>
            {t('chat.messageActionBar.turnTokens', {
              tokens: formatCompactTokens(turnUsageDetails.totalTokens),
            })}
          </span>
        </Tooltip.Trigger>
        <Tooltip.Content>
          <span className="whitespace-pre-line">
            {buildTurnUsageTooltipLines({ details: turnUsageDetails, t }).join('\n')}
          </span>
        </Tooltip.Content>
      </Tooltip.Root>
    );

  // Edit (Pencil) button — last user message only. Enters the inline edit
  // state owned by UserMessage; keep it disabled while any message action is
  // in flight so editing cannot race with Fork's history read or a menu action.
  const editBtn = onEdit && (
    <Tooltip.Root key="edit">
      <Tooltip.Trigger asChild>
        <button
          type="button"
          onClick={(e) => {
            e.stopPropagation();
            onEdit();
          }}
          disabled={inFlight}
          className={actionButtonClass}
          aria-label={t('chat.messageActionBar.edit')}
        >
          <Pencil
            size={14}
            strokeWidth={2}
            className={actionIconClass}
          />
        </button>
      </Tooltip.Trigger>
      <Tooltip.Content>{t('chat.messageActionBar.edit')}</Tooltip.Content>
    </Tooltip.Root>
  );

  // Rewind、链接复制与单条删除收进 More 菜单;普通任务仍在菜单里提供
  // “添加到对话”,伙伴对话则将同一动作外显成“回复”。
  // 面板/行几何遵守 12px container + 8px inner-control 两档圆角。
  const canRewind = Boolean(onRewind);
  const addToChatInMenu = simplifiedBotConversation ? undefined : onAddToChat;
  const moreMenu = (compact || addToChatInMenu || menuActions?.length || copyLinkText || canRewind || onDelete) && (
    <DropdownMenu key="more" open={menuOpen} onOpenChange={setMenuOpen}>
      <DropdownMenuTrigger asChild>
        <Tip text={t('chat.messageActionBar.moreActions')}>
          <button
            type="button"
            onClick={(e) => e.stopPropagation()}
            onPointerDown={() => {
              menuInteractionFromPointerRef.current = true;
            }}
            onKeyDown={() => {
              menuInteractionFromPointerRef.current = false;
            }}
            disabled={moreInFlight}
            className={cn(actionButtonClass, 'data-[state=open]:bg-[var(--cmd-palette-item-hover)]')}
            aria-label={t('chat.messageActionBar.moreActions')}
          >
            {moreInFlight ? (
              <Spinner size={14} strokeWidth={2} className="text-[var(--cmd-palette-item-meta)]" />
            ) : (
              <Ellipsis
                size={14}
                strokeWidth={2}
                className={actionIconClass}
              />
            )}
          </button>
        </Tip>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        align={align === 'left' ? 'start' : 'end'}
        sideOffset={4}
        onPointerDownCapture={() => {
          menuInteractionFromPointerRef.current = true;
        }}
        onPointerDownOutside={() => {
          menuInteractionFromPointerRef.current = true;
        }}
        onKeyDownCapture={() => {
          menuInteractionFromPointerRef.current = false;
        }}
        onCloseAutoFocus={(event) => {
          if (menuInteractionFromPointerRef.current) event.preventDefault();
        }}
        className="min-w-[184px]"
      >
        {compact && (
          <DropdownMenuItem
            onSelect={(event) => {
              event.stopPropagation();
              void handleCopyFromMenu();
            }}
            className={MENU_ITEM_CLASS}
          >
            <Copy size={14} strokeWidth={2} className="shrink-0" />
            {t('chat.messageActionBar.copy')}
          </DropdownMenuItem>
        )}
        {compact && onShareAsImage && (
          <DropdownMenuItem
            onSelect={(event) => {
              event.stopPropagation();
              onShareAsImage();
            }}
            className={MENU_ITEM_CLASS}
          >
            <Share size={14} strokeWidth={2} className="shrink-0" />
            {t('chat.shareImage.entry')}
          </DropdownMenuItem>
        )}
        {addToChatInMenu && (
          <DropdownMenuItem
            onSelect={(event) => {
              event.stopPropagation();
              addToChatInMenu();
            }}
            className={MENU_ITEM_CLASS}
          >
            <MessageSquarePlus size={14} strokeWidth={2} className="shrink-0" />
            {t('chat.quote.addToChat')}
          </DropdownMenuItem>
        )}
        {menuActions?.map((action) => (
          <DropdownMenuItem
            key={action.key}
            disabled={action.disabled}
            onSelect={(event) => {
              event.stopPropagation();
              action.onSelect();
            }}
            className={MENU_ITEM_CLASS}
          >
            {action.icon}
            {action.label}
          </DropdownMenuItem>
        ))}
        {copyLinkText && (
          <DropdownMenuItem
            onSelect={(event) => {
              event.stopPropagation();
              void handleCopyLink();
            }}
            className={MENU_ITEM_CLASS}
          >
            <Link2 size={14} strokeWidth={2} className="shrink-0" />
            {t('chat.messageActionBar.copyLink')}
          </DropdownMenuItem>
        )}
        {canRewind && (
          <DropdownMenuItem
            disabled={rewindInFlight}
            onSelect={(event) => {
              event.stopPropagation();
              if (!rewindInFlight) onRewind?.();
            }}
            className={MENU_ITEM_CLASS}
          >
            <Undo2 size={14} strokeWidth={2} className="shrink-0" />
            {t('chat.messageActionBar.rewind')}
          </DropdownMenuItem>
        )}
        {onDelete && (
          <>
            {(addToChatInMenu || menuActions?.length || copyLinkText || canRewind) && (
              <DropdownMenuSeparator />
            )}
            <DropdownMenuItem
              disabled={deleting}
              onSelect={(event) => {
                event.stopPropagation();
                void handleDelete();
              }}
              variant="danger"
              className={MENU_ITEM_CLASS}
            >
              <Trash2 size={14} strokeWidth={2} className="shrink-0" />
              {t('chat.messageActionBar.delete')}
            </DropdownMenuItem>
          </>
        )}
        {compact && absText && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuLabel className="whitespace-pre-line text-12 font-normal text-[var(--settings-section-desc)]">
              {absText}
            </DropdownMenuLabel>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );

  const canReadAloud = simplifiedBotConversation && readAloudMessage && readAloud?.available
    && readAloud.sessionId === readAloudMessage.sessionId && readAloud.canRead(copyText);
  const reading = canReadAloud && readAloud.messageId === readAloudMessage.messageId;
  const readAloudLabel = t(reading ? 'bots.voiceMode.stopReadAloud' : 'bots.voiceMode.readAloud');
  const readAloudBtn = canReadAloud && (
    <Tooltip.Root key="read-aloud">
      <Tooltip.Trigger asChild>
        <button
          type="button"
          className={actionButtonClass}
          aria-label={readAloudLabel}
          aria-pressed={Boolean(reading)}
          aria-busy={Boolean(reading && readAloud.phase === 'preparing')}
          disabled={readAloud.disabled && !reading}
          onClick={(event) => {
            event.stopPropagation();
            readAloud.toggle(readAloudMessage.messageId, copyText);
          }}
        >
          {reading && readAloud.phase === 'preparing' ? (
            <Spinner size={14} strokeWidth={2} className={actionIconClass} />
          ) : reading ? (
            <Square size={14} strokeWidth={2} className={actionIconClass} />
          ) : (
            <Volume2 size={14} strokeWidth={2} className={actionIconClass} />
          )}
        </button>
      </Tooltip.Trigger>
      <Tooltip.Content>
        {readAloud.disabled && !reading ? t('bots.voiceMode.finishBeforeReadAloud') : readAloudLabel}
      </Tooltip.Content>
    </Tooltip.Root>
  );

  // 普通任务:
  // align='left'  → [copy][share][fork][edit][more][time][cost]
  // align='right' → [time][copy][share][fork][edit][more]   (user)
  // 伙伴对话:[copy][share][reply][more][time] / [time][copy][share][reply][edit][more]
  // 贴在气泡旁(compact,群聊与伙伴私聊):[引用回复][话题][朗读][表情][编辑][more],复制、分享与时间收进 more
  const items = compact
    ? align === 'left' ? [quoteBtn || botReplyBtn, replyBtn, readAloudBtn, reactionBtn, editBtn, moreMenu] : [moreMenu, editBtn, reactionBtn, readAloudBtn, replyBtn, quoteBtn || botReplyBtn]
    : align === 'left'
      ? [
          copyBtn,
          shareBtn,
          forkBtn,
          quoteBtn,
          replyBtn,
          readAloudBtn,
          reactionBtn,
          editBtn,
          moreMenu,
          timeText,
          simplifiedBotConversation ? null : costText || tokensText,
        ]
      : [timeText, copyBtn, shareBtn, forkBtn, quoteBtn, replyBtn, readAloudBtn, reactionBtn, editBtn, moreMenu];

  return (
    <div
      // 操作栏是纯交互件:分享图片的光栅化会按这个标记整条剔除,不进产物。
      {...{ [SHARE_EXCLUDE_ATTR]: '' }}
      className={cn(
        'flex flex-wrap items-center gap-0.5',
        align === 'right' ? 'justify-end' : 'justify-start',
        // 250ms is long enough to perceive the fade without dragging.
        // Hover re-enters mid-fade interpolate from the current opacity
        // (browser CSS transition behavior — no replay from 0).
        'transition-opacity duration-[var(--motion-enter)] ease-[var(--motion-ease-out)] motion-reduce:transition-none',
        simplifiedBotConversation || visible || menuOpen || reactionAction?.open
          ? 'opacity-100'
          : 'opacity-0 pointer-events-none focus-within:opacity-100 focus-within:pointer-events-auto',
        // Menu-owned actions dim the entire bar and block clicks. Fork only
        // disables its own button so More remains available.
        moreInFlight && 'opacity-60 pointer-events-none',
      )}
    >
      {items}
    </div>
  );
}

/**
 * The frame that hangs a compact toolbar beside its message bubble (群聊与伙伴私聊): on the bubble's
 * outer `side`, level with its top, inside the message row so moving the pointer across the gap keeps
 * the row hovered. It shows while the message (`group/message`) is hovered, while keyboard focus is
 * inside, while `open` (a picker) is set, and always on touch screens. The bubble must be `relative`.
 */
export function BubbleHoverToolbar({ side, open = false, besideReactions = false, marker, children }: {
  side: 'left' | 'right'; open?: boolean;
  /** Steps past reactions hung on the bubble's outer top corner. */
  besideReactions?: boolean;
  /** A data attribute that names this toolbar for its caller's tests and checks. */
  marker?: `data-${string}`;
  children: ReactNode;
}) {
  const left = side === 'left';
  return (
    <div {...{ [SHARE_EXCLUDE_ATTR]: '' }} {...(marker ? { [marker]: '' } : {})} data-open={open ? '' : undefined}
      className={cn('pointer-events-none absolute top-0 z-10 w-max rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-0.5 opacity-0 transition-opacity duration-[var(--motion-fast)] ease-[var(--motion-ease-out)] focus-within:pointer-events-auto focus-within:opacity-100 group-hover/message:pointer-events-auto group-hover/message:opacity-100 data-[open]:pointer-events-auto data-[open]:opacity-100 motion-reduce:transition-none [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100',
        left ? 'right-full' : 'left-full', besideReactions ? (left ? 'mr-6' : 'ml-6') : (left ? 'mr-1.5' : 'ml-1.5'))}>
      {children}
    </div>
  );
}