{
  "schemaVersion": 1,
  "target": "react",
  "name": "bubble",
  "version": "0.1.0",
  "category": "ai-elements",
  "title": "Bubble",
  "description": "Chat message bubbles for user and assistant with avatars, timestamps, grouping of consecutive messages, and copy and retry actions on hover.",
  "tags": [
    "ai",
    "chat",
    "message",
    "bubble",
    "conversation",
    "avatar"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "@base-ui/react": "^1.9.0"
  },
  "registryDependencies": [
    {
      "name": "agent-state",
      "version": "0.1.0"
    },
    {
      "name": "tooltip",
      "version": "0.1.1"
    }
  ],
  "docsPath": "/components/bubble",
  "props": [
    {
      "name": "from",
      "type": "\"user\" | \"assistant\"",
      "description": "User bubbles sit right in a soft tint; assistant bubbles sit left on a hairline."
    },
    {
      "name": "author / avatar",
      "type": "string / string | ReactNode",
      "description": "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."
    },
    {
      "name": "timestamp / formatTime",
      "type": "Date | string | number / (date) => string",
      "description": "Shown with the name and next to the actions on later bubbles."
    },
    {
      "name": "position",
      "type": "\"single\" | \"first\" | \"middle\" | \"last\"",
      "default": "\"single\"",
      "description": "Place in a run from one sender; tightens corners and hides the repeated avatar."
    },
    {
      "name": "status",
      "type": "\"sending\" | \"streaming\" | \"complete\" | \"failed\"",
      "default": "\"complete\"",
      "description": "Streaming with no content shows Thinking; failed shows the error and a resend or retry action."
    },
    {
      "name": "copyText / onRetry / actions",
      "type": "string / () => void / ReactNode",
      "description": "The hover actions. Copy uses the string children by default."
    },
    {
      "name": "BubbleList",
      "type": "({ messages, windowMs?, onRetry?(id) }) => JSX",
      "description": "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."
  ],
  "states": [
    "user",
    "assistant",
    "grouped",
    "streaming",
    "sending",
    "failed"
  ],
  "files": [
    {
      "path": "agent/bubble.tsx",
      "content": "\"use client\";\n\nimport { Avatar } from \"@base-ui/react/avatar\";\nimport { type ComponentProps, type ReactNode, useEffect, useRef, useState } from \"react\";\nimport { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from \"../ui/tooltip\";\nimport { AgentMark, AgentState } from \"./agent-state\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nconst ease = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\n\nexport type BubbleFrom = \"user\" | \"assistant\";\nexport type BubblePosition = \"single\" | \"first\" | \"middle\" | \"last\";\nexport type BubbleStatus = \"sending\" | \"streaming\" | \"complete\" | \"failed\";\nexport type Timestamp = Date | string | number;\n\nexport interface BubbleProps extends Omit<ComponentProps<\"div\">, \"children\"> {\n  /** Who wrote it. User bubbles sit on the right in a soft tint; assistant bubbles on the left on a hairline. */\n  from: BubbleFrom;\n  children?: ReactNode;\n  /** Display name, shown above the first bubble of a group. */\n  author?: string;\n  /** Avatar image URL, or any node. Assistants default to a still Agent State mark that animates while streaming. */\n  avatar?: string | ReactNode;\n  /** When it was sent. Shown with the name, and next to the actions on hover. */\n  timestamp?: Timestamp;\n  /** Formats `timestamp`. Defaults to a short local time such as 9:41 AM. */\n  formatTime?: (date: Date) => string;\n  /** Where the bubble sits in a run of messages from the same sender; tightens corners and hides the repeated avatar. */\n  position?: BubblePosition;\n  status?: BubbleStatus;\n  /** Shown when the status is failed. */\n  error?: ReactNode;\n  /** Text for the copy action. Defaults to the children when they are a string; without it there is no copy action. */\n  copyText?: string;\n  /** Shows a retry action: regenerate for assistant replies, resend for failed user messages. */\n  onRetry?: () => void;\n  /** Extra action buttons after copy and retry. */\n  actions?: ReactNode;\n}\n\nfunction toDate(value: Timestamp): Date {\n  return value instanceof Date ? value : new Date(value);\n}\n\nconst defaultFormat = (date: Date) => date.toLocaleTimeString([], { hour: \"numeric\", minute: \"2-digit\" });\n\n// The corner nearest the next or previous bubble in a group tightens, so a run reads as one voice.\nconst corners: Record<BubbleFrom, Record<BubblePosition, string>> = {\n  user: { single: \"\", first: \"rounded-br-md\", middle: \"rounded-r-md\", last: \"rounded-tr-md\" },\n  assistant: { single: \"\", first: \"rounded-bl-md\", middle: \"rounded-l-md\", last: \"rounded-tl-md\" },\n};\n\n/**\n * One chat message bubble with an avatar, the author and time at the start of a group, and copy\n * and retry actions that appear on hover or focus (always on touch screens).\n */\nexport function Bubble({\n  from,\n  children,\n  author,\n  avatar,\n  timestamp,\n  formatTime = defaultFormat,\n  position = \"single\",\n  status = \"complete\",\n  error,\n  copyText,\n  onRetry,\n  actions,\n  className,\n  ...props\n}: BubbleProps) {\n  const isUser = from === \"user\";\n  const leads = position === \"single\" || position === \"first\";\n  const streaming = status === \"streaming\";\n  const failed = status === \"failed\";\n  const text = copyText ?? (typeof children === \"string\" ? children : undefined);\n  const date = timestamp != null ? toDate(timestamp) : undefined;\n  const time = date ? (\n    <time dateTime={date.toISOString()} suppressHydrationWarning>\n      {formatTime(date)}\n    </time>\n  ) : null;\n  const name = author ?? (isUser ? \"You\" : \"Assistant\");\n  const empty = children == null || children === \"\";\n\n  return (\n    <div\n      data-from={from}\n      data-position={position}\n      data-status={status}\n      aria-busy={streaming || undefined}\n      className={cx(\n        \"group/bubble flex w-full gap-2.5\",\n        isUser && \"flex-row-reverse\",\n        `transition-[opacity,translate] duration-200 ${ease} starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none`,\n        className,\n      )}\n      {...props}\n    >\n      <div className=\"w-7 shrink-0\">{leads ? <BubbleAvatar from={from} avatar={avatar} name={name} streaming={streaming} /> : null}</div>\n\n      <div className={cx(\"@container flex min-w-0 flex-1 flex-col\", isUser ? \"items-end\" : \"items-start\")}>\n        {leads ? (\n          <p className={cx(\"mb-1 flex items-baseline gap-2 text-xs leading-5\", isUser && \"flex-row-reverse\")}>\n            <span className=\"font-medium text-zinc-700 dark:text-zinc-300\">{name}</span>\n            {time ? <span className=\"text-zinc-500\">{time}</span> : null}\n          </p>\n        ) : (\n          <p className=\"sr-only\">{name}</p>\n        )}\n\n        <div className={cx(\"flex w-full items-end gap-1\", isUser ? \"flex-row-reverse\" : \"flex-row\")}>\n          <div\n            className={cx(\n              \"min-w-0 max-w-[min(100%,36rem)] rounded-2xl px-3.5 py-2 text-sm leading-relaxed break-words\",\n              isUser\n                ? \"bg-zinc-950/[0.05] text-zinc-950 dark:bg-white/[0.09] dark:text-white\"\n                : \"border border-zinc-950/10 bg-white text-zinc-950 dark:border-white/10 dark:bg-black dark:text-white\",\n              corners[from][position],\n              failed && isUser && \"opacity-70\",\n              status === \"sending\" && \"opacity-60\",\n              \"transition-opacity duration-200 motion-reduce:transition-none\",\n            )}\n          >\n            {empty && streaming ? <AgentState variant=\"plain\" size=\"sm\" activity=\"thinking\" label=\"Thinking\" className=\"h-5 text-sm\" /> : children}\n            {failed && !isUser ? (\n              <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\">\n                {error ?? \"The reply stopped before it finished.\"}\n              </p>\n            ) : null}\n          </div>\n\n          {!streaming && status !== \"sending\" ? (\n            <div\n              className={cx(\n                \"flex shrink-0 items-center gap-0.5 pb-0.5\",\n                isUser && \"flex-row-reverse\",\n                \"opacity-0 transition-opacity duration-150 ease-out motion-reduce:transition-none\",\n                \"group-focus-within/bubble:opacity-100 group-hover/bubble:opacity-100 [@media(hover:none)]:opacity-100\",\n              )}\n            >\n              <TooltipProvider>\n                {text ? <CopyAction text={text} /> : null}\n                {onRetry && !(isUser && !failed) ? (\n                  <Action label={isUser ? \"Resend\" : \"Retry\"} onClick={onRetry}>\n                    <path d=\"M12.75 8a4.75 4.75 0 1 1-1.39-3.36M12.75 2.75v2.5h-2.5\" />\n                  </Action>\n                ) : null}\n                {actions}\n              </TooltipProvider>\n              {!leads && time ? <span className=\"px-1 text-[11px] whitespace-nowrap text-zinc-500 tabular-nums @max-md:hidden\">{time}</span> : null}\n            </div>\n          ) : null}\n        </div>\n\n        {failed && isUser ? (\n          <p role=\"alert\" className=\"mt-1 flex items-center gap-1.5 text-xs text-red-600 dark:text-red-400\">\n            <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" className=\"size-3.5\">\n              <circle cx=\"8\" cy=\"8\" r=\"6.25\" />\n              <path d=\"M8 5v3.25M8 10.75v.01\" />\n            </svg>\n            {error ?? \"Not sent\"}\n          </p>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n\nfunction BubbleAvatar({ from, avatar, name, streaming }: { from: BubbleFrom; avatar?: string | ReactNode; name: string; streaming: boolean }) {\n  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)]\";\n  if (avatar != null && typeof avatar !== \"string\") return <span aria-hidden=\"true\">{avatar}</span>;\n  if (avatar == null && from === \"assistant\") {\n    return (\n      <span aria-hidden=\"true\" className={cx(\"flex size-7 items-center justify-center rounded-full\", ring)}>\n        <AgentMark activity=\"thinking\" size={16} paused={!streaming} className=\"text-zinc-950 dark:text-white\" />\n      </span>\n    );\n  }\n  const initials = name\n    .split(/\\s+/)\n    .map((part) => part.charAt(0))\n    .join(\"\")\n    .slice(0, 2)\n    .toUpperCase();\n  return (\n    <Avatar.Root aria-hidden=\"true\" className={cx(\"inline-flex size-7 items-center justify-center overflow-hidden rounded-full select-none\", ring)}>\n      {typeof avatar === \"string\" ? <Avatar.Image src={avatar} alt=\"\" className=\"size-full object-cover\" /> : null}\n      <Avatar.Fallback className=\"text-[11px] font-semibold text-zinc-600 dark:text-zinc-300\">{initials}</Avatar.Fallback>\n    </Avatar.Root>\n  );\n}\n\nexport interface BubbleActionProps {\n  /** Accessible name and tooltip text. */\n  label: string;\n  onClick?: () => void;\n  /** SVG paths in a 16 unit box, drawn with a 1.5 stroke. */\n  children: ReactNode;\n}\n\n/** A 28px icon button with a tooltip, for the hover actions row. Pass extra ones to `actions`. */\nexport function Action({ label, onClick, children }: BubbleActionProps) {\n  return (\n    <Tooltip>\n      <TooltipTrigger\n        render={\n          <button\n            type=\"button\"\n            aria-label={label}\n            onClick={onClick}\n            className={cx(\n              \"inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-zinc-500\",\n              \"transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none\",\n              \"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white\",\n              \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n            )}\n          />\n        }\n      >\n        <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" className=\"size-4\">\n          {children}\n        </svg>\n      </TooltipTrigger>\n      <TooltipContent side=\"top\">{label}</TooltipContent>\n    </Tooltip>\n  );\n}\n\nfunction CopyAction({ text }: { text: string }) {\n  const [copied, setCopied] = useState(false);\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  useEffect(() => () => clearTimeout(timer.current), []);\n\n  async function copy() {\n    try {\n      await navigator.clipboard.writeText(text);\n      setCopied(true);\n      clearTimeout(timer.current);\n      timer.current = setTimeout(() => setCopied(false), 1500);\n    } catch {\n      setCopied(false);\n    }\n  }\n\n  return (\n    <>\n      <Action label={copied ? \"Copied\" : \"Copy\"} onClick={copy}>\n        {copied ? (\n          <path key=\"check\" d=\"m3.75 8.5 2.75 2.75 5.75-6.5\" className=\"text-emerald-600 dark:text-emerald-400\" />\n        ) : (\n          <g key=\"copy\">\n            <rect x=\"5.25\" y=\"5.25\" width=\"8\" height=\"8\" rx=\"1.75\" />\n            <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\" />\n          </g>\n        )}\n      </Action>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {copied ? \"Copied\" : \"\"}\n      </span>\n    </>\n  );\n}\n\nexport interface ChatMessage {\n  id: string;\n  from: BubbleFrom;\n  content: ReactNode;\n  /** Plain text for the copy action when `content` is not a string. */\n  text?: string;\n  author?: string;\n  avatar?: string | ReactNode;\n  timestamp?: Timestamp;\n  status?: BubbleStatus;\n  error?: ReactNode;\n}\n\n/**\n * Marks each message's place in its group. Consecutive messages from the same sender and author\n * join a group while they are less than `windowMs` apart (when both have timestamps).\n */\nexport function groupMessages<T extends Pick<ChatMessage, \"from\" | \"author\" | \"timestamp\">>(\n  messages: T[],\n  windowMs = 5 * 60_000,\n): { message: T; position: BubblePosition }[] {\n  const joins = (a: T | undefined, b: T | undefined) => {\n    if (!a || !b || a.from !== b.from || a.author !== b.author) return false;\n    if (a.timestamp == null || b.timestamp == null) return true;\n    return Math.abs(toDate(b.timestamp).getTime() - toDate(a.timestamp).getTime()) < windowMs;\n  };\n  return messages.map((message, index) => {\n    const withPrevious = joins(messages[index - 1], message);\n    const withNext = joins(message, messages[index + 1]);\n    const position: BubblePosition = withPrevious ? (withNext ? \"middle\" : \"last\") : withNext ? \"first\" : \"single\";\n    return { message, position };\n  });\n}\n\nexport interface BubbleListProps extends Omit<ComponentProps<\"ol\">, \"children\"> {\n  messages: ChatMessage[];\n  /** Consecutive messages closer than this join one group. */\n  windowMs?: number;\n  /** Called with a message id from its retry action. Assistant replies and failed user messages get one. */\n  onRetry?: (id: string) => void;\n  formatTime?: (date: Date) => string;\n}\n\n/** A conversation: groups consecutive messages per sender and renders each as a Bubble. */\nexport function BubbleList({ messages, windowMs, onRetry, formatTime, className, ...props }: BubbleListProps) {\n  return (\n    <ol aria-label=\"Conversation\" className={cx(\"flex flex-col\", className)} {...props}>\n      {groupMessages(messages, windowMs).map(({ message, position }, index) => (\n        <li key={message.id} className={cx(index === 0 ? \"\" : position === \"single\" || position === \"first\" ? \"mt-5\" : \"mt-1\")}>\n          <Bubble\n            from={message.from}\n            author={message.author}\n            avatar={message.avatar}\n            timestamp={message.timestamp}\n            formatTime={formatTime}\n            position={position}\n            status={message.status}\n            error={message.error}\n            copyText={message.text}\n            onRetry={onRetry && (message.from === \"assistant\" || message.status === \"failed\") ? () => onRetry(message.id) : undefined}\n          >\n            {message.content}\n          </Bubble>\n        </li>\n      ))}\n    </ol>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { BubbleList, type ChatMessage } from \"@/components/shaken/agent/bubble\";\n\nconst at = (minutes: number) => new Date(Date.UTC(2026, 10, 14, 16, minutes));\n\nconst messages: ChatMessage[] = [\n  { 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?\" },\n  { id: \"m2\", from: \"user\", author: \"Priya Raman\", timestamp: at(2), content: \"Their finance team flagged it this morning.\" },\n  {\n    id: \"m3\",\n    from: \"assistant\",\n    author: \"Billing agent\",\n    timestamp: at(3),\n    content:\n      \"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.\",\n  },\n  {\n    id: \"m4\",\n    from: \"assistant\",\n    author: \"Billing agent\",\n    timestamp: at(3),\n    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?\",\n  },\n  { id: \"m5\", from: \"user\", author: \"Priya Raman\", timestamp: at(5), content: \"Yes, and add a test for the half cent case.\" },\n];\n\nconst formatTime = (date: Date) => date.toLocaleTimeString(\"en-US\", { hour: \"numeric\", minute: \"2-digit\", timeZone: \"UTC\" });\n\nexport default function BubbleExample() {\n  return <BubbleList messages={messages} formatTime={formatTime} onRetry={() => {}} className=\"w-full max-w-xl\" />;\n}\n"
  }
}
