{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chat-history-sidebar",
  "title": "Chat History Sidebar",
  "description": "The history sidebar of an AI chat app: conversations grouped by date with pinned chats on top, project folders that filter the list, search with highlighted matches, a row menu to rename, pin, archive, move or delete with undo, a collapsible icon rail and a drawer on small screens.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/chat-history-sidebar/chat-history-sidebar.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport interface HistoryProject {\n  id: string;\n  name: string;\n  color: string;\n}\nexport interface HistoryChat {\n  id: string;\n  title: string;\n  /** Days since the chat was last updated: 0 is today. Used for the date groups. */\n  daysAgo: number;\n  prompt: string;\n  answer: string;\n  project?: string;\n  pinned?: boolean;\n  archived?: boolean;\n}\ntype Msg = { id: string; from: \"user\" | \"assistant\"; text: string };\n\nexport interface ChatHistorySidebarProps {\n  workspace?: string;\n  model?: string;\n  chats?: HistoryChat[];\n  projects?: HistoryProject[];\n  user?: { name: string; plan?: string };\n  defaultActiveId?: string | null;\n  defaultCollapsed?: boolean;\n  onSelect?: (id: string) => void;\n  onNew?: () => void;\n  onRename?: (id: string, title: string) => void;\n  onDelete?: (id: string) => void;\n  theme?: \"dark\" | \"light\";\n  className?: string;\n}\n\nconst PALETTES = {\n  dark: { bg: \"#0A0A0A\", side: \"#0F0F0F\", text: \"#F5F4F1\", muted: \"rgba(245,244,241,0.62)\", faint: \"rgba(245,244,241,0.36)\", card: \"#161616\", border: \"rgba(255,255,255,0.09)\", hover: \"rgba(255,255,255,0.045)\", active: \"rgba(255,255,255,0.08)\", on: \"#F5F4F1\", onText: \"#0A0A0A\", accent: \"#FB923C\", accentSoft: \"rgba(251,146,60,0.16)\", danger: \"#F87171\", menu: \"#1A1A1A\", scrim: \"rgba(0,0,0,0.55)\", user: \"#1C1C1C\", ring: \"rgba(245,244,241,0.6)\" },\n  light: { bg: \"#FFFFFF\", side: \"#F6F5F2\", text: \"#0A0A0A\", muted: \"rgba(10,10,10,0.62)\", faint: \"rgba(10,10,10,0.4)\", card: \"#FFFFFF\", border: \"rgba(10,10,10,0.09)\", hover: \"rgba(10,10,10,0.04)\", active: \"rgba(10,10,10,0.07)\", on: \"#0A0A0A\", onText: \"#FAFAF8\", accent: \"#EA580C\", accentSoft: \"rgba(234,88,12,0.12)\", danger: \"#DC2626\", menu: \"#FFFFFF\", scrim: \"rgba(10,10,10,0.3)\", user: \"#F1F0EC\", ring: \"rgba(10,10,10,0.5)\" },\n};\n\nconst DEFAULT_PROJECTS: HistoryProject[] = [\n  { id: \"launch\", name: \"Spring launch\", color: \"#FB923C\" },\n  { id: \"eng\", name: \"Engineering\", color: \"#60A5FA\" },\n  { id: \"home\", name: \"Personal\", color: \"#4ADE80\" },\n];\nconst DEFAULT_CHATS: HistoryChat[] = [\n  { id: \"c1\", title: \"Launch email subject lines\", daysAgo: 0, project: \"launch\", pinned: true, prompt: \"Give me subject lines for our spring launch email. Calm, not salesy.\", answer: \"Here are five to test:\\n1. Something new for spring\\n2. We rebuilt the editor\\n3. Faster, quieter, ready today\\n4. Your workspace, one step lighter\\n5. A small update you'll notice every day\" },\n  { id: \"c2\", title: \"Fix flaky checkout test\", daysAgo: 0, project: \"eng\", prompt: \"Our checkout end-to-end test fails about one run in ten. It clicks Pay before the button is enabled.\", answer: \"Wait for the state, not for time. Replace the fixed sleep with an assertion that the Pay button is enabled, then click. If the button re-renders, query it again after the wait so you don't hold a stale handle.\" },\n  { id: \"c3\", title: \"Explain Rust lifetimes\", daysAgo: 1, project: \"eng\", prompt: \"Explain Rust lifetimes like I know TypeScript.\", answer: \"A lifetime is the compiler's name for how long a reference stays valid. TypeScript never asks because the garbage collector keeps things alive; Rust has no collector, so it checks at compile time that nothing points at memory that's already gone.\" },\n  { id: \"c4\", title: \"Lisbon weekend plan\", daysAgo: 1, project: \"home\", prompt: \"Plan two relaxed days in Lisbon with lots of walking and good coffee.\", answer: \"Day 1: Alfama in the morning before the crowds, lunch near Graça, tram 28 back down, sunset at Miradouro de Santa Catarina.\\nDay 2: Belém early, then LX Factory for coffee and books.\" },\n  { id: \"c5\", title: \"SQL for monthly churn\", daysAgo: 3, project: \"eng\", prompt: \"Write SQL for monthly logo churn from a subscriptions table.\", answer: \"Count customers active at the start of each month, then those of them who are no longer active at the end. Churn is the second number divided by the first. I'd use a calendar CTE and a left join on the end-of-month status.\" },\n  { id: \"c6\", title: \"Pricing page FAQ\", daysAgo: 4, project: \"launch\", prompt: \"Draft six FAQ answers for our pricing page.\", answer: \"1. Can I change plans later? Yes, any time, and we prorate the difference.\\n2. Is there a free trial? 14 days on every paid plan, no card needed.\\n3. Do you offer discounts for non-profits? Yes, 40% off Team.\" },\n  { id: \"c7\", title: \"Postgres index advice\", daysAgo: 6, project: \"eng\", prompt: \"This query on orders (customer_id, created_at) is slow. Which index?\", answer: \"A composite index on (customer_id, created_at DESC) matches both the filter and the sort, so Postgres can read the newest rows for a customer without sorting.\" },\n  { id: \"c8\", title: \"Birthday party for a 7-year-old\", daysAgo: 9, project: \"home\", prompt: \"Ideas for a backyard birthday party for a 7-year-old who loves space.\", answer: \"Build a cardboard rocket photo booth, run a 'planet hunt' with painted balls hidden in the garden, and end with glow sticks and a star map on a sheet.\" },\n  { id: \"c9\", title: \"Summarise user interviews\", daysAgo: 12, project: \"launch\", prompt: \"Summarise the five interview notes I pasted into themes.\", answer: \"Three themes came up in four of five interviews: onboarding takes too long, people can't find shared files, and the mobile app is used mostly for approvals.\" },\n  { id: \"c10\", title: \"Regex for UK postcodes\", daysAgo: 18, project: \"eng\", prompt: \"A practical regex for UK postcodes.\", answer: \"^[A-Z]{1,2}\\\\d[A-Z\\\\d]? ?\\\\d[A-Z]{2}$ with the i flag covers real-world input. Validate against a lookup service if the address really matters.\" },\n  { id: \"c11\", title: \"Offsite agenda ideas\", daysAgo: 26, prompt: \"A one-day offsite agenda for a team of 12.\", answer: \"Start with a 30-minute look back, then two working sessions on the biggest open question, a long lunch outside, and finish with a short 'one thing I'll change' round.\" },\n  { id: \"c12\", title: \"Cover letter for design role\", daysAgo: 41, project: \"home\", prompt: \"Help me tighten this cover letter for a product design role.\", answer: \"Lead with the outcome from your best project, not your title. Cut the second paragraph to two sentences and end with one specific reason you want this team.\" },\n  { id: \"c13\", title: \"Compare vector databases\", daysAgo: 58, project: \"eng\", archived: true, prompt: \"Compare three vector databases for a small RAG app.\", answer: \"For under a million vectors, a Postgres extension keeps everything in one place. Move to a dedicated store when you need filtering at scale or very low latency.\" },\n];\nconst REPLY = \"Good follow-up. Here's a tighter version, and I kept the parts you liked from the first draft.\";\n\nconst GROUPS = [\"Today\", \"Yesterday\", \"Previous 7 days\", \"Previous 30 days\", \"Older\"] as const;\nconst groupOf = (d: number) => (d <= 0 ? GROUPS[0] : d === 1 ? GROUPS[1] : d <= 7 ? GROUPS[2] : d <= 30 ? GROUPS[3] : GROUPS[4]);\nconst initials = (n: string) =>\n  n\n    .split(/\\s+/)\n    .map((w) => w[0])\n    .join(\"\")\n    .slice(0, 2)\n    .toUpperCase();\n\nfunction Highlight({ text, q, color }: { text: string; q: string; color: string }) {\n  if (!q) return <>{text}</>;\n  const i = text.toLowerCase().indexOf(q.toLowerCase());\n  if (i < 0) return <>{text}</>;\n  return (\n    <>\n      {text.slice(0, i)}\n      <mark className=\"rounded-[3px] bg-transparent px-0 font-semibold\" style={{ color, boxShadow: `inset 0 -0.5em 0 ${color}33` }}>\n        {text.slice(i, i + q.length)}\n      </mark>\n      {text.slice(i + q.length)}\n    </>\n  );\n}\n\nconst Icon = {\n  panel: (\n    <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" aria-hidden=\"true\" className=\"shrink-0\">\n      <rect x=\"3.5\" y=\"4.5\" width=\"17\" height=\"15\" rx=\"3\" />\n      <path d=\"M9.5 4.5v15\" />\n    </svg>\n  ),\n  pen: (\n    <svg width=\"17\" height=\"17\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" className=\"shrink-0\">\n      <path d=\"M4 20h4L19 9l-4-4L4 16z\" />\n      <path d=\"m13.5 6.5 4 4\" />\n    </svg>\n  ),\n  search: (\n    <svg width=\"17\" height=\"17\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" aria-hidden=\"true\" className=\"shrink-0\">\n      <circle cx=\"11\" cy=\"11\" r=\"6.5\" />\n      <path d=\"m20 20-4-4\" />\n    </svg>\n  ),\n  dots: (\n    <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden=\"true\" className=\"shrink-0\">\n      <circle cx=\"5\" cy=\"12\" r=\"1.7\" />\n      <circle cx=\"12\" cy=\"12\" r=\"1.7\" />\n      <circle cx=\"19\" cy=\"12\" r=\"1.7\" />\n    </svg>\n  ),\n  pin: (\n    <svg width=\"13\" height=\"13\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" className=\"shrink-0\">\n      <path d=\"M12 17v5M8 3h8l-1 6 3 4H6l3-4z\" />\n    </svg>\n  ),\n  box: (\n    <svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinejoin=\"round\" aria-hidden=\"true\" className=\"shrink-0\">\n      <path d=\"M3.5 7.5h17v3h-17zM5 10.5v9h14v-9M10 14h4\" />\n    </svg>\n  ),\n  send: (\n    <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" className=\"shrink-0\">\n      <path d=\"M12 19V5M5 12l7-7 7 7\" />\n    </svg>\n  ),\n};\n\nexport function ChatHistorySidebar({\n  workspace = \"Lumen\",\n  model = \"Lumen 3\",\n  chats: chatsProp,\n  projects = DEFAULT_PROJECTS,\n  user = { name: \"Mara Okafor\", plan: \"Pro\" },\n  defaultActiveId = \"c2\",\n  defaultCollapsed = false,\n  onSelect,\n  onNew,\n  onRename,\n  onDelete,\n  theme = \"dark\",\n  className,\n}: ChatHistorySidebarProps) {\n  const p = PALETTES[theme];\n  const reduce = !!useReducedMotion();\n  const uid = React.useId();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const sideRef = React.useRef<HTMLElement>(null);\n  const searchRef = React.useRef<HTMLInputElement>(null);\n  const [chats, setChats] = React.useState<HistoryChat[]>(() => chatsProp ?? DEFAULT_CHATS);\n  const [active, setActive] = React.useState<string | null>(defaultActiveId);\n  const [collapsed, setCollapsed] = React.useState(defaultCollapsed);\n  const [narrow, setNarrow] = React.useState(false);\n  const [drawer, setDrawer] = React.useState(false);\n  const [q, setQ] = React.useState(\"\");\n  const [projectFilter, setProjectFilter] = React.useState<string | null>(null);\n  const [view, setView] = React.useState<\"chats\" | \"archived\">(\"chats\");\n  const [menu, setMenu] = React.useState<{ id: string; top: number } | null>(null);\n  const [renaming, setRenaming] = React.useState<string | null>(null);\n  const [toast, setToast] = React.useState<{ chat: HistoryChat; index: number; kind: \"deleted\" | \"archived\"; n: number } | null>(null);\n  const [extra, setExtra] = React.useState<Record<string, Msg[]>>({});\n  const [draft, setDraft] = React.useState(\"\");\n  const [typing, setTyping] = React.useState(false);\n  const seq = React.useRef(0);\n\n  React.useEffect(() => {\n    const el = rootRef.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([e]) => setNarrow(e.contentRect.width < 720));\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n\n  React.useEffect(() => {\n    if (!toast) return;\n    const id = setTimeout(() => setToast(null), 5000);\n    return () => clearTimeout(id);\n  }, [toast]);\n\n  React.useEffect(() => {\n    if (!typing) return;\n    const target = active;\n    const id = setTimeout(() => {\n      setTyping(false);\n      if (!target) return;\n      seq.current += 1;\n      const n = seq.current;\n      setExtra((x) => ({ ...x, [target]: [...(x[target] ?? []), { id: `r${n}`, from: \"assistant\", text: REPLY }] }));\n    }, 900);\n    return () => clearTimeout(id);\n  }, [typing, active]);\n\n  React.useEffect(() => {\n    if (!menu) return;\n    const close = (e: PointerEvent) => {\n      if (!(e.target as HTMLElement).closest(\"[data-history-menu]\")) setMenu(null);\n    };\n    const key = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") {\n        const id = menu.id;\n        setMenu(null);\n        requestAnimationFrame(() => document.getElementById(`${uid}-more-${id}`)?.focus());\n      }\n    };\n    window.addEventListener(\"pointerdown\", close);\n    window.addEventListener(\"keydown\", key);\n    return () => {\n      window.removeEventListener(\"pointerdown\", close);\n      window.removeEventListener(\"keydown\", key);\n    };\n  }, [menu, uid]);\n\n  const query = q.trim();\n  const visible = chats.filter((c) => (view === \"archived\" ? c.archived : !c.archived) && (!projectFilter || c.project === projectFilter) && (!query || `${c.title} ${c.answer}`.toLowerCase().includes(query.toLowerCase())));\n  const pinned = view === \"chats\" ? visible.filter((c) => c.pinned) : [];\n  const grouped = GROUPS.map((g) => ({ g, items: visible.filter((c) => (view === \"archived\" || !c.pinned) && groupOf(c.daysAgo) === g) })).filter((x) => x.items.length);\n  const archivedCount = chats.filter((c) => c.archived).length;\n  const chat = chats.find((c) => c.id === active) ?? null;\n  const projectOf = (id?: string) => projects.find((x) => x.id === id);\n  const sideOpen = narrow ? drawer : !collapsed;\n\n  const select = (id: string) => {\n    setActive(id);\n    setMenu(null);\n    if (narrow) setDrawer(false);\n    onSelect?.(id);\n  };\n  const newChat = () => {\n    setActive(null);\n    setView(\"chats\");\n    if (narrow) setDrawer(false);\n    onNew?.();\n  };\n  const update = (id: string, patch: Partial<HistoryChat>) => setChats((cs) => cs.map((c) => (c.id === id ? { ...c, ...patch } : c)));\n  const remove = (id: string, kind: \"deleted\" | \"archived\") => {\n    const index = chats.findIndex((c) => c.id === id);\n    const c = chats[index];\n    if (!c) return;\n    seq.current += 1;\n    setToast({ chat: c, index, kind, n: seq.current });\n    if (kind === \"deleted\") {\n      setChats((cs) => cs.filter((x) => x.id !== id));\n      onDelete?.(id);\n    } else update(id, { archived: true, pinned: false });\n    if (active === id) setActive(null);\n    setMenu(null);\n  };\n  const undo = () => {\n    if (!toast) return;\n    const { chat: c, index } = toast;\n    setChats((cs) => (cs.some((x) => x.id === c.id) ? cs.map((x) => (x.id === c.id ? c : x)) : [...cs.slice(0, index), c, ...cs.slice(index)]));\n    setToast(null);\n  };\n  const openMenu = (id: string, btn: HTMLElement) => {\n    if (menu?.id === id) return setMenu(null);\n    const side = sideRef.current?.getBoundingClientRect();\n    const r = btn.getBoundingClientRect();\n    if (!side) return;\n    const h = 292;\n    const below = r.bottom - side.top + 4;\n    setMenu({ id, top: below + h > side.height - 8 ? Math.max(8, r.top - side.top - h - 4) : below });\n  };\n  const send = (raw: string) => {\n    const text = raw.trim();\n    if (!text || typing) return;\n    seq.current += 1;\n    const n = seq.current;\n    let id = active;\n    if (!id) {\n      id = `new${n}`;\n      const fresh: HistoryChat = { id, title: text.length > 34 ? `${text.slice(0, 34)}…` : text, daysAgo: 0, prompt: text, answer: \"\" };\n      setChats((cs) => [fresh, ...cs]);\n      setActive(id);\n      setView(\"chats\");\n    } else {\n      const target = id;\n      setExtra((x) => ({ ...x, [target]: [...(x[target] ?? []), { id: `u${n}`, from: \"user\", text }] }));\n    }\n    setDraft(\"\");\n    setTyping(true);\n  };\n\n  const rowBtn = (c: HistoryChat) => {\n    const isActive = c.id === active;\n    const proj = projectOf(c.project);\n    return (\n      <motion.li key={c.id} layout={reduce ? false : \"position\"} initial={reduce ? false : { opacity: 0, x: -8 }} animate={{ opacity: 1, x: 0 }} exit={reduce ? undefined : { opacity: 0, x: -16, height: 0, marginTop: 0 }} transition={{ duration: 0.2 }} className=\"group relative\">\n        {isActive && <motion.span layoutId={`${uid}-active`} className=\"absolute inset-0 rounded-lg\" style={{ background: p.active }} transition={{ type: \"spring\", stiffness: 500, damping: 40 }} />}\n        {renaming === c.id ? (\n          <form\n            className=\"relative px-1 py-0.5\"\n            onSubmit={(e) => {\n              e.preventDefault();\n              const v = String(new FormData(e.currentTarget).get(\"t\") ?? \"\").trim();\n              if (v) {\n                update(c.id, { title: v });\n                onRename?.(c.id, v);\n              }\n              setRenaming(null);\n            }}\n          >\n            <label className=\"sr-only\" htmlFor={`${uid}-rn-${c.id}`}>\n              Rename chat\n            </label>\n            <input\n              id={`${uid}-rn-${c.id}`}\n              name=\"t\"\n              defaultValue={c.title}\n              ref={(el) => {\n                if (el && document.activeElement !== el && !el.dataset.f) {\n                  el.dataset.f = \"1\";\n                  el.focus({ preventScroll: true });\n                  el.select();\n                }\n              }}\n              onBlur={(e) => e.currentTarget.form?.requestSubmit()}\n              onKeyDown={(e) => {\n                if (e.key === \"Escape\") {\n                  e.stopPropagation();\n                  setRenaming(null);\n                }\n              }}\n              className=\"h-8 w-full rounded-md border px-2 text-[13.5px] outline-none\"\n              style={{ background: p.card, borderColor: p.accent, color: p.text }}\n            />\n          </form>\n        ) : (\n          <div className=\"relative flex items-center\">\n            <button\n              type=\"button\"\n              onClick={() => select(c.id)}\n              aria-current={isActive ? \"page\" : undefined}\n              className=\"flex h-9 min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-lg border-0 bg-transparent pr-8 pl-2.5 text-left text-[13.5px] outline-none hover:bg-[var(--h)] focus-visible:ring-2\"\n              style={{ color: isActive ? p.text : p.muted, [\"--h\" as string]: isActive ? \"transparent\" : p.hover, [\"--tw-ring-color\" as string]: p.ring }}\n            >\n              {proj && !projectFilter && <span aria-hidden=\"true\" className=\"h-1.5 w-1.5 shrink-0 rounded-full\" style={{ background: proj.color }} />}\n              <span className=\"min-w-0 flex-1 truncate\">\n                <Highlight text={c.title} q={query} color={p.accent} />\n              </span>\n            </button>\n            <button\n              id={`${uid}-more-${c.id}`}\n              type=\"button\"\n              data-history-menu\n              aria-label={`Options for ${c.title}`}\n              aria-haspopup=\"menu\"\n              aria-expanded={menu?.id === c.id}\n              onClick={(e) => openMenu(c.id, e.currentTarget)}\n              className={cn(\"absolute right-1 grid h-7 w-7 cursor-pointer place-items-center rounded-md border-0 bg-transparent outline-none focus-visible:ring-2 focus-visible:opacity-100 [@media(hover:none)]:opacity-100\", isActive || menu?.id === c.id ? \"opacity-100\" : \"opacity-0 group-hover:opacity-100\")}\n              style={{ color: p.muted, [\"--tw-ring-color\" as string]: p.ring }}\n            >\n              {Icon.dots}\n            </button>\n          </div>\n        )}\n      </motion.li>\n    );\n  };\n\n  const menuChat = menu ? chats.find((c) => c.id === menu.id) : null;\n  const msgs: Msg[] = chat ? [...(chat.answer ? [{ id: \"p\", from: \"user\" as const, text: chat.prompt }, { id: \"a\", from: \"assistant\" as const, text: chat.answer }] : [{ id: \"p\", from: \"user\" as const, text: chat.prompt }]), ...(extra[chat.id] ?? [])] : [];\n\n  const sidebar = (\n    <motion.aside\n      ref={sideRef}\n      aria-label=\"Chat history\"\n      initial={false}\n      animate={narrow ? { x: drawer ? 0 : -300, width: 284 } : { x: 0, width: collapsed ? 60 : 272 }}\n      transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 380, damping: 38 }}\n      className={cn(\"relative z-20 flex h-full shrink-0 flex-col overflow-hidden border-r\", narrow && \"absolute inset-y-0 left-0 shadow-[0_20px_60px_rgba(0,0,0,0.5)]\")}\n      style={{ background: p.side, borderColor: p.border }}\n      inert={narrow && !drawer ? true : undefined}\n    >\n      {/* Top */}\n      <div className={cn(\"flex h-14 shrink-0 items-center gap-2 px-3\", !sideOpen && \"flex-col justify-center\")}>\n        {sideOpen && (\n          <span className=\"flex min-w-0 flex-1 items-center gap-2 pl-1\">\n            <span className=\"grid h-6 w-6 shrink-0 place-items-center rounded-md text-[12px] font-bold\" style={{ background: p.on, color: p.onText }}>\n              {workspace[0]}\n            </span>\n            <span className=\"truncate text-[14px] font-semibold\">{workspace}</span>\n          </span>\n        )}\n        <button\n          type=\"button\"\n          onClick={() => (narrow ? setDrawer(false) : setCollapsed((v) => !v))}\n          aria-label={narrow ? \"Close sidebar\" : collapsed ? \"Expand sidebar\" : \"Collapse sidebar\"}\n          aria-expanded={sideOpen}\n          className=\"grid h-8 w-8 shrink-0 cursor-pointer place-items-center rounded-lg border-0 bg-transparent outline-none hover:bg-[var(--h)] focus-visible:ring-2\"\n          style={{ color: p.muted, [\"--h\" as string]: p.hover, [\"--tw-ring-color\" as string]: p.ring }}\n        >\n          {Icon.panel}\n        </button>\n      </div>\n\n      {/* Actions */}\n      <div className={cn(\"shrink-0 space-y-1 px-3\", !sideOpen && \"flex flex-col items-center\")}>\n        <button\n          type=\"button\"\n          onClick={newChat}\n          aria-label={sideOpen ? undefined : \"New chat\"}\n          className={cn(\"flex h-9 cursor-pointer items-center gap-2.5 rounded-lg border-0 text-[13.5px] font-medium outline-none focus-visible:ring-2\", sideOpen ? \"w-full px-2.5\" : \"w-9 justify-center\")}\n          style={{ background: active === null && view === \"chats\" ? p.active : \"transparent\", color: p.text, [\"--tw-ring-color\" as string]: p.ring }}\n        >\n          {Icon.pen}\n          {sideOpen && <span className=\"flex-1 text-left\">New chat</span>}\n        </button>\n        {sideOpen ? (\n          <label className=\"flex h-9 items-center gap-2.5 rounded-lg border px-2.5\" style={{ borderColor: p.border, background: p.bg }}>\n            <span style={{ color: p.faint }}>{Icon.search}</span>\n            <span className=\"sr-only\">Search chats</span>\n            <input ref={searchRef} value={q} onChange={(e) => setQ(e.target.value)} placeholder=\"Search chats\" className=\"h-full min-w-0 flex-1 border-0 bg-transparent text-[13.5px] outline-none\" style={{ color: p.text }} />\n            {q ? (\n              <button type=\"button\" onClick={() => setQ(\"\")} aria-label=\"Clear search\" className=\"cursor-pointer border-0 bg-transparent text-[15px] leading-none\" style={{ color: p.faint }}>\n                ×\n              </button>\n            ) : (\n              <kbd className=\"rounded border px-1 font-sans text-[10.5px]\" style={{ borderColor: p.border, color: p.faint }}>\n                ⌘K\n              </kbd>\n            )}\n          </label>\n        ) : (\n          <button\n            type=\"button\"\n            onClick={() => {\n              setCollapsed(false);\n              requestAnimationFrame(() => searchRef.current?.focus({ preventScroll: true }));\n            }}\n            aria-label=\"Search chats\"\n            className=\"grid h-9 w-9 cursor-pointer place-items-center rounded-lg border-0 bg-transparent outline-none hover:bg-[var(--h)] focus-visible:ring-2\"\n            style={{ color: p.text, [\"--h\" as string]: p.hover, [\"--tw-ring-color\" as string]: p.ring }}\n          >\n            {Icon.search}\n          </button>\n        )}\n      </div>\n\n      {/* Lists */}\n      {sideOpen ? (\n        <div className=\"mt-3 min-h-0 flex-1 overflow-y-auto overscroll-contain px-3 pb-3 [scrollbar-width:thin]\" onScroll={() => menu && setMenu(null)}>\n          {view === \"chats\" && (\n            <>\n              <p className=\"m-0 px-2.5 pb-1 text-[11px] font-semibold tracking-[0.08em] uppercase\" style={{ color: p.faint }}>\n                Projects\n              </p>\n              <ul className=\"m-0 mb-3 list-none p-0\">\n                {projects.map((pr) => {\n                  const on = projectFilter === pr.id;\n                  const count = chats.filter((c) => c.project === pr.id && !c.archived).length;\n                  return (\n                    <li key={pr.id}>\n                      <button\n                        type=\"button\"\n                        aria-pressed={on}\n                        onClick={() => setProjectFilter(on ? null : pr.id)}\n                        className=\"flex h-8 w-full cursor-pointer items-center gap-2.5 rounded-lg border-0 px-2.5 text-left text-[13px] outline-none hover:bg-[var(--h)] focus-visible:ring-2\"\n                        style={{ background: on ? p.accentSoft : \"transparent\", color: on ? p.text : p.muted, [\"--h\" as string]: on ? p.accentSoft : p.hover, [\"--tw-ring-color\" as string]: p.ring }}\n                      >\n                        <svg width=\"15\" height=\"15\" viewBox=\"0 0 24 24\" fill=\"none\" stroke={pr.color} strokeWidth=\"2\" strokeLinejoin=\"round\" aria-hidden=\"true\" className=\"shrink-0\">\n                          <path d=\"M3.5 6.5h6l2 2h9v10h-17z\" fill={on ? pr.color : \"none\"} fillOpacity={0.25} />\n                        </svg>\n                        <span className=\"min-w-0 flex-1 truncate\">{pr.name}</span>\n                        <span className=\"text-[11.5px] tabular-nums\" style={{ color: p.faint }}>\n                          {count}\n                        </span>\n                      </button>\n                    </li>\n                  );\n                })}\n              </ul>\n            </>\n          )}\n          {view === \"archived\" && (\n            <button type=\"button\" onClick={() => setView(\"chats\")} className=\"mb-2 flex h-8 cursor-pointer items-center gap-1.5 rounded-lg border-0 bg-transparent px-2 text-[13px] font-medium outline-none focus-visible:ring-2\" style={{ color: p.text, [\"--tw-ring-color\" as string]: p.ring }}>\n              <span aria-hidden=\"true\">←</span> Archived chats\n            </button>\n          )}\n\n          <p className=\"sr-only\" aria-live=\"polite\">\n            {query ? `${visible.length} ${visible.length === 1 ? \"chat\" : \"chats\"} found` : \"\"}\n          </p>\n          {pinned.length > 0 && (\n            <section aria-label=\"Pinned\">\n              <p className=\"m-0 flex items-center gap-1.5 px-2.5 pb-1 text-[11px] font-semibold tracking-[0.08em] uppercase\" style={{ color: p.faint }}>\n                {Icon.pin} Pinned\n              </p>\n              <ul className=\"m-0 mb-3 list-none p-0\">\n                <AnimatePresence initial={false}>{pinned.map(rowBtn)}</AnimatePresence>\n              </ul>\n            </section>\n          )}\n          {grouped.map(({ g, items }) => (\n            <section key={g} aria-label={g}>\n              <p className=\"m-0 px-2.5 pb-1 text-[11px] font-semibold tracking-[0.08em] uppercase\" style={{ color: p.faint }}>\n                {g}\n              </p>\n              <ul className=\"m-0 mb-3 list-none p-0\">\n                <AnimatePresence initial={false}>{items.map(rowBtn)}</AnimatePresence>\n              </ul>\n            </section>\n          ))}\n          {!visible.length && (\n            <div className=\"px-2.5 py-6 text-center text-[13px]\" style={{ color: p.muted }}>\n              {query ? `No chats match “${query}”.` : view === \"archived\" ? \"Nothing archived.\" : \"No chats in this project yet.\"}\n            </div>\n          )}\n        </div>\n      ) : (\n        <div className=\"mt-4 flex flex-1 flex-col items-center gap-2\">\n          {projects.map((pr) => (\n            <button\n              key={pr.id}\n              type=\"button\"\n              aria-label={`${pr.name} project`}\n              aria-pressed={projectFilter === pr.id}\n              onClick={() => {\n                setProjectFilter(pr.id);\n                setCollapsed(false);\n              }}\n              className=\"grid h-9 w-9 cursor-pointer place-items-center rounded-lg border-0 bg-transparent outline-none hover:bg-[var(--h)] focus-visible:ring-2\"\n              style={{ [\"--h\" as string]: p.hover, [\"--tw-ring-color\" as string]: p.ring }}\n            >\n              <span className=\"h-2.5 w-2.5 rounded-full\" style={{ background: pr.color, boxShadow: projectFilter === pr.id ? `0 0 0 2px ${p.side}, 0 0 0 3.5px ${pr.color}` : undefined }} />\n            </button>\n          ))}\n        </div>\n      )}\n\n      {/* Bottom */}\n      <div className={cn(\"shrink-0 border-t p-3\", !sideOpen && \"flex flex-col items-center\")} style={{ borderColor: p.border }}>\n        {sideOpen && view === \"chats\" && archivedCount > 0 && (\n          <button type=\"button\" onClick={() => setView(\"archived\")} className=\"mb-2 flex h-8 w-full cursor-pointer items-center gap-2.5 rounded-lg border-0 bg-transparent px-2.5 text-[13px] outline-none hover:bg-[var(--h)] focus-visible:ring-2\" style={{ color: p.muted, [\"--h\" as string]: p.hover, [\"--tw-ring-color\" as string]: p.ring }}>\n            {Icon.box}\n            <span className=\"flex-1 text-left\">Archived</span>\n            <span className=\"text-[11.5px] tabular-nums\" style={{ color: p.faint }}>\n              {archivedCount}\n            </span>\n          </button>\n        )}\n        <div className=\"flex items-center gap-2.5\">\n          <span className=\"grid h-8 w-8 shrink-0 place-items-center rounded-full text-[12px] font-semibold\" style={{ background: p.accentSoft, color: p.accent }} aria-hidden={!sideOpen ? undefined : true} title={sideOpen ? undefined : user.name}>\n            {initials(user.name)}\n          </span>\n          {sideOpen && (\n            <span className=\"min-w-0 flex-1\">\n              <span className=\"block truncate text-[13px] font-medium\">{user.name}</span>\n              {user.plan && (\n                <span className=\"block text-[11.5px]\" style={{ color: p.faint }}>\n                  {user.plan} plan\n                </span>\n              )}\n            </span>\n          )}\n        </div>\n      </div>\n\n      {/* Row menu */}\n      <AnimatePresence>\n        {menu && menuChat && sideOpen && (\n          <motion.div\n            key=\"menu\"\n            data-history-menu\n            role=\"menu\"\n            aria-label={`Options for ${menuChat.title}`}\n            initial={reduce ? false : { opacity: 0, scale: 0.96, y: -4 }}\n            animate={{ opacity: 1, scale: 1, y: 0 }}\n            exit={reduce ? undefined : { opacity: 0, scale: 0.97 }}\n            transition={{ duration: 0.14 }}\n            className=\"absolute right-3 z-30 w-[200px] origin-top-right rounded-xl border p-1 shadow-[0_18px_40px_-12px_rgba(0,0,0,0.5)]\"\n            style={{ top: menu.top, background: p.menu, borderColor: p.border }}\n            onKeyDown={(e) => {\n              if (e.key !== \"ArrowDown\" && e.key !== \"ArrowUp\") return;\n              e.preventDefault();\n              const items = [...e.currentTarget.querySelectorAll<HTMLElement>(\"[role^=menuitem]\")];\n              const i = items.indexOf(document.activeElement as HTMLElement);\n              items[(i + (e.key === \"ArrowDown\" ? 1 : -1) + items.length) % items.length]?.focus();\n            }}\n          >\n            {(() => {\n              const item = \"flex h-8 w-full cursor-pointer items-center gap-2 rounded-lg border-0 bg-transparent px-2.5 text-left text-[13px] outline-none hover:bg-[var(--h)] focus-visible:bg-[var(--h)]\";\n              const st = { color: p.text, [\"--h\" as string]: p.hover } as React.CSSProperties;\n              return (\n                <>\n                  <button\n                    type=\"button\"\n                    role=\"menuitem\"\n                    className={item}\n                    style={st}\n                    ref={(el) => {\n                      if (el && !el.dataset.f) {\n                        el.dataset.f = \"1\";\n                        el.focus({ preventScroll: true });\n                      }\n                    }}\n                    onClick={() => {\n                      setRenaming(menuChat.id);\n                      setMenu(null);\n                    }}\n                  >\n                    Rename\n                  </button>\n                  {view === \"chats\" ? (\n                    <>\n                      <button type=\"button\" role=\"menuitem\" className={item} style={st} onClick={() => { update(menuChat.id, { pinned: !menuChat.pinned }); setMenu(null); }}>\n                        {menuChat.pinned ? \"Unpin\" : \"Pin to top\"}\n                      </button>\n                      <button type=\"button\" role=\"menuitem\" className={item} style={st} onClick={() => remove(menuChat.id, \"archived\")}>\n                        Archive\n                      </button>\n                    </>\n                  ) : (\n                    <button type=\"button\" role=\"menuitem\" className={item} style={st} onClick={() => { update(menuChat.id, { archived: false, daysAgo: 0 }); setMenu(null); }}>\n                      Restore\n                    </button>\n                  )}\n                  <div className=\"my-1 h-px\" style={{ background: p.border }} />\n                  <p className=\"m-0 px-2.5 pt-1 pb-0.5 text-[10.5px] font-semibold tracking-[0.08em] uppercase\" style={{ color: p.faint }}>\n                    Move to\n                  </p>\n                  {[...projects, { id: \"\", name: \"No project\", color: p.faint }].map((pr) => {\n                    const on = (menuChat.project ?? \"\") === pr.id;\n                    return (\n                      <button key={pr.id || \"none\"} type=\"button\" role=\"menuitemradio\" aria-checked={on} className={item} style={st} onClick={() => { update(menuChat.id, { project: pr.id || undefined }); setMenu(null); }}>\n                        <span className=\"h-2 w-2 shrink-0 rounded-full\" style={{ background: pr.color }} aria-hidden=\"true\" />\n                        <span className=\"flex-1\">{pr.name}</span>\n                        {on && (\n                          <svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2.2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\" className=\"shrink-0\" style={{ color: p.accent }}>\n                            <path d=\"m5 12 5 5 9-10\" />\n                          </svg>\n                        )}\n                      </button>\n                    );\n                  })}\n                  <div className=\"my-1 h-px\" style={{ background: p.border }} />\n                  <button type=\"button\" role=\"menuitem\" className={item} style={{ ...st, color: p.danger }} onClick={() => remove(menuChat.id, \"deleted\")}>\n                    Delete\n                  </button>\n                </>\n              );\n            })()}\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </motion.aside>\n  );\n\n  return (\n    <div\n      ref={rootRef}\n      className={cn(\"relative isolate flex h-[640px] w-full overflow-hidden\", className)}\n      style={{ background: p.bg, color: p.text }}\n      onKeyDown={(e) => {\n        if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"k\") {\n          e.preventDefault();\n          if (narrow) setDrawer(true);\n          else setCollapsed(false);\n          requestAnimationFrame(() => searchRef.current?.focus({ preventScroll: true }));\n        }\n      }}\n    >\n      {sidebar}\n      <AnimatePresence>\n        {narrow && drawer && (\n          <motion.button\n            key=\"scrim\"\n            type=\"button\"\n            aria-label=\"Close sidebar\"\n            tabIndex={-1}\n            initial={{ opacity: 0 }}\n            animate={{ opacity: 1 }}\n            exit={{ opacity: 0 }}\n            onClick={() => setDrawer(false)}\n            className=\"absolute inset-0 z-10 cursor-default border-0\"\n            style={{ background: p.scrim }}\n          />\n        )}\n      </AnimatePresence>\n\n      {/* Main */}\n      <main className=\"relative flex min-w-0 flex-1 flex-col\">\n        <header className=\"flex h-14 shrink-0 items-center gap-2 border-b px-3\" style={{ borderColor: p.border }}>\n          {narrow && (\n            <button type=\"button\" onClick={() => setDrawer(true)} aria-label=\"Open chat history\" aria-expanded={drawer} className=\"grid h-8 w-8 shrink-0 cursor-pointer place-items-center rounded-lg border-0 bg-transparent outline-none focus-visible:ring-2\" style={{ color: p.muted, [\"--tw-ring-color\" as string]: p.ring }}>\n              {Icon.panel}\n            </button>\n          )}\n          <span className=\"flex h-8 shrink-0 items-center gap-1.5 rounded-lg border px-2.5 text-[12.5px] font-medium\" style={{ borderColor: p.border }}>\n            <span className=\"h-1.5 w-1.5 rounded-full\" style={{ background: p.accent }} aria-hidden=\"true\" />\n            {model}\n          </span>\n          <span className=\"min-w-0 flex-1 truncate pl-1 text-[13.5px]\" style={{ color: p.muted }}>\n            {chat ? chat.title : \"New chat\"}\n          </span>\n          {chat && projectOf(chat.project) && (\n            <span className=\"hidden shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1 text-[11.5px] @min-[520px]:flex sm:flex\" style={{ background: p.hover, color: p.muted }}>\n              <span className=\"h-1.5 w-1.5 rounded-full\" style={{ background: projectOf(chat.project)!.color }} />\n              {projectOf(chat.project)!.name}\n            </span>\n          )}\n        </header>\n\n        <div className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain\">\n          <AnimatePresence mode=\"wait\" initial={false}>\n            <motion.div key={chat?.id ?? \"new\"} initial={reduce ? false : { opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }} exit={reduce ? undefined : { opacity: 0 }} transition={{ duration: 0.18 }} className=\"mx-auto flex min-h-full max-w-[640px] flex-col px-4 py-6\">\n              {chat ? (\n                <ul className=\"m-0 flex list-none flex-col gap-5 p-0\" aria-live=\"polite\">\n                  {msgs.map((m) =>\n                    m.from === \"user\" ? (\n                      <li key={m.id} className=\"flex justify-end\">\n                        <span className=\"max-w-[85%] rounded-2xl px-4 py-2.5 text-[14px] leading-[1.5]\" style={{ background: p.user, border: `1px solid ${p.border}` }}>\n                          {m.text}\n                        </span>\n                      </li>\n                    ) : (\n                      <li key={m.id} className=\"flex gap-3\">\n                        <span className=\"mt-0.5 grid h-7 w-7 shrink-0 place-items-center rounded-full border text-[12px] font-bold\" style={{ borderColor: p.border, color: p.accent }} aria-hidden=\"true\">\n                          ✦\n                        </span>\n                        <span className=\"min-w-0 flex-1 text-[14px] leading-[1.65] whitespace-pre-line\">{m.text}</span>\n                      </li>\n                    ),\n                  )}\n                  {typing && (\n                    <li className=\"flex gap-3\" aria-label=\"Assistant is typing\">\n                      <span className=\"mt-0.5 grid h-7 w-7 shrink-0 place-items-center rounded-full border text-[12px] font-bold\" style={{ borderColor: p.border, color: p.accent }} aria-hidden=\"true\">\n                        ✦\n                      </span>\n                      <span className=\"flex items-center gap-1 pt-2\">\n                        {[0, 1, 2].map((i) => (\n                          <motion.span key={i} className=\"h-1.5 w-1.5 rounded-full\" style={{ background: p.muted }} animate={reduce ? undefined : { opacity: [0.3, 1, 0.3] }} transition={{ duration: 0.9, repeat: Infinity, delay: i * 0.15 }} />\n                        ))}\n                      </span>\n                    </li>\n                  )}\n                </ul>\n              ) : (\n                <div className=\"my-auto text-center\">\n                  <p className=\"m-0 text-[24px] font-semibold tracking-[-0.02em]\">What are we working on?</p>\n                  <p className=\"m-0 mt-2 text-[14px]\" style={{ color: p.muted }}>\n                    {projectFilter ? `New chat in ${projectOf(projectFilter)?.name}` : \"Start a chat, or pick one from your history.\"}\n                  </p>\n                </div>\n              )}\n            </motion.div>\n          </AnimatePresence>\n        </div>\n\n        <form\n          className=\"mx-auto mb-4 flex w-[calc(100%-32px)] max-w-[640px] shrink-0 items-center gap-2 rounded-2xl border py-1.5 pr-1.5 pl-4\"\n          style={{ background: p.card, borderColor: p.border }}\n          onSubmit={(e) => {\n            e.preventDefault();\n            send(draft);\n          }}\n        >\n          <label className=\"sr-only\" htmlFor={`${uid}-composer`}>\n            Message {model}\n          </label>\n          <input id={`${uid}-composer`} value={draft} onChange={(e) => setDraft(e.target.value)} placeholder={`Message ${model}`} className=\"h-9 min-w-0 flex-1 border-0 bg-transparent text-[14px] outline-none\" style={{ color: p.text }} />\n          <button type=\"submit\" disabled={!draft.trim() || typing} aria-label=\"Send\" className=\"grid h-9 w-9 shrink-0 cursor-pointer place-items-center rounded-xl border-0 outline-none focus-visible:ring-2 disabled:cursor-not-allowed disabled:opacity-35\" style={{ background: p.on, color: p.onText, [\"--tw-ring-color\" as string]: p.ring }}>\n            {Icon.send}\n          </button>\n        </form>\n\n        {/* Undo toast */}\n        <AnimatePresence>\n          {toast && (\n            <motion.div key={toast.n} role=\"status\" initial={reduce ? false : { opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} exit={reduce ? undefined : { opacity: 0, y: 8 }} className=\"absolute bottom-20 left-1/2 z-10 flex -translate-x-1/2 items-center gap-3 rounded-xl border py-2 pr-2 pl-3.5 text-[13px] whitespace-nowrap shadow-[0_16px_32px_-12px_rgba(0,0,0,0.5)]\" style={{ background: p.menu, borderColor: p.border }}>\n              Chat {toast.kind}\n              <button type=\"button\" onClick={undo} className=\"h-7 cursor-pointer rounded-lg border-0 px-2.5 text-[12.5px] font-semibold outline-none focus-visible:ring-2\" style={{ background: p.accentSoft, color: p.accent, [\"--tw-ring-color\" as string]: p.ring }}>\n                Undo\n              </button>\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </main>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}