Message Actions
A compact row under a chat message. Copy turns the Markdown into plain text and can add formatted HTML; the send time reads as Today, Yesterday, or a date; assistant replies can be rated and regenerated. Message Branch steps between regenerated versions.
Installation
pnpm dlx shadcn@latest add https://sprout.tulipfarm.ai/r/message-actions.jsonCopies Message Actions and the components it uses (Button, Hover Card, and Tooltip) into your app, installs the packages, and adds the styles. Then import it from @/components/ui/message-actions. Needs Tailwind CSS 4 and a components.json from shadcn init.
Install the following dependencies:
pnpm add clsx tailwind-merge @hugeicons/core-free-icons @hugeicons/reactAdd Sprout base once per app: the
cn()helper and the design tokens.lib/sprout/classes.ts- Design tokens, for your global CSS
Add the components it uses: Button, Hover Card, and Tooltip.
Copy and paste the following code into your project.
'use client'; import { useEffect, useState, type ComponentProps, type ReactNode } from 'react'; import { CheckIcon } from '@/lib/sprout/icons/check-icon'; import { ChevronLeftIcon } from '@/lib/sprout/icons/chevron-left-icon'; import { ChevronRightIcon } from '@/lib/sprout/icons/chevron-right-icon'; import { CopyIcon } from '@/lib/sprout/icons/copy-icon'; import { RotateRightIcon } from '@/lib/sprout/icons/rotate-right-icon'; import { ThumbsDownIcon } from '@/lib/sprout/icons/thumbs-down-icon'; import { ThumbsUpIcon } from '@/lib/sprout/icons/thumbs-up-icon'; import { cn } from '@/lib/sprout/classes'; import { Button } from '@/components/ui/button'; import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card'; import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'; export const messageActionsAuthorNames = ['assistant', 'human'] as const; export type MessageActionsAuthor = (typeof messageActionsAuthorNames)[number]; export type MessageFeedback = 'up' | 'down'; export interface MessageActionsStats { model?: string | undefined; firstTokenMs?: number | undefined; durationMs?: number | undefined; inputTokens?: number | undefined; outputTokens?: number | undefined; traceId?: string | undefined; } export interface MessageActionsProps { text: string; author?: MessageActionsAuthor; createdAt?: string | undefined; stats?: MessageActionsStats | undefined; html?: (() => string | undefined) | undefined; hover?: boolean; feedback?: MessageFeedback | null | undefined; onFeedback?: ((value: MessageFeedback | null) => void) | undefined; onRetry?: (() => void) | undefined; disabled?: boolean; className?: string | undefined; } const markdownLink = /\[([^\]]*)\]\(<?([^)\s>]+)>?(?:\s+"[^"]*")?\)/g; function plainTextFromMarkdown(markdown: string) { return markdown .replace(markdownLink, (_, label: string, url: string) => (!label || label === url ? url : `${label} (${url})`)) .replace(/<(https?:\/\/[^>\s]+)>/g, '$1'); } function formatDate(options: Intl.DateTimeFormatOptions, date: Date) { return Number.isNaN(date.getTime()) ? date.toString() : new Intl.DateTimeFormat([], options).format(date); } const startOfDay = (date: Date) => new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime(); function messageTime(iso: string, now = new Date()) { const date = new Date(iso); const time = formatDate({ hour: 'numeric', minute: '2-digit' }, date); const days = Math.round((startOfDay(now) - startOfDay(date)) / 86_400_000); if (days === 0) return time; if (days === 1) return `Yesterday ${time}`; const day = formatDate( date.getFullYear() === now.getFullYear() ? { month: 'short', day: 'numeric' } : { month: 'short', day: 'numeric', year: 'numeric' }, date, ); return `${day}, ${time}`; } function formatDuration(ms: number) { if (ms < 1000) return `${Math.round(ms)} ms`; if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`; return `${Math.floor(ms / 60_000)} min ${Math.round((ms % 60_000) / 1000)} s`; } const formatCount = (value: number) => new Intl.NumberFormat().format(value); function statRows(stats: MessageActionsStats) { const rows: [string, ReactNode][] = []; const { model, firstTokenMs, durationMs, inputTokens, outputTokens, traceId } = stats; if (model) rows.push(['Model', model]); if (firstTokenMs !== undefined) rows.push(['First word', formatDuration(firstTokenMs)]); if (durationMs !== undefined) rows.push(['Total time', formatDuration(durationMs)]); if (inputTokens !== undefined || outputTokens !== undefined) rows.push([ 'Tokens', [ inputTokens !== undefined && `${formatCount(inputTokens)} in`, outputTokens !== undefined && `${formatCount(outputTokens)} out`, ] .filter(Boolean) .join(' · '), ]); const writingMs = durationMs !== undefined ? durationMs - (firstTokenMs ?? 0) : 0; if (outputTokens !== undefined && writingMs > 0) rows.push(['Speed', `${formatCount(Math.round(outputTokens / (writingMs / 1000)))} tokens/s`]); if (traceId) rows.push(['Trace', <code className="sprout-message-actions-trace">{traceId}</code>]); return rows; } function MessageTime({ createdAt, stats, align, }: { createdAt: string; stats?: MessageActionsStats | undefined; align: 'start' | 'end'; }) { const rows = stats ? statRows(stats) : []; return ( <HoverCard> <HoverCardTrigger delay={300} closeDelay={150} render={<time tabIndex={0} dateTime={createdAt} className="sprout-message-actions-time" />} > {messageTime(createdAt)} </HoverCardTrigger> <HoverCardContent side="top" align={align} className="sprout-message-actions-stats"> <p className="sprout-message-actions-stats-date"> {formatDate({ dateStyle: 'full', timeStyle: 'medium' }, new Date(createdAt))} </p> {rows.length > 0 && ( <dl> {rows.map(([label, value]) => ( <div key={label}> <dt>{label}</dt> <dd>{value}</dd> </div> ))} </dl> )} </HoverCardContent> </HoverCard> ); } function ActionButton({ label, ...props }: ComponentProps<typeof Button> & { label: string }) { return ( <Tooltip> <TooltipTrigger delay={400} render={<Button variant="ghost" size="icon-sm" {...props} />} /> <TooltipContent side="bottom">{label}</TooltipContent> </Tooltip> ); } export function MessageActions({ text, author = 'assistant', createdAt, stats, html, hover = false, feedback, onFeedback, onRetry, disabled = false, className, }: MessageActionsProps) { const [copy, setCopy] = useState<'idle' | 'copied' | 'error'>('idle'); const noun = author === 'human' ? 'message' : 'response'; const Noun = author === 'human' ? 'Message' : 'Response'; const copyText = async () => { const plain = plainTextFromMarkdown(text); const rich = html?.(); try { if (rich && typeof ClipboardItem !== 'undefined') await navigator.clipboard.write([ new ClipboardItem({ 'text/html': new Blob([rich], { type: 'text/html' }), 'text/plain': new Blob([plain], { type: 'text/plain' }), }), ]); else await navigator.clipboard.writeText(plain); setCopy('copied'); } catch { setCopy('error'); } }; useEffect(() => { if (copy !== 'copied') return; const timer = setTimeout(() => setCopy('idle'), 2000); return () => clearTimeout(timer); }, [copy]); const rate = (value: MessageFeedback) => onFeedback?.(feedback === value ? null : value); return ( <div data-slot="message-actions" data-author={author} data-hover={hover ? '' : undefined} className={cn('sprout-message-actions', className)} > <div role="group" aria-label={`${Noun} actions`} data-hover={hover ? '' : undefined} className="sprout-message-actions-row" > <ActionButton label={copy === 'copied' ? 'Copied' : 'Copy'} disabled={disabled} aria-label={copy === 'copied' ? `${Noun} copied` : `Copy ${noun}`} data-copied={copy === 'copied' ? '' : undefined} onClick={() => void copyText()} > {copy === 'copied' ? <CheckIcon size="md" aria-hidden="true" /> : <CopyIcon size="md" aria-hidden="true" />} </ActionButton> {onFeedback && ( <> <ActionButton label="Helpful" disabled={disabled} aria-label="Helpful response" aria-pressed={feedback === 'up'} onClick={() => rate('up')} > <ThumbsUpIcon size="md" aria-hidden="true" /> </ActionButton> <ActionButton label="Unhelpful" disabled={disabled} aria-label="Unhelpful response" aria-pressed={feedback === 'down'} onClick={() => rate('down')} > <ThumbsDownIcon size="md" aria-hidden="true" /> </ActionButton> </> )} {onRetry && ( <ActionButton label="Regenerate" disabled={disabled} aria-label="Regenerate response" onClick={onRetry}> <RotateRightIcon size="md" aria-hidden="true" /> </ActionButton> )} {createdAt && <MessageTime createdAt={createdAt} stats={stats} align={author === 'human' ? 'end' : 'start'} />} </div> {copy === 'error' && ( <p role="alert" className="sprout-message-actions-error"> Couldn't copy. Select the {noun} text or try again. </p> )} <span role="status" className="sprout-message-actions-sr-only"> {copy === 'copied' ? `${Noun} copied to clipboard.` : ''} </span> </div> ); } export interface MessageBranchProps { index: number; total: number; onChange: (index: number) => void; className?: string | undefined; } export function MessageBranch({ index, total, onChange, className }: MessageBranchProps) { return ( <div data-slot="message-branch" role="group" aria-label="Response versions" className={cn('sprout-message-branch', className)} > <Button variant="ghost" size="icon-sm" aria-label="Previous response" disabled={index <= 0} onClick={() => onChange(index - 1)} > <ChevronLeftIcon size="sm" aria-hidden="true" /> </Button> <span aria-live="polite" className="sprout-message-branch-count"> {index + 1} / {total} </span> <Button variant="ghost" size="icon-sm" aria-label="Next response" disabled={index >= total - 1} onClick={() => onChange(index + 1)} > <ChevronRightIcon size="sm" aria-hidden="true" /> </Button> </div> ); }And the files it imports:
lib/sprout/icons/check-icon.tsxlib/sprout/icons/chevron-left-icon.tsxlib/sprout/icons/chevron-right-icon.tsxlib/sprout/icons/copy-icon.tsxlib/sprout/icons/create-icon.tsxlib/sprout/icons/rotate-right-icon.tsxlib/sprout/icons/thumbs-down-icon.tsxlib/sprout/icons/thumbs-up-icon.tsx
Add the styles to your global CSS, after
@import "tailwindcss".@layer components { .sprout-message-actions { min-width: 0; font-family: var(--sprout-font); flex-direction: column; gap: 4px; display: flex; } .sprout-message-actions-row { flex-wrap: wrap; align-items: center; gap: 4px; min-width: 0; display: flex; } .sprout-message-actions[data-author="human"] .sprout-message-actions-row { justify-content: flex-end; } .sprout-message-actions-row[data-hover] { opacity: 0; transition: opacity var(--sprout-motion-fast) var(--sprout-motion-ease); } .sprout-message:hover .sprout-message-actions-row[data-hover], .sprout-message:focus-within .sprout-message-actions-row[data-hover], .sprout-message-actions-row[data-hover]:focus-within { opacity: 1; } @media (hover: none) { .sprout-message-actions-row[data-hover] { opacity: 1; } } .sprout-message-content > .sprout-message-actions[data-hover] { margin-top: calc(4px - var(--sprout-message-content-gap)); } @media (prefers-reduced-motion: reduce) { .sprout-message-actions-row[data-hover] { transition: none; } } :is(.sprout-message-actions-row) { gap: 2px; } .sprout-message-actions-row > .sprout-button { color: var(--sprout-muted); } .sprout-message-actions-row > .sprout-button:hover, .sprout-message-actions-row > .sprout-button[aria-pressed="true"] { color: var(--sprout-text); } .sprout-message-actions-row > .sprout-button[aria-pressed="true"] { background: color-mix(in oklab, var(--sprout-text) 8%, transparent); } .sprout-message-actions-time { color: var(--sprout-muted); font-size: var(--sprout-text-xs); font-variant-numeric: tabular-nums; white-space: nowrap; cursor: default; border-radius: 6px; margin-inline-start: 4px; padding: 2px 4px; line-height: 1rem; } .sprout-message-actions-time:hover, .sprout-message-actions-time[data-popup-open] { color: var(--sprout-text); } .sprout-message-actions-time:focus-visible { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: 0; } .sprout-hover-card-content.sprout-message-actions-stats { width: auto; min-width: 14rem; max-width: min(22rem, var(--available-width)); font-size: var(--sprout-text-xs); padding: 10px 12px; line-height: 1rem; } .sprout-message-actions-stats-date { color: var(--sprout-text); margin: 0; font-weight: 500; } .sprout-message-actions-stats dl { border-top: 1px solid var(--sprout-line); grid-template-columns: auto minmax(0, 1fr); gap: 4px 16px; margin: 8px 0 0; padding-top: 8px; display: grid; } .sprout-message-actions-stats dl > div { display: contents; } .sprout-message-actions-stats dt { color: var(--sprout-muted); } .sprout-message-actions-stats dd { color: var(--sprout-text); font-variant-numeric: tabular-nums; text-align: end; overflow-wrap: anywhere; margin: 0; } .sprout-message-actions-trace { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: inherit; user-select: all; } .sprout-message-actions-error { color: var(--sprout-danger); font-size: var(--sprout-text-sm); margin: 0; line-height: 1.25rem; } .sprout-message-actions-sr-only { clip-path: inset(50%); white-space: nowrap; border: 0; width: 1px; height: 1px; margin: -1px; padding: 0; position: absolute; overflow: hidden; } .sprout-message-branch { color: var(--sprout-muted); font-family: var(--sprout-font); font-size: var(--sprout-text-xs); align-items: center; gap: 4px; line-height: 1rem; display: inline-flex; } .sprout-message-branch-count { text-align: center; font-variant-numeric: tabular-nums; min-width: 2.5rem; } }Import it from
@/components/ui/message-actions. Update the paths if your@/alias points elsewhere.
pnpm add @tulipfarm/sprout@import "tailwindcss";
@import "@tulipfarm/sprout/styles.css";The package keeps the source and ships fixes with each release. Import from @tulipfarm/sprout/message-actions.
Usage
import { MessageActions } from "@tulipfarm/sprout/message-actions";
<MessageActions
text={message.text}
createdAt={message.createdAt}
feedback={message.feedback}
onFeedback={(value) => rate(message.id, value)}
onRetry={() => regenerate(message.id)}
stats={{ model: message.model, firstTokenMs: 640, durationMs: 4200, outputTokens: 214 }}
/>Only text is required, which shows a single Copy button. Each other prop adds one part: createdAt the time at the end of the row,onFeedback the Helpful and Unhelpful toggles,onRetry a Regenerate button, and stats reply details on the time. There are no visual variants; every action is a ghost icon-sm button with a tooltip, and a given rating is tinted.
author names the controls: "assistant" (the default) says “response”, "human" says “message”.disabled turns off every button, for example while a reply is still running.
In a conversation
const entry = useRef<HTMLDivElement>(null);
<Message align={message.author === "human" ? "end" : "start"}>
<MessageContent ref={entry}>
{bubbles}
<MessageActions
text={text}
author={message.author}
createdAt={message.createdAt}
hover
html={() => {
const parts = entry.current?.querySelectorAll("[data-slot=message-bubble]");
return parts?.length ? [...parts].map((part) => part.innerHTML).join("") : undefined;
}}
/>
</MessageContent>
</Message>With hover, the row stays hidden until the pointer is over the surrounding Message or anything in it has focus. On touch screens it is always shown. html runs when Copy is pressed; when it returns markup, the clipboard gets both HTML and plain text, so pasting into a document keeps bold, code, and links.
Send time
createdAt is an ISO time shown in the reader’s locale and time zone. Hovering or focusing it opens a card with the full date and time. Pass stats to add the reply’s model, time to first token, total time, tokens in and out, speed, and trace ID. Every field is optional and a missing one is left out.
Versions
import { MessageActions, MessageBranch } from "@tulipfarm/sprout/message-actions";
<MessageBranch index={index} total={versions.length} onChange={setIndex} />
<MessageActions text={versions[index].text} onRetry={regenerate} />index is zero-based and shown as “2 / 3”. Previous is disabled on the first version and Next on the last.
Copy only
Pass just text under text that is not a chat turn, such as a written handoff in a dialog.
States
After a copy the icon becomes a check and its label says it was copied. If the browser refuses the write, a message under the row asks the reader to select the text instead. Choose Blocked to try it; this demo blocks the clipboard only while that option is chosen.
Accessibility
Actions sit in a group named “Response actions” or “Message actions”; versions in a group named “Response versions”. Icon buttons have labels and tooltips, the time is focusable and opens its card on focus, and the ratings are toggle buttons witharia-pressed. A successful copy is announced through a status region and a failed one as an alert. The version count is a polite live region. A hover row becomes visible as soon as keyboard focus enters the message. It fades in over 120ms, or appears at once when reduced motion is set.