{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "agent-chat",
  "type": "registry:ui",
  "title": "Agent Chat",
  "description": "The agent-chat primitive.",
  "dependencies": [
    "lucide-react@^1.49.0"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/menu.json",
    "https://ui.klarhimmel.com/r/theme.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/ui/agent-chat.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/agent-chat.tsx",
      "content": "// The shared chat: messages, their action row, the loader, the thread and the empty start, used with ChatComposer by every app\n// (Felix 2026-10-22 18:48-18:49, Gemini references in ~/.omni/fleet/briefs/2026-10-22/design-root-1848p, -1849q, -1849r).\n// - The person's message: a rounded bubble on the right; no avatar, no name.\n// - The assistant's reply: plain text at reading width; no bubble, icon or name. A quiet icon row under it.\n// - While the assistant works: a small animated loader where the reply will start, no words, no skeleton; the reply then\n//   streams in its place. The composer's send turns into stop (ChatComposer busy).\n// - One scroll: the thread scrolls with the page, the composer sticks to the view's bottom (Felix 19:21).\n// - On send the new message moves near the top and the reply streams in below it; the view does not chase the stream. While\n//   there is more below the fold, a round arrow floats bottom-centre above the composer (Felix 18:50, Gemini scroll).\n// - No day dividers. An empty chat: a centred greeting, the composer, suggestion rows under it, on the plain canvas (no glow:\n//   Felix 18:55 \"remove the gradient we don't need it\").\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';\nimport { ArrowDown, Check, Copy, MoreHorizontal, RotateCw, ThumbsDown, ThumbsUp } from 'lucide-react';\nimport { cn } from '../lib/utils';\nimport { klarhimmelMark } from '../theme/brand';\nimport './agent-chat.css';\nimport { Menu, MenuContent, MenuItem, MenuTrigger } from './menu';\n\nconst useIsoLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;\n\n// The element that scrolls the thread: its nearest scrolling ancestor, or the window (null).\nfunction scrollerOf(el: HTMLElement | null): HTMLElement | null {\n  for (let p = el?.parentElement; p && p !== document.body; p = p.parentElement) {\n    const o = getComputedStyle(p).overflowY;\n    if ((o === 'auto' || o === 'scroll') && p.scrollHeight > p.clientHeight) return p;\n  }\n  return null;\n}\n\n/** The conversation and its composer. By default it scrolls with the page (one scroll, the window's or the app's main area; Felix\n *  2026-10-22 19:21 \"The inline scrollbar makes the experience feel janky\"): the messages flow in the document and the composer\n *  sticks to the bottom of the view. `scroll=\"inner\"` is for a box of fixed height that must scroll by itself; its scrollbar is\n *  hidden. When `anchor` changes (the id of the newest message the person sent), that message scrolls near the top and the reply\n *  grows under it; a round arrow takes the person to the bottom while more is below. */\nexport function ChatThread({ children, composer, anchor, scroll = 'page', jumpLabel = 'Scroll to the bottom', className }: {\n  children: ReactNode;\n  /** The ChatComposer, at the bottom of the view. */\n  composer?: ReactNode;\n  /** Changes on each send: the id of the newest user message. */\n  anchor?: string | number;\n  /** page: scrolls with the page (default). inner: its own scroll area (give it a height), scrollbar hidden. */\n  scroll?: 'page' | 'inner';\n  jumpLabel?: string;\n  className?: string;\n}) {\n  const inner = scroll === 'inner';\n  const box = useRef<HTMLDivElement>(null);\n  const list = useRef<HTMLDivElement>(null);\n  const spacer = useRef<HTMLDivElement>(null);\n  const foot = useRef<HTMLDivElement>(null);\n  const [below, setBelow] = useState(false);\n  const scroller = useCallback(() => (inner ? box.current : scrollerOf(list.current)), [inner]);\n  const view = useCallback(() => { const sc = scroller(); return sc ? sc.getBoundingClientRect() : { top: 0, bottom: window.innerHeight, height: window.innerHeight }; }, [scroller]);\n  // The bottom edge content may reach: the composer's top (it sits over the view's bottom), or the view's bottom.\n  const floor = useCallback(() => (foot.current ? foot.current.getBoundingClientRect().top : view().bottom), [view]);\n  // More below: the end of the real content (the spacer's top) is more than one composer height under the floor. The room kept\n  // under a new message never counts. Less than that is a reply's last line or a card's buttons just above the composer, where the\n  // arrow would sit on them and a tap would jump instead of acting (Klar Agent KA-143, 11-05: it covered a card's Ändra at 390 px).\n  const measure = useCallback(() => {\n    const sp = spacer.current;\n    if (sp) setBelow(sp.getBoundingClientRect().top - floor() > Math.max(24, foot.current?.offsetHeight ?? 0));\n  }, [floor]);\n  // Room under the newest user message, so it can sit near the top before the reply fills the view; it shrinks as the reply grows.\n  const fit = useCallback(() => {\n    const sp = spacer.current;\n    if (!sp) return;\n    const users = list.current?.querySelectorAll<HTMLElement>('[data-kh-chat-user]');\n    const last = users?.[users.length - 1];\n    if (!last || anchor === undefined) { sp.style.height = '0px'; return; }\n    const v = view();\n    const content = sp.getBoundingClientRect().top - last.getBoundingClientRect().top;\n    const footH = foot.current?.offsetHeight ?? 0;\n    sp.style.height = `${Math.max(0, v.height - footH - content - parseFloat(getComputedStyle(last).scrollMarginTop || '0'))}px`;\n  }, [anchor, view]);\n  useIsoLayoutEffect(() => {\n    if (anchor === undefined) return;\n    fit();\n    const users = list.current?.querySelectorAll<HTMLElement>('[data-kh-chat-user]');\n    users?.[users.length - 1]?.scrollIntoView({ behavior: 'smooth', block: 'start' });\n  }, [anchor]); // eslint-disable-line react-hooks/exhaustive-deps\n  useEffect(() => {\n    const sc = scroller();\n    const target: HTMLElement | Window = sc ?? window;\n    const on = () => measure();\n    target.addEventListener('scroll', on, { passive: true });\n    window.addEventListener('resize', on);\n    const ro = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => { fit(); measure(); });\n    if (list.current) ro?.observe(list.current);\n    measure();\n    return () => { target.removeEventListener('scroll', on); window.removeEventListener('resize', on); ro?.disconnect(); };\n  }, [scroller, fit, measure]);\n  const jump = () => {\n    const sp = spacer.current;\n    if (!sp) return;\n    const by = sp.getBoundingClientRect().top - floor() + 16;\n    (scroller() ?? window).scrollBy({ top: by, behavior: 'smooth' });\n  };\n  const messages = (\n    <div ref={list} className=\"mx-auto flex w-full max-w-3xl flex-col gap-8 px-4 pt-6 pb-4\">\n      {children}\n      <div ref={spacer} aria-hidden className=\"-mt-8 shrink-0\" />\n    </div>\n  );\n  const footer = composer && (\n    <div ref={foot} className={cn('z-10 shrink-0 bg-(--kh-chat-bg)', !inner && 'sticky bottom-0')}>\n      <div className=\"relative mx-auto w-full max-w-3xl px-4 pb-3 pt-1\">\n        {below && (\n          <button type=\"button\" aria-label={jumpLabel} title={jumpLabel} onClick={jump}\n            className=\"absolute -top-12 left-1/2 inline-flex size-9 -translate-x-1/2 items-center justify-center rounded-kh-pill border border-kh-line bg-kh-surface text-kh-ink-2 shadow-kh-2 transition-colors duration-(--kh-dur) hover:text-kh-ink pointer-coarse:size-11 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus)\">\n            <ArrowDown aria-hidden className=\"size-4\" />\n          </button>\n        )}\n        {composer}\n      </div>\n    </div>\n  );\n  // --kh-chat-bg: what is behind the composer's strip, so text scrolling under it does not show; set it where the thread sits on\n  // something other than the surface (a page on the canvas: [--kh-chat-bg:var(--kh-canvas)]). A host page (a hotel's guest chat)\n  // sets --kh-chat-ground once above the chat instead, and --kh-chat-accent with --kh-chat-on-accent for the person's bubble and the\n  // send button: the kit reads them with today's look as the fallback, so no host needs !important (UI-27).\n  return inner ? (\n    <div className={cn('flex min-h-0 flex-col [--kh-chat-bg:var(--kh-chat-ground,var(--kh-surface))]', className)}>\n      <div ref={box} className=\"relative min-h-0 flex-1 overflow-y-auto [overflow-anchor:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\">{messages}</div>\n      {footer}\n    </div>\n  ) : (\n    <div className={cn('flex flex-col [--kh-chat-bg:var(--kh-chat-ground,var(--kh-surface))] [overflow-anchor:none]', className)}>\n      <div className=\"flex-1\">{messages}</div>\n      {footer}\n    </div>\n  );\n}\n\n/** One message. `from=\"user\"`: a bubble on the right. `from=\"assistant\"`: plain text, with `actions` (MessageActions) under it. */\nexport function ChatMessage({ from, children, actions, className }: { from: 'user' | 'assistant'; children: ReactNode; actions?: ReactNode; className?: string }) {\n  if (from === 'user') {\n    return (\n      <div data-kh-chat-user className={cn('flex scroll-mt-[var(--kh-chat-top,5rem)] justify-end', className)}>\n        <div className=\"max-w-[min(80%,36rem)] whitespace-pre-wrap rounded-[1.5rem] bg-[var(--kh-chat-accent,var(--kh-bubble))] px-5 py-3 text-kh-body leading-6 text-[var(--kh-chat-on-accent,var(--kh-ink))] [overflow-wrap:anywhere]\">{children}</div>\n      </div>\n    );\n  }\n  return (\n    <div className={cn('min-w-0', className)}>\n      {/* Rich text as it streams: headings, bold, lists, links, code (render the Markdown in the app; the look is here). */}\n      <div className={cn('text-kh-body leading-7 text-kh-ink [overflow-wrap:anywhere] [&>*+*]:mt-4',\n        '[&_h1]:mt-7 [&_h1]:text-[1.375rem] [&_h1]:font-semibold [&_h2]:mt-7 [&_h2]:text-[1.25rem] [&_h2]:font-medium [&_h3]:mt-6 [&_h3]:font-semibold [&_:is(h1,h2,h3)+*]:mt-2',\n        '[&_strong]:font-semibold [&_ul]:list-disc [&_ol]:list-decimal [&_:is(ul,ol)]:space-y-2 [&_:is(ul,ol)]:pl-6 [&_li]:pl-1 [&_li]:marker:text-kh-muted',\n        '[&_a]:underline [&_a]:underline-offset-4 [&_a]:decoration-kh-line-strong [&_a:hover]:decoration-kh-ink [&_code]:rounded [&_code]:bg-(--kh-bubble) [&_code]:px-1 [&_code]:text-[0.9em]',\n        '[&_pre]:overflow-x-auto [&_pre]:rounded-kh-lg [&_pre]:bg-(--kh-bubble) [&_pre]:p-4 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_blockquote]:border-l-2 [&_blockquote]:border-kh-line-strong [&_blockquote]:pl-4 [&_blockquote]:text-kh-ink-2')}>{children}</div>\n      {actions && <div className=\"mt-2 -ml-2\">{actions}</div>}\n    </div>\n  );\n}\n\nexport interface MessageActionsLabels { good: string; bad: string; retry: string; copy: string; copied: string; more: string }\nconst EN: MessageActionsLabels = { good: 'Good answer', bad: 'Bad answer', retry: 'Try again', copy: 'Copy', copied: 'Copied', more: 'More' };\n\nconst quiet = 'inline-flex size-9 items-center justify-center rounded-kh-pill text-kh-muted transition-colors duration-(--kh-dur) hover:bg-(--kh-bubble) hover:text-kh-ink pointer-coarse:size-11 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus) [&_svg]:size-[1.125rem]';\n\n/** The quiet icon row under a reply: rate it, try again, copy it, more. Each shows only when the app gives it. */\nexport function MessageActions({ rating, onRate, onRetry, copyText, more, labels }: {\n  /** The person's rating, so the pressed thumb stays pressed. */\n  rating?: 'good' | 'bad' | null;\n  onRate?: (rating: 'good' | 'bad' | null) => void;\n  onRetry?: () => void;\n  /** The reply as text: Copy copies it and says Copied. */\n  copyText?: string;\n  more?: { label: string; onSelect: () => void; danger?: boolean }[];\n  labels?: Partial<MessageActionsLabels>;\n}) {\n  const w = { ...EN, ...labels };\n  const [copied, setCopied] = useState(false);\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  useEffect(() => () => clearTimeout(timer.current), []);\n  const copy = () => {\n    if (copyText === undefined) return;\n    void navigator.clipboard?.writeText(copyText);\n    setCopied(true);\n    clearTimeout(timer.current);\n    timer.current = setTimeout(() => setCopied(false), 1600);\n  };\n  return (\n    <div className=\"flex items-center gap-0.5\">\n      {onRate && <>\n        <button type=\"button\" aria-label={w.good} title={w.good} aria-pressed={rating === 'good'} onClick={() => onRate(rating === 'good' ? null : 'good')} className={cn(quiet, rating === 'good' && 'text-kh-ink [&_svg]:fill-current')}><ThumbsUp aria-hidden /></button>\n        <button type=\"button\" aria-label={w.bad} title={w.bad} aria-pressed={rating === 'bad'} onClick={() => onRate(rating === 'bad' ? null : 'bad')} className={cn(quiet, rating === 'bad' && 'text-kh-ink [&_svg]:fill-current')}><ThumbsDown aria-hidden /></button>\n      </>}\n      {onRetry && <button type=\"button\" aria-label={w.retry} title={w.retry} onClick={onRetry} className={quiet}><RotateCw aria-hidden /></button>}\n      {copyText !== undefined && (\n        <button type=\"button\" aria-label={copied ? w.copied : w.copy} title={copied ? w.copied : w.copy} onClick={copy} className={quiet}>\n          {copied ? <Check aria-hidden /> : <Copy aria-hidden />}\n        </button>\n      )}\n      {copyText !== undefined && <span role=\"status\" className=\"sr-only\">{copied ? w.copied : ''}</span>}\n      {more && more.length > 0 && (\n        <Menu>\n          <MenuTrigger asChild><button type=\"button\" aria-label={w.more} title={w.more} className={quiet}><MoreHorizontal aria-hidden /></button></MenuTrigger>\n          <MenuContent align=\"start\">{more.map((m) => <MenuItem key={m.label} danger={m.danger} onSelect={m.onSelect}>{m.label}</MenuItem>)}</MenuContent>\n        </Menu>\n      )}\n    </div>\n  );\n}\n\n/**\n * Where the reply will start while the assistant works: the Klarhimmel mark rising over its horizon, no words (Felix 18:37 10-22 removed\n * a visible \"Thinking…\"; the 10-24 variants with words or dots went unpicked and were removed 10-25). The label is the screen-reader\n * name. Swap it for the reply as it streams. live: false inside a region that already announces (a role=log), so the loader is not a\n * second live region in it.\n */\nexport function ChatLoader({ label = 'Answering', className, live = true }: { label?: string; className?: string; live?: boolean }) {\n  return (\n    <div role={live ? 'status' : undefined} className={cn('flex h-7 items-center gap-2.5', className)}>\n      <svg aria-hidden viewBox=\"0 0 32 32\" width=\"18\" height=\"18\" className=\"kh-chat-mark size-[1.125rem] shrink-0 overflow-visible text-kh-ink\">\n        <path className=\"kh-chat-dome\" fill=\"currentColor\" d={klarhimmelMark.paths[0]} />\n        <path className=\"kh-chat-line\" fill=\"currentColor\" d={klarhimmelMark.paths[1]} />\n      </svg>\n      <span className=\"sr-only\">{label}</span>\n    </div>\n  );\n}\n\n/** An empty chat: a centred greeting, the composer (children), suggestion rows under it. */\nexport function ChatStart({ greeting, children, suggestions = [], className }: {\n  greeting: ReactNode;\n  /** The ChatComposer. */\n  children: ReactNode;\n  /** Up to four: each fills or sends a first message. */\n  suggestions?: { label: string; icon?: ReactNode; onSelect: () => void }[];\n  className?: string;\n}) {\n  return (\n    <div className={cn('flex w-full flex-col items-center justify-center px-4 py-12 @container', className)}>\n      <h2 className=\"text-center font-kh-display text-[clamp(1.375rem,6cqw,2.5rem)] font-normal leading-tight tracking-tight text-kh-ink\">{greeting}</h2>\n      <div className=\"mt-8 w-full max-w-3xl\">{children}</div>\n      {suggestions.length > 0 && (\n        <ul className=\"mt-5 flex w-full max-w-3xl flex-col items-start px-2\">\n          {suggestions.slice(0, 4).map((s) => (\n            <li key={s.label} className=\"max-w-full\">\n              <button type=\"button\" onClick={s.onSelect}\n                className=\"flex min-h-11 max-w-full items-center gap-3 rounded-kh-pill px-3 text-left text-kh-body text-kh-ink-2 transition-colors duration-(--kh-dur) hover:bg-(--kh-bubble) hover:text-kh-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus) [&_svg]:size-[1.125rem] [&_svg]:shrink-0 [&_svg]:text-kh-muted\">\n                {s.icon}<span className=\"truncate\">{s.label}</span>\n              </button>\n            </li>\n          ))}\n        </ul>\n      )}\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/ui/agent-chat.css",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/agent-chat.css",
      "content": "/* ChatLoader (agent-chat.tsx). Felix 2026-10-24 13:0x on /ws: \"loading spinner needs some love, we can create something more\n   interesting\". The mark rises over its horizon like a small sunrise, and the label reads as the assistant working. */\n@keyframes kh-chat-rise {\n  0%, 100% { transform: translateY(2.5px); opacity: 0.45; }\n  50% { transform: translateY(-0.5px); opacity: 1; }\n}\n@keyframes kh-chat-horizon {\n  0%, 100% { opacity: 0.35; }\n  50% { opacity: 0.9; }\n}\n.kh-chat-mark .kh-chat-dome { transform-box: fill-box; animation: kh-chat-rise 1.6s ease-in-out infinite; }\n.kh-chat-mark .kh-chat-line { animation: kh-chat-horizon 1.6s ease-in-out infinite; }\n@media (prefers-reduced-motion: reduce) {\n  .kh-chat-mark .kh-chat-dome, .kh-chat-mark .kh-chat-line { animation: none; opacity: 1; transform: none; }\n}\n"
    }
  ]
}
