import { ActionBarPrimitive, AuiIf, MessagePrimitive, useAuiState, useMessagePartText, } from "@assistant-ui/react"; import { useAtomValue } from "jotai"; import { CheckIcon, CopyIcon, Pencil } from "lucide-react"; import Image from "next/image"; import { type FC, useState } from "react"; import { currentThreadAtom } from "@/atoms/chat/current-thread.atom"; import { messageDocumentsMapAtom } from "@/atoms/chat/mentioned-documents.atom"; import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button"; import { getConnectorIcon } from "@/contracts/enums/connectorIcons"; import { getMentionDocKey } from "@/lib/chat/mention-doc-key"; import { parseMentionSegments } from "@/lib/chat/parse-mention-segments"; interface AuthorMetadata { displayName: string | null; avatarUrl: string | null; } const UserAvatar: FC = ({ displayName, avatarUrl }) => { const [hasError, setHasError] = useState(false); const initials = displayName ? displayName .split(" ") .map((n) => n[0]) .join("") .toUpperCase() .slice(0, 2) : "U"; if (avatarUrl && !hasError) { return ( {displayName setHasError(true)} unoptimized /> ); } return (
{initials}
); }; const UserTextPart: FC = () => { const messageId = useAuiState(({ message }) => message?.id); const part = useMessagePartText(); const text = (part as { text?: string }).text ?? ""; const messageDocumentsMap = useAtomValue(messageDocumentsMapAtom); const mentionedDocs = (messageId ? messageDocumentsMap[messageId] : undefined) ?? []; const segments = parseMentionSegments(text, mentionedDocs); return (

{segments.map((segment) => segment.type === "text" ? ( {segment.value} ) : ( {getConnectorIcon(segment.doc.document_type ?? "UNKNOWN", "h-3 w-3")} {segment.doc.title} ) )}

); }; const userMessageParts = { Text: UserTextPart }; export const UserMessage: FC = () => { const metadata = useAuiState(({ message }) => message?.metadata); const author = metadata?.custom?.author as AuthorMetadata | undefined; const isSharedChat = useAtomValue(currentThreadAtom).visibility === "SEARCH_SPACE"; const showAvatar = isSharedChat && !!author; return (
{showAvatar && (
)}
); }; const UserActionBar: FC = () => { const isThreadRunning = useAuiState(({ thread }) => thread.isRunning); // Get current message ID const currentMessageId = useAuiState(({ message }) => message?.id); // Find the last user message ID in the thread (computed once, memoized by selector) const lastUserMessageId = useAuiState(({ thread }) => { const messages = thread.messages; for (let i = messages.length - 1; i >= 0; i--) { if (messages[i].role === "user") { return messages[i].id; } } return null; }); // Simple comparison - no iteration needed per message const isLastUserMessage = currentMessageId === lastUserMessageId; // Show edit button only on the last user message and when thread is not running const canEdit = isLastUserMessage && !isThreadRunning; return ( message.isCopied}> !message.isCopied}> {canEdit && ( )} ); };