Bubble
SaveChat message bubbles for user and assistant with avatars, timestamps, grouping of consecutive messages, and copy and retry actions on hover.
- Category
- AI elements
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Bubble preview
Priya Raman
Can you check why the March invoice for Northwind is off by a cent?Priya Raman
Their finance team flagged it this morning.Billing agent
Found it. Proration rounds each line item before adding them up, so two half cents both round down. The invoice shows $12.33 instead of $12.34.Billing agent
I can change it to round once after the sum and reissue the invoice as a correction. Want me to open a pull request?Priya Raman
Yes, and add a test for the half cent case.
Installation
npx @shakenui/cli add bubbleReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add bubble --dry-runUsage
bubble-example.tsx
"use client";
import { BubbleList, type ChatMessage } from "@/components/shaken/agent/bubble";
const at = (minutes: number) => new Date(Date.UTC(2026, 10, 14, 16, minutes));
const messages: ChatMessage[] = [
{ id: "m1", from: "user", author: "Priya Raman", timestamp: at(2), content: "Can you check why the March invoice for Northwind is off by a cent?" },
{ id: "m2", from: "user", author: "Priya Raman", timestamp: at(2), content: "Their finance team flagged it this morning." },
{
id: "m3",
from: "assistant",
author: "Billing agent",
timestamp: at(3),
content:
"Found it. Proration rounds each line item before adding them up, so two half cents both round down. The invoice shows $12.33 instead of $12.34.",
},
{
id: "m4",
from: "assistant",
author: "Billing agent",
timestamp: at(3),
content: "I can change it to round once after the sum and reissue the invoice as a correction. Want me to open a pull request?",
},
{ id: "m5", from: "user", author: "Priya Raman", timestamp: at(5), content: "Yes, and add a test for the half cent case." },
];
const formatTime = (date: Date) => date.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", timeZone: "UTC" });
export default function BubbleExample() {
return <BubbleList messages={messages} formatTime={formatTime} onRetry={() => {}} className="w-full max-w-xl" />;
}API
| Prop | Type | Default | Description |
|---|---|---|---|
| from | "user" | "assistant" | — | User bubbles sit right in a soft tint; assistant bubbles sit left on a hairline. |
| author / avatar | string / string | ReactNode | — | Name above the first bubble of a group, and an image URL or node. Assistants default to an Agent State mark that animates while streaming. |
| timestamp / formatTime | Date | string | number / (date) => string | — | Shown with the name and next to the actions on later bubbles. |
| position | "single" | "first" | "middle" | "last" | "single" | Place in a run from one sender; tightens corners and hides the repeated avatar. |
| status | "sending" | "streaming" | "complete" | "failed" | "complete" | Streaming with no content shows Thinking; failed shows the error and a resend or retry action. |
| copyText / onRetry / actions | string / () => void / ReactNode | — | The hover actions. Copy uses the string children by default. |
| BubbleList | ({ messages, windowMs?, onRetry?(id) }) => JSX | — | Groups consecutive messages within five minutes per sender and renders them. groupMessages is exported too. |
Accessibility
- Every bubble names its sender, visibly at the start of a group and with sr-only text on later bubbles; times use the time element with an ISO dateTime.
- Actions appear on hover and whenever focus is inside the message, and stay visible on touch screens; each icon button has an aria-label and a tooltip.
- Copy announces Copied; failed messages are role alert with a text reason, not only a dimmed bubble.
- Bubbles enter with a 4px rise and fade in 200ms and the assistant mark animates only while streaming; both hold still with reduced motion.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/agent/bubble.tsxbubble- Also installs agent-state@0.1.0registry dependency
- Also installs tooltip@0.1.1registry dependency
- npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/bubble/0.1.0.json.
agent/bubble.tsxShowHide
agent/bubble.tsx
"use client";
import { Avatar } from "@base-ui/react/avatar";
import { type ComponentProps, type ReactNode, useEffect, useRef, useState } from "react";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "../ui/tooltip";
import { AgentMark, AgentState } from "./agent-state";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
export type BubbleFrom = "user" | "assistant";
export type BubblePosition = "single" | "first" | "middle" | "last";
export type BubbleStatus = "sending" | "streaming" | "complete" | "failed";
export type Timestamp = Date | string | number;
export interface BubbleProps extends Omit<ComponentProps<"div">, "children"> {
/** Who wrote it. User bubbles sit on the right in a soft tint; assistant bubbles on the left on a hairline. */
from: BubbleFrom;
children?: ReactNode;
/** Display name, shown above the first bubble of a group. */
author?: string;
/** Avatar image URL, or any node. Assistants default to a still Agent State mark that animates while streaming. */
avatar?: string | ReactNode;
/** When it was sent. Shown with the name, and next to the actions on hover. */
timestamp?: Timestamp;
/** Formats `timestamp`. Defaults to a short local time such as 9:41 AM. */
formatTime?: (date: Date) => string;
/** Where the bubble sits in a run of messages from the same sender; tightens corners and hides the repeated avatar. */
position?: BubblePosition;
status?: BubbleStatus;
/** Shown when the status is failed. */
error?: ReactNode;
/** Text for the copy action. Defaults to the children when they are a string; without it there is no copy action. */
copyText?: string;
/** Shows a retry action: regenerate for assistant replies, resend for failed user messages. */
onRetry?: () => void;
/** Extra action buttons after copy and retry. */
actions?: ReactNode;
}
function toDate(value: Timestamp): Date {
return value instanceof Date ? value : new Date(value);
}
const defaultFormat = (date: Date) => date.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
// The corner nearest the next or previous bubble in a group tightens, so a run reads as one voice.
const corners: Record<BubbleFrom, Record<BubblePosition, string>> = {
user: { single: "", first: "rounded-br-md", middle: "rounded-r-md", last: "rounded-tr-md" },
assistant: { single: "", first: "rounded-bl-md", middle: "rounded-l-md", last: "rounded-tl-md" },
};
/**
* One chat message bubble with an avatar, the author and time at the start of a group, and copy
* and retry actions that appear on hover or focus (always on touch screens).
*/
export function Bubble({
from,
children,
author,
avatar,
timestamp,
formatTime = defaultFormat,
position = "single",
status = "complete",
error,
copyText,
onRetry,
actions,
className,
...props
}: BubbleProps) {
const isUser = from === "user";
const leads = position === "single" || position === "first";
const streaming = status === "streaming";
const failed = status === "failed";
const text = copyText ?? (typeof children === "string" ? children : undefined);
const date = timestamp != null ? toDate(timestamp) : undefined;
const time = date ? (
<time dateTime={date.toISOString()} suppressHydrationWarning>
{formatTime(date)}
</time>
) : null;
const name = author ?? (isUser ? "You" : "Assistant");
const empty = children == null || children === "";
return (
<div
data-from={from}
data-position={position}
data-status={status}
aria-busy={streaming || undefined}
className={cx(
"group/bubble flex w-full gap-2.5",
isUser && "flex-row-reverse",
`transition-[opacity,translate] duration-200 ${ease} starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none`,
className,
)}
{...props}
>
<div className="w-7 shrink-0">{leads ? <BubbleAvatar from={from} avatar={avatar} name={name} streaming={streaming} /> : null}</div>
<div className={cx("@container flex min-w-0 flex-1 flex-col", isUser ? "items-end" : "items-start")}>
{leads ? (
<p className={cx("mb-1 flex items-baseline gap-2 text-xs leading-5", isUser && "flex-row-reverse")}>
<span className="font-medium text-zinc-700 dark:text-zinc-300">{name}</span>
{time ? <span className="text-zinc-500">{time}</span> : null}
</p>
) : (
<p className="sr-only">{name}</p>
)}
<div className={cx("flex w-full items-end gap-1", isUser ? "flex-row-reverse" : "flex-row")}>
<div
className={cx(
"min-w-0 max-w-[min(100%,36rem)] rounded-2xl px-3.5 py-2 text-sm leading-relaxed break-words",
isUser
? "bg-zinc-950/[0.05] text-zinc-950 dark:bg-white/[0.09] dark:text-white"
: "border border-zinc-950/10 bg-white text-zinc-950 dark:border-white/10 dark:bg-black dark:text-white",
corners[from][position],
failed && isUser && "opacity-70",
status === "sending" && "opacity-60",
"transition-opacity duration-200 motion-reduce:transition-none",
)}
>
{empty && streaming ? <AgentState variant="plain" size="sm" activity="thinking" label="Thinking" className="h-5 text-sm" /> : children}
{failed && !isUser ? (
<p role="alert" className="mt-2 rounded-lg border border-red-500/35 bg-red-500/[0.08] px-3 py-2 text-[13px] text-red-700 dark:text-red-300">
{error ?? "The reply stopped before it finished."}
</p>
) : null}
</div>
{!streaming && status !== "sending" ? (
<div
className={cx(
"flex shrink-0 items-center gap-0.5 pb-0.5",
isUser && "flex-row-reverse",
"opacity-0 transition-opacity duration-150 ease-out motion-reduce:transition-none",
"group-focus-within/bubble:opacity-100 group-hover/bubble:opacity-100 [@media(hover:none)]:opacity-100",
)}
>
<TooltipProvider>
{text ? <CopyAction text={text} /> : null}
{onRetry && !(isUser && !failed) ? (
<Action label={isUser ? "Resend" : "Retry"} onClick={onRetry}>
<path d="M12.75 8a4.75 4.75 0 1 1-1.39-3.36M12.75 2.75v2.5h-2.5" />
</Action>
) : null}
{actions}
</TooltipProvider>
{!leads && time ? <span className="px-1 text-[11px] whitespace-nowrap text-zinc-500 tabular-nums @max-md:hidden">{time}</span> : null}
</div>
) : null}
</div>
{failed && isUser ? (
<p role="alert" className="mt-1 flex items-center gap-1.5 text-xs text-red-600 dark:text-red-400">
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className="size-3.5">
<circle cx="8" cy="8" r="6.25" />
<path d="M8 5v3.25M8 10.75v.01" />
</svg>
{error ?? "Not sent"}
</p>
) : null}
</div>
</div>
);
}
function BubbleAvatar({ from, avatar, name, streaming }: { from: BubbleFrom; avatar?: string | ReactNode; name: string; streaming: boolean }) {
const ring = "shadow-[inset_0_0_0_1px_rgb(9_9_11/0.1)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.16)]";
if (avatar != null && typeof avatar !== "string") return <span aria-hidden="true">{avatar}</span>;
if (avatar == null && from === "assistant") {
return (
<span aria-hidden="true" className={cx("flex size-7 items-center justify-center rounded-full", ring)}>
<AgentMark activity="thinking" size={16} paused={!streaming} className="text-zinc-950 dark:text-white" />
</span>
);
}
const initials = name
.split(/\s+/)
.map((part) => part.charAt(0))
.join("")
.slice(0, 2)
.toUpperCase();
return (
<Avatar.Root aria-hidden="true" className={cx("inline-flex size-7 items-center justify-center overflow-hidden rounded-full select-none", ring)}>
{typeof avatar === "string" ? <Avatar.Image src={avatar} alt="" className="size-full object-cover" /> : null}
<Avatar.Fallback className="text-[11px] font-semibold text-zinc-600 dark:text-zinc-300">{initials}</Avatar.Fallback>
</Avatar.Root>
);
}
export interface BubbleActionProps {
/** Accessible name and tooltip text. */
label: string;
onClick?: () => void;
/** SVG paths in a 16 unit box, drawn with a 1.5 stroke. */
children: ReactNode;
}
/** A 28px icon button with a tooltip, for the hover actions row. Pass extra ones to `actions`. */
export function Action({ label, onClick, children }: BubbleActionProps) {
return (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={label}
onClick={onClick}
className={cx(
"inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-zinc-500",
"transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none",
"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
)}
/>
}
>
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4">
{children}
</svg>
</TooltipTrigger>
<TooltipContent side="top">{label}</TooltipContent>
</Tooltip>
);
}
function CopyAction({ text }: { text: string }) {
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
async function copy() {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(false), 1500);
} catch {
setCopied(false);
}
}
return (
<>
<Action label={copied ? "Copied" : "Copy"} onClick={copy}>
{copied ? (
<path key="check" d="m3.75 8.5 2.75 2.75 5.75-6.5" className="text-emerald-600 dark:text-emerald-400" />
) : (
<g key="copy">
<rect x="5.25" y="5.25" width="8" height="8" rx="1.75" />
<path d="M10.75 5.25V3.5c0-.97-.78-1.75-1.75-1.75H3.5c-.97 0-1.75.78-1.75 1.75V9c0 .97.78 1.75 1.75 1.75h1.75" />
</g>
)}
</Action>
<span className="sr-only" aria-live="polite">
{copied ? "Copied" : ""}
</span>
</>
);
}
export interface ChatMessage {
id: string;
from: BubbleFrom;
content: ReactNode;
/** Plain text for the copy action when `content` is not a string. */
text?: string;
author?: string;
avatar?: string | ReactNode;
timestamp?: Timestamp;
status?: BubbleStatus;
error?: ReactNode;
}
/**
* Marks each message's place in its group. Consecutive messages from the same sender and author
* join a group while they are less than `windowMs` apart (when both have timestamps).
*/
export function groupMessages<T extends Pick<ChatMessage, "from" | "author" | "timestamp">>(
messages: T[],
windowMs = 5 * 60_000,
): { message: T; position: BubblePosition }[] {
const joins = (a: T | undefined, b: T | undefined) => {
if (!a || !b || a.from !== b.from || a.author !== b.author) return false;
if (a.timestamp == null || b.timestamp == null) return true;
return Math.abs(toDate(b.timestamp).getTime() - toDate(a.timestamp).getTime()) < windowMs;
};
return messages.map((message, index) => {
const withPrevious = joins(messages[index - 1], message);
const withNext = joins(message, messages[index + 1]);
const position: BubblePosition = withPrevious ? (withNext ? "middle" : "last") : withNext ? "first" : "single";
return { message, position };
});
}
export interface BubbleListProps extends Omit<ComponentProps<"ol">, "children"> {
messages: ChatMessage[];
/** Consecutive messages closer than this join one group. */
windowMs?: number;
/** Called with a message id from its retry action. Assistant replies and failed user messages get one. */
onRetry?: (id: string) => void;
formatTime?: (date: Date) => string;
}
/** A conversation: groups consecutive messages per sender and renders each as a Bubble. */
export function BubbleList({ messages, windowMs, onRetry, formatTime, className, ...props }: BubbleListProps) {
return (
<ol aria-label="Conversation" className={cx("flex flex-col", className)} {...props}>
{groupMessages(messages, windowMs).map(({ message, position }, index) => (
<li key={message.id} className={cx(index === 0 ? "" : position === "single" || position === "first" ? "mt-5" : "mt-1")}>
<Bubble
from={message.from}
author={message.author}
avatar={message.avatar}
timestamp={message.timestamp}
formatTime={formatTime}
position={position}
status={message.status}
error={message.error}
copyText={message.text}
onRetry={onRetry && (message.from === "assistant" || message.status === "failed") ? () => onRetry(message.id) : undefined}
>
{message.content}
</Bubble>
</li>
))}
</ol>
);
}