import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode, } from "react"; import { Activity, Check, ChevronRight, CircleAlert, Clock3, Copy, Link2, Quote, Wrench } from "lucide-react"; import { useTranslation } from "react-i18next"; import { DisclosureContent } from "@/components/ui/disclosure"; import { AttachmentTile } from "@/components/AttachmentTile"; import { SessionHandleLabel } from "@/components/SessionHandleLabel"; import { FallbackResponseSources } from "@/components/ResponseSourceBadge"; import { ImageGallery } from "@/components/ImageGallery"; import { InlineImageProvider, useInlineImages } from "@/components/InlineImageContext"; import { MarkdownText } from "@/components/MarkdownText"; import { SlashCommandText } from "@/components/SlashCommandText"; import { ReasoningRow } from "@/components/thread/activity/ReasoningRow"; import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen"; import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice"; import { UserMessageText } from "@/components/UserMessageText"; import { HoverHint } from "@/components/ui/tooltip"; import { cn } from "@/lib/utils"; import { copyTextToClipboard } from "@/lib/clipboard"; import { formatMessageEndTime } from "@/lib/format-time"; import { toMediaAttachment } from "@/lib/media"; import { matchingSlashCommand } from "@/lib/slash-command"; import { sessionHandleColor } from "@/lib/session-handle"; import { parseQuotedUserMessage } from "@/lib/user-message-quote"; import type { CliAppInfo, McpPresetInfo, SlashCommand, UICliAppAttachment, UIMcpPresetAttachment, UIImage, UIMediaAttachment, UIMessage, MessageDeliveryErrorKind, MessageDeliveryStatus, } from "@/lib/types"; interface MessageBubbleProps { message: UIMessage; /** Give temporary-chat user turns the dashed private-mode treatment. */ temporary?: boolean; cliApps?: CliAppInfo[]; mcpPresets?: McpPresetInfo[]; slashCommands?: SlashCommand[]; onOpenFilePreview?: (path: string) => void; /** Context-menu trigger positioned against this message's visual block. */ contextMenu?: ReactNode; } function ForkArrowIcon({ className }: { className?: string }) { return ( ); } function useMessageCopy(content: string) { const { t } = useTranslation(); const [copied, setCopied] = useState(false); const copyResetRef = useRef(null); useEffect(() => { return () => { if (copyResetRef.current !== null) { window.clearTimeout(copyResetRef.current); } }; }, []); const onCopy = useCallback(() => { void copyTextToClipboard(content).then((ok) => { if (!ok) return; setCopied(true); if (copyResetRef.current !== null) { window.clearTimeout(copyResetRef.current); } copyResetRef.current = window.setTimeout(() => { setCopied(false); copyResetRef.current = null; }, 1_500); }); }, [content]); const label = copied ? t("message.copiedReply") : t("message.copyReply"); return { copied, label, onCopy }; } function messageCopyContent(message: UIMessage, t: (key: string) => string) { return message.role === "assistant" && message.compactReply === "empty" ? t("thread.compaction.empty") : message.role === "assistant" && message.compactReply === "failed" ? t("thread.compaction.failed") : message.content; } /** The same copy behavior in the desktop menu and the mobile reply footer. */ export function MessageCopyButton({ message, className }: { message: UIMessage; className?: string }) { const { t } = useTranslation(); const content = messageCopyContent(message, t); const { copied, label, onCopy } = useMessageCopy(content); if (!content.trim()) return null; return ; } interface MessageBlockMenuActivity { label: string; expanded: boolean; controls: string; onToggle: () => void; } interface MessageBlockMenuActionsProps { message: UIMessage; isTurnStreaming?: boolean; onForkFromHere?: () => void; activity?: MessageBlockMenuActivity; onViewLinks?: () => void; sheet?: boolean; } /** Actions and metadata shown after opening a visual message block's context panel. */ export function MessageBlockMenuActions({ message, isTurnStreaming = false, onForkFromHere, activity, onViewLinks, sheet = false, }: MessageBlockMenuActionsProps) { const { t } = useTranslation(); const content = messageCopyContent(message, t); const hasText = content.trim().length > 0; const showFork = message.role === "assistant" && !message.isStreaming && !isTurnStreaming && hasText && onForkFromHere !== undefined; const timestamp = message.role === "assistant" && typeof message.completedAt === "number" && Number.isFinite(message.completedAt) ? message.completedAt : message.createdAt; const timestampLabel = typeof timestamp === "number" && Number.isFinite(timestamp) ? formatMessageEndTime(timestamp) : ""; const automationSourceLabel = message.role === "assistant" && ["cron", "local_trigger", "trigger"].includes(message.source?.kind ?? "") ? message.source?.label?.trim() || t("message.automationSourceFallback") : ""; return (
{(!sheet && hasText) || showFork || activity ? (
{(!sheet && hasText) || showFork ? (
{!sheet && hasText ? : null} {showFork ? ( ) : null}
) : null} {activity ? ( ) : null}
) : null} {onViewLinks ? : null} {timestampLabel || automationSourceLabel ? (
{timestampLabel ? ( ) : null} {automationSourceLabel ? ( {t("message.automationTriggered")}{" "} {automationSourceLabel} ) : null}
) : null}
); } function deliveryErrorCopy( kind: MessageDeliveryErrorKind | undefined, t: (key: string) => string, ): { title: string; body: string } { switch (kind) { case "message_too_big": return { title: t("errors.messageTooBig.title"), body: t("errors.messageTooBig.body"), }; case "workspace_scope_rejected": return { title: t("errors.workspaceScopeRejected.title"), body: t("errors.workspaceScopeRejected.body"), }; case "turn_rejected": case undefined: return { title: t("errors.turnRejected.title"), body: t("errors.turnRejected.body"), }; default: { const _exhaustive: never = kind; return { title: String(_exhaustive), body: "" }; } } } function UserDeliveryStatus({ status, errorKind, }: { status: MessageDeliveryStatus | undefined; errorKind: MessageDeliveryErrorKind | undefined; }) { const { t } = useTranslation(); if (status !== "sending" && status !== "failed") return null; if (status === "sending") { return ( {t("message.delivery.sending")} ); } const label = t("message.delivery.failed"); const { title, body } = deliveryErrorCopy(errorKind, t); return ( <>

{title}

{body}

} >
{title}. {body} ); } function IncomingSessionMessage({ message, contextMenu, onOpenFilePreview, }: { message: UIMessage; contextMenu?: ReactNode; onOpenFilePreview?: (path: string) => void; }) { const handle = message.sessionMessage!.session; const color = sessionHandleColor(handle.id); const handleName = `@${handle.name}`; return (
{contextMenu}
{handleName}
{message.content}
); } /** Render user turns as compact bubbles and assistant turns as document-like prose. */ export function MessageBubble({ message, temporary = false, cliApps = [], mcpPresets = [], slashCommands = [], onOpenFilePreview, contextMenu, }: MessageBubbleProps) { const { t } = useTranslation(); const mentionCliApps = useMemo( () => mergeCliMentionApps(cliApps, message.cliApps), [cliApps, message.cliApps], ); const mentionMcpPresets = useMemo( () => mergeMcpMentionPresets(mcpPresets, message.mcpPresets), [mcpPresets, message.mcpPresets], ); if (message.kind === "compaction" && message.compaction) { return ; } if (message.kind === "trace") { return ; } if (message.role === "user" && message.sessionMessage) { return ( ); } if (message.role === "user") { const images = message.images ?? []; const media = message.media ?? []; const hasImages = images.length > 0; const hasMedia = media.length > 0; const parsedMessage = parseQuotedUserMessage(message.content); const userContent = parsedMessage.content; const hasText = userContent.trim().length > 0; const showDeliveryStatus = message.deliveryStatus === "sending" || message.deliveryStatus === "failed"; const quotedContext = parsedMessage.quotedContext; const slashCommand = matchingSlashCommand(userContent, slashCommands); const messageText = slashCommand ? ( <> ) : ( ); return (
{contextMenu} {hasImages ? : null} {!hasImages && hasMedia ? ( ) : null} {quotedContext ? ( ) : null} {hasText ? (

{messageText}

) : null} {showDeliveryStatus ? (
) : null}
); } const assistantContent = message.compactReply === "empty" ? t("thread.compaction.empty") : message.compactReply === "failed" ? t("thread.compaction.failed") : message.content; const empty = assistantContent.trim().length === 0; const media = message.media ?? []; const reasoning = message.role === "assistant" ? message.reasoning ?? "" : ""; const reasoningStreaming = !!(message.role === "assistant" && message.reasoningStreaming); const hasReasoning = reasoning.length > 0 || reasoningStreaming; return (
{contextMenu} {hasReasoning ? ( ) : null} {empty && message.isStreaming && !hasReasoning ? ( ) : empty && message.isStreaming ? null : (
{/* A mode switch rebuilds Streamdown's subtree and moves the scroll anchor. */} {assistantContent}
{media.length > 0 ? : null}
)}
); } function UserQuotedContext({ text, label }: { text: string; label: string }) { return (

{text}

); } function mergeMcpMentionPresets( presets: McpPresetInfo[], attachments: UIMcpPresetAttachment[] | undefined, ): McpPresetInfo[] { if (!attachments?.length) return presets; const byName = new Map(presets.map((preset) => [preset.name.toLowerCase(), preset])); for (const attachment of attachments) { const name = attachment.name?.trim(); if (!name) continue; const existing = byName.get(name.toLowerCase()); byName.set(name.toLowerCase(), { name, display_name: attachment.display_name || existing?.display_name || name, category: attachment.category || existing?.category || "mcp", description: existing?.description || "", docs_url: existing?.docs_url || "", transport: attachment.transport || existing?.transport || "mcp", requires: existing?.requires || "", note: existing?.note || "", install_supported: existing?.install_supported ?? true, installed: true, configured: attachment.configured ?? existing?.configured ?? true, available: existing?.available ?? true, status: attachment.status || existing?.status || "configured", logo_url: attachment.logo_url ?? existing?.logo_url ?? null, brand_color: attachment.brand_color ?? existing?.brand_color ?? null, required_fields: existing?.required_fields || [], connection_summary: existing?.connection_summary || "", }); } return Array.from(byName.values()); } function mergeCliMentionApps( cliApps: CliAppInfo[], attachments: UICliAppAttachment[] | undefined, ): CliAppInfo[] { if (!attachments?.length) return cliApps; const byName = new Map(cliApps.map((app) => [app.name.toLowerCase(), app])); for (const attachment of attachments) { const name = attachment.name?.trim(); if (!name) continue; const existing = byName.get(name.toLowerCase()); byName.set(name.toLowerCase(), { name, display_name: attachment.display_name || existing?.display_name || name, category: attachment.category || existing?.category || "cli", description: existing?.description || "", requires: existing?.requires || "", source: existing?.source || "attached", entry_point: attachment.entry_point || existing?.entry_point || "", install_supported: existing?.install_supported ?? true, installed: true, available: existing?.available ?? true, status: existing?.status || "installed", logo_url: attachment.logo_url ?? existing?.logo_url ?? null, brand_color: attachment.brand_color ?? existing?.brand_color ?? null, skill_installed: existing?.skill_installed ?? true, }); } return Array.from(byName.values()); } function MessageMedia({ media, align, }: { media: UIMediaAttachment[]; align: "left" | "right"; }) { const inlineImages = useInlineImages(); if (media.length === 0) return null; const images: UIImage[] = []; const seen = new Set(); const nonImages: UIMediaAttachment[] = []; for (const item of media) { const normalized = toMediaAttachment(item); if (normalized.kind === "image") { if (normalized.url && (inlineImages.has(normalized.url) || seen.has(normalized.url))) continue; if (normalized.url) seen.add(normalized.url); images.push({ url: normalized.url, name: normalized.name }); } else { nonImages.push(normalized); } } if (images.length === 0 && nonImages.length === 0) return null; return (
{images.length > 0 ? ( ) : null} {nonImages.map((item, i) => ( ))}
); } /** Quiet pre-token state that occupies a stable line in the answer column. */ function ThinkingState() { const { t } = useTranslation(); return ( {t("message.reasoningStreaming", { defaultValue: "Thinking…" })} ); } interface ReasoningBubbleProps { text: string; streaming: boolean; hasBodyBelow: boolean; } function ReasoningBubble({ text, streaming, hasBodyBelow, }: ReasoningBubbleProps) { return ( ); } interface TraceGroupProps { message: UIMessage; } /** * Collapsible group of tool-call / progress breadcrumbs. Defaults to * collapsed because tool traces are supporting evidence, not the answer. * A single click expands the exact calls when the user wants details. */ function TraceGroup({ message }: TraceGroupProps) { const { t } = useTranslation(); const lines = message.traces ?? [message.content]; const count = lines.length; const [open, setOpen] = useState(false); const [hasOpened, setHasOpened] = useState(false); const releaseContent = useCallback(() => setHasOpened(false), []); const contentId = useId(); return (
{hasOpened &&
    {lines.map((line, i) => (
  • {line}
  • ))}
}
); }