{"slug":"chat-app","name":"Chat App","description":"A complete agent conversation workspace composing navigation, messages, streaming, planning, approvals, tools, code, diffs, generated media, sources, and prompt input.","category":"agents","source_url":"https://beui.dev/r/chat-app/raw","detail_url":"https://beui.dev/r/chat-app","raw_url":"https://beui.dev/r/chat-app/raw","page_url":"https://beui.dev/components/agents/chat-app","markdown_url":"https://beui.dev/components/agents/chat-app.md","published_at":"2026-08-02","updated_at":"2026-11-28","dependencies":["@floating-ui/dom","clsx","lucide-react","motion","react","react-dom","shiki","tailwind-merge"],"internal":["../magnetic","./action-swap","./activity-row","./agent-progress","./ai-sidebar/messages","./ai-sidebar/resource-row","./ai-sidebar/tree","./ai-sidebar/types","./animated-sidebar/context","./animated-sidebar/menu-button","./animated-sidebar/menu-sub-button","./animated-sidebar/mobile-sidebar","./animated-sidebar/motion","./animated-sidebar/use-is-mobile","./base","./context","./dropdown-menu/context","./dropdown-menu/item-base","./dropdown-menu/menu-panel","./dropdown-menu/placement","./engine","./magnetic","./marquee-label","./messages","./metallic","./motion","./placement","./reasoning-text","./resource-menu-action","./stateful","./thinking-shimmer","./tooltip/grace","./tooltip/positioner","./tooltip/use-position","./tree","./types","./use-position","@/components/agents/agent-activity","@/components/agents/agent-code","@/components/agents/agent-disclosure","@/components/agents/ai-sidebar","@/components/agents/approval-card","@/components/agents/chat-app","@/components/agents/citations","@/components/agents/clip-resize-frame","@/components/agents/code-block","@/components/agents/file-diff","@/components/agents/icon-swap","@/components/agents/image-generation","@/components/agents/loading-states","@/components/agents/loading-states/thinking-shimmer","@/components/agents/message","@/components/agents/message-bubble","@/components/agents/message-context","@/components/agents/message-scroller","@/components/agents/prompt-input","@/components/agents/streaming-response","@/components/agents/todo-list","@/components/agents/tool-approval","@/components/agents/tool-result","@/components/motion/action-swap","@/components/motion/action-swap-roll","@/components/motion/animated-sidebar","@/components/motion/button","@/components/motion/checkbox","@/components/motion/dropdown-menu","@/components/motion/input","@/components/motion/loader","@/components/motion/menu/menu-item-highlight","@/components/motion/menu/use-menu-navigation","@/components/motion/popover-morph","@/components/motion/popover-position","@/components/motion/preview-rail","@/components/motion/radio","@/components/motion/shared-layout-bg","@/components/motion/text-scramble","@/components/motion/text-shimmer","@/components/motion/tooltip","@/components/motion/tooltip-surface","@/components/previews/agents/chat-app-usage","@/lib/audio-context","@/lib/ease","@/lib/favicon","@/lib/focusable","@/lib/hooks/use-controllable","@/lib/hooks/use-copy","@/lib/hooks/use-dismiss","@/lib/hooks/use-favicon","@/lib/hooks/use-focus-trap","@/lib/hooks/use-hover-capable","@/lib/hooks/use-hover-gesture","@/lib/hooks/use-row-cursor","@/lib/hooks/use-status-open","@/lib/hooks/use-tap-gesture","@/lib/hooks/use-touch-capable","@/lib/i18n","@/lib/layers","@/lib/merge-refs","@/lib/presence-gate","@/lib/scroll-lock","@/lib/sound","@/lib/sounds/close","@/lib/sounds/engine","@/lib/sounds/open","@/lib/sounds/press","@/lib/sounds/select","@/lib/text-shimmer","@/lib/touch","@/lib/utils"],"install_slugs":["chat-app"],"requires_theme":true,"props":[{"displayName":"ChatApp","props":[{"name":"sidebarWidth","type":"string","required":false,"defaultValue":"17rem","description":"Docked sidebar width as a CSS length. Default `17rem`."},{"name":"collapseSidebarBelow","type":"number","required":false,"defaultValue":"600","description":"Shell width in px under which the sidebar folds off-canvas. Ignored while\n`open` is controlled - the consumer owns the state then."},{"name":"open","type":"boolean","required":false,"defaultValue":null,"description":"Whether the desktop sidebar is expanded, for controlled use."},{"name":"defaultOpen","type":"boolean","required":false,"defaultValue":null,"description":"Whether the desktop sidebar starts expanded when uncontrolled. Default: true"},{"name":"onOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the next state when the desktop sidebar expands or collapses."},{"name":"openMobile","type":"boolean","required":false,"defaultValue":null,"description":"Whether the mobile drawer is open, for controlled use."},{"name":"defaultOpenMobile","type":"boolean","required":false,"defaultValue":null,"description":"Whether the mobile drawer starts open when uncontrolled. Default: false"},{"name":"onOpenMobileChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the next state when the mobile drawer opens or closes."},{"name":"style","type":"SidebarProviderStyle","required":false,"defaultValue":null,"description":"Inline styles; set `--sidebar-width`, `--sidebar-width-icon` or `--sidebar-width-mobile` here."},{"name":"labels","type":"Partial<{ label: string; toggle: string; close: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"AgentActivity","props":[{"name":"items","type":"AgentActivityItem[]","required":true,"defaultValue":null,"description":"Chronological activity entries. Append or update items as events stream."},{"name":"contentType","type":"\"search\" | \"text\" | \"mixed\" | \"step\" | \"tool\" | \"trace\"","required":false,"defaultValue":null,"description":"Expected activity kind before the first streamed item arrives."},{"name":"status","type":"\"complete\" | \"working\"","required":false,"defaultValue":"working","description":"Current run phase. Active runs always stay expanded."},{"name":"duration","type":"number","required":false,"defaultValue":"0","description":"Elapsed run time, in seconds. Used by the step-only summary."},{"name":"open","type":"boolean","required":false,"defaultValue":null,"description":"Controlled expanded state used after the run completes."},{"name":"defaultOpen","type":"boolean","required":false,"defaultValue":"false","description":"Initial expanded state used after the run completes."},{"name":"onOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called when the completed activity disclosure changes state."},{"name":"collapseOnComplete","type":"boolean","required":false,"defaultValue":"true","description":"Collapse the disclosure when status changes from working to complete."},{"name":"activeLabel","type":"ReactNode","required":false,"defaultValue":null,"description":"Optional label shown while the run is active."},{"name":"summary","type":"ReactNode","required":false,"defaultValue":null,"description":"Optional completed summary. Derived from the item types by default."},{"name":"renderWorkingStatus","type":"((context: { label: ReactNode; duration: number; }) => ReactNode)","required":false,"defaultValue":null,"description":"Optional renderer for the contents of the active status row."},{"name":"renderCompletedStatus","type":"((context: { summary: ReactNode; duration: number; }) => ReactNode)","required":false,"defaultValue":null,"description":"Optional renderer for the contents before the built-in disclosure chevron."},{"name":"maxHeight","type":"number","required":false,"defaultValue":"208","description":"Maximum visible activity height before the stream begins gliding."},{"name":"labels","type":"Partial<{ thinking: string; searching: string; runningTools: string; workingTrace: string; workingMixed: string; thoughtFor: string; seconds: string; minutes: string; minutesSeconds: string; searched: string; ... 13 more ...; run: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string. Pick `One`/`Other` keys by count; `{count}`, `{duration}`, `{seconds}` and `{minutes}` fill the matching messages."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."},{"name":"contentClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the list of activity items."}]},{"displayName":"AISidebar","props":[{"name":"items","type":"SidebarResource[]","required":false,"defaultValue":null,"description":"The resource tree, for controlled use."},{"name":"defaultItems","type":"SidebarResource[]","required":false,"defaultValue":"[]","description":"The initial resource tree when uncontrolled."},{"name":"onItemsChange","type":"((items: SidebarResource[]) => void)","required":false,"defaultValue":null,"description":"Called with the new tree after a move, rename or rollback."},{"name":"onMove","type":"((move: SidebarResourceMove) => void | Promise<void>)","required":false,"defaultValue":null,"description":"Reject the promise to roll the optimistic move back."},{"name":"onMoveError","type":"((error: unknown, move: SidebarResourceMove) => void)","required":false,"defaultValue":null,"description":"Called with the error and the move when `onMove` rejects."},{"name":"onRename","type":"((item: SidebarResource, label: string) => void | Promise<void>)","required":false,"defaultValue":null,"description":"Called with the item and trimmed new label. Reject to roll it back."},{"name":"activeId","type":"string | null","required":false,"defaultValue":null,"description":"Id of the selected row, for controlled use."},{"name":"defaultActiveId","type":"string | null","required":false,"defaultValue":"null","description":"Id of the initially selected row when uncontrolled. Default: null"},{"name":"onActiveChange","type":"((id: string) => void)","required":false,"defaultValue":null,"description":"Called with the row's id when a row is selected."},{"name":"defaultExpandedIds","type":"string[]","required":false,"defaultValue":"[]","description":"Ids of folders and projects that start expanded."},{"name":"renderIcon","type":"((item: SidebarResource) => ReactNode)","required":false,"defaultValue":null,"description":"Renders a row's icon in place of the built-in kind icon."},{"name":"renderMenu","type":"((item: SidebarResource, controls: SidebarResourceMenuControls) => ReactNode)","required":false,"defaultValue":null,"description":"Renders a row's actions menu, with controls to close, rename and move."},{"name":"ariaLabel","type":"string","required":false,"defaultValue":null,"description":"Accessible name for the tree. Default: \"Resources\""},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the tree element."},{"name":"labels","type":"Partial<{ label: string; rename: string; renameItem: string; actions: string; moveUp: string; moveDown: string; moveInto: string; moveOut: string; moveToTop: string; movePending: string; movedBefore: string; ... 5 more ...; unnamedItem: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."}]},{"displayName":"ApprovalCard","props":[{"name":"title","type":"ReactNode","required":false,"defaultValue":null,"description":"Heading of the card. A question's own title replaces it. Default: \"Approval required\""},{"name":"description","type":"ReactNode","required":false,"defaultValue":null,"description":"Supporting text under the title when there are no questions."},{"name":"questions","type":"ApprovalCardQuestion[]","required":false,"defaultValue":"[]","description":"Questions asked one step at a time. Replaces approve and reject buttons."},{"name":"status","type":"\"pending\" | \"submitting\" | \"approved\" | \"rejected\" | \"changes-requested\" | \"answered\"","required":false,"defaultValue":"pending","description":"Current state, which sets the badge, icon and whether the form shows. Default: \"pending\""},{"name":"answers","type":"ApprovalCardAnswers","required":false,"defaultValue":null,"description":"Answers keyed by question id, for controlled use."},{"name":"defaultAnswers","type":"ApprovalCardAnswers","required":false,"defaultValue":"{}","description":"The initial answers when uncontrolled."},{"name":"onAnswersChange","type":"((answers: ApprovalCardAnswers) => void)","required":false,"defaultValue":null,"description":"Called with all answers whenever one changes."},{"name":"step","type":"number","required":false,"defaultValue":null,"description":"Index of the shown question, for controlled use."},{"name":"defaultStep","type":"number","required":false,"defaultValue":"0","description":"The initial question index when uncontrolled. Default: 0"},{"name":"onStepChange","type":"((step: number) => void)","required":false,"defaultValue":null,"description":"Called with the new question index when the step changes."},{"name":"onSubmit","type":"((answers: ApprovalCardAnswers) => void)","required":false,"defaultValue":null,"description":"Called with all answers when the last question is submitted."},{"name":"onApprove","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the approve button is pressed."},{"name":"onReject","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the reject button is pressed. The button shows only when set."},{"name":"onRequestChanges","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the request changes button is pressed. The button shows only when set."},{"name":"onDismiss","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the close button is pressed. The button shows only when set."},{"name":"approveLabel","type":"ReactNode","required":false,"defaultValue":null,"description":"Text of the approve button. Default: \"Approve\""},{"name":"submitLabel","type":"ReactNode","required":false,"defaultValue":null,"description":"Text of the last question's submit button. Default: \"Submit response\""},{"name":"result","type":"ReactNode","required":false,"defaultValue":null,"description":"Shown in place of the form once the card is settled. Defaults to the status label."},{"name":"labels","type":"Partial<{ title: string; approve: string; submit: string; requestChanges: string; reject: string; dismiss: string; previousQuestion: string; nextQuestion: string; customPlaceholder: string; questionProgress: string; ... 6 more ...; answered: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"CodeBlock","props":[{"name":"code","type":"string","required":true,"defaultValue":null,"description":"The source code to show. May grow while `status` is \"streaming\"."},{"name":"language","type":"\"text\" | \"bash\" | \"diff\" | \"json\" | \"tsx\" | \"typescript\"","required":false,"defaultValue":"typescript","description":"Language for syntax highlighting, also shown in the header. Default: \"typescript\""},{"name":"filename","type":"ReactNode","required":false,"defaultValue":null,"description":"File name shown in the header."},{"name":"status","type":"\"streaming\" | \"complete\"","required":false,"defaultValue":"complete","description":"\"streaming\" shows Writing and follows new lines, \"complete\" shows Ready. Default: \"complete\""},{"name":"showLineNumbers","type":"boolean","required":false,"defaultValue":"true","description":"Shows a line number gutter. Default: true"},{"name":"highlightLines","type":"number[]","required":false,"defaultValue":"[]","description":"1-based line numbers to tint."},{"name":"maxHeight","type":"number","required":false,"defaultValue":"280","description":"Height in px before the code scrolls. Default: 280"},{"name":"wrap","type":"boolean","required":false,"defaultValue":"false","description":"Wraps long lines instead of scrolling sideways. Default: false"},{"name":"copyable","type":"boolean","required":false,"defaultValue":"true","description":"Shows the copy button. Default: true"},{"name":"onCopy","type":"(() => void | Promise<void>)","required":false,"defaultValue":null,"description":"Runs in place of the clipboard write when copy is pressed. Shows the copy button."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."},{"name":"labels","type":"Partial<{ writing: string; ready: string; copy: string; copied: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."}]},{"displayName":"FileDiff","props":[{"name":"file","type":"ReactNode","required":true,"defaultValue":null,"description":"File name or path shown in the header."},{"name":"lines","type":"FileDiffLine[]","required":true,"defaultValue":null,"description":"Diff lines, each added, removed or context, with optional line numbers."},{"name":"status","type":"\"streaming\" | \"complete\"","required":false,"defaultValue":"streaming","description":"\"streaming\" while lines arrive, \"complete\" once the edit lands. Default: \"streaming\""},{"name":"open","type":"boolean","required":false,"defaultValue":null,"description":"Whether the diff is expanded, for controlled use."},{"name":"defaultOpen","type":"boolean","required":false,"defaultValue":"true","description":"Whether the diff starts expanded when uncontrolled. Default: true"},{"name":"onOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the new state when the diff expands or collapses."},{"name":"collapseOnComplete","type":"boolean","required":false,"defaultValue":"true","description":"Fold the diff when status moves from streaming to complete. Default: true"},{"name":"maxHeight","type":"number","required":false,"defaultValue":"220","description":"Tallest the line viewport grows before it scrolls (px). Default: 220"},{"name":"language","type":"\"text\" | \"bash\" | \"diff\" | \"json\" | \"tsx\" | \"typescript\"","required":false,"defaultValue":"typescript","description":"Language used for syntax highlighting. Default: \"typescript\""},{"name":"copyText","type":"string","required":false,"defaultValue":null,"description":"Text the copy button writes to the clipboard. Shows the button when set."},{"name":"onCopy","type":"(() => void | Promise<void>)","required":false,"defaultValue":null,"description":"Runs instead of the clipboard write when the copy button is pressed."},{"name":"labels","type":"Partial<{ applying: string; applied: string; changes: string; copy: string; copied: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"ImageGeneration","props":[{"name":"children","type":"ReactNode","required":false,"defaultValue":null,"description":"The completed media. Pass an img, Next Image, canvas, video, or custom preview."},{"name":"status","type":"\"error\" | \"complete\" | \"queued\" | \"generating\" | \"refining\"","required":false,"defaultValue":"generating","description":"Generation stage. Sets the dither overlay, media blur and status line. Default: \"generating\""},{"name":"label","type":"string","required":false,"defaultValue":null,"description":"Accessible description. Defaults to a description derived from prompt."},{"name":"prompt","type":"string","required":false,"defaultValue":null,"description":"The prompt, shown in quotes under the status line."},{"name":"resolution","type":"string","required":false,"defaultValue":"1024 × 1024","description":"Badge in the top right corner. Default: \"1024 × 1024\""},{"name":"aspectRatio","type":"AspectRatio","required":false,"defaultValue":"1 / 1","description":"CSS aspect ratio reserved before generated media is available."},{"name":"size","type":"\"compact\" | \"fluid\"","required":false,"defaultValue":"compact","description":"\"compact\" caps the width at 208px, \"fluid\" fills the container. Default: \"compact\""},{"name":"interactive","type":"boolean","required":false,"defaultValue":"true","description":"Lets the active dither cluster follow fine-pointer movement."},{"name":"statusText","type":"string","required":false,"defaultValue":null,"description":"Replaces the built-in status line text for the current status."},{"name":"showStatus","type":"boolean","required":false,"defaultValue":"true","description":"Shows the status line under the media. Default: true"},{"name":"onRetry","type":"(() => void)","required":false,"defaultValue":null,"description":"Called from the retry button, which shows only when status is \"error\"."},{"name":"labels","type":"Partial<{ queued: string; generating: string; refining: string; complete: string; error: string; labelWithPrompt: string; quotedPrompt: string; retry: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string. `{status}` and `{prompt}` fill `labelWithPrompt`; `{prompt}` fills `quotedPrompt`."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."},{"name":"mediaClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the layer that holds the media."},{"name":"statusClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the status line."}]},{"displayName":"ThinkingShimmer","props":[{"name":"children","type":"ReactNode","required":false,"defaultValue":null,"description":"Loading message shown to the user."},{"name":"duration","type":"number","required":false,"defaultValue":"1.8","description":"Seconds taken for one shimmer pass."},{"name":"labels","type":"Partial<{ thinking: string; churning: string; inProgress: string; reasoning: string; phraseThinking: string; phraseReading: string; phraseConnecting: string; phraseForming: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the shimmering text."}]},{"displayName":"Message","props":[{"name":"from","type":"\"user\" | \"assistant\"","required":true,"defaultValue":null,"description":"Who sent it; \"user\" rows align to the end, \"assistant\" rows to the start."},{"name":"animateIn","type":"boolean","required":false,"defaultValue":"false","description":"Plays a trailing-edge pop-up once when this message row mounts."},{"name":"labels","type":"Partial<{ user: string; assistant: string; typing: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageGroup","props":[{"name":"spacing","type":"\"default\" | \"compact\"","required":false,"defaultValue":"compact","description":"Gap between messages: 6 px for \"compact\", 16 px for \"default\". Default: \"compact\""},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageAvatar","props":[{"name":"placeholder","type":"boolean","required":false,"defaultValue":"false","description":"Keep an empty avatar slot so grouped messages remain aligned."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageContent","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageHeader","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageFooter","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageMarker","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageTyping","props":[{"name":"label","type":"string","required":false,"defaultValue":null,"description":"Screen reader text for the typing dots. Default: \"Responding\""},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageBubble","props":[{"name":"variant","type":"\"outline\" | \"ghost\" | \"danger\" | \"solid\" | \"soft\" | \"tint\"","required":false,"defaultValue":"soft","description":"Fill and border style of the bubble. Default: \"soft\""},{"name":"align","type":"\"start\" | \"end\"","required":false,"defaultValue":null,"description":"Defaults to the surrounding Message alignment when omitted."},{"name":"animateIn","type":"boolean","required":false,"defaultValue":"false","description":"Plays the bubble entrance once when this component mounts."},{"name":"labels","type":"Partial<{ showMore: string; showLess: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageBubbleCollapsible","props":[{"name":"open","type":"boolean","required":false,"defaultValue":null,"description":"Whether the full text shows, for controlled use."},{"name":"defaultOpen","type":"boolean","required":false,"defaultValue":"false","description":"Whether the full text shows at first when uncontrolled. Default: false"},{"name":"onOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the new state when the text expands or collapses."},{"name":"collapsedLines","type":"2 | 6 | 3 | 4 | 5","required":false,"defaultValue":"4","description":"Lines shown while collapsed. Default: 4"},{"name":"moreLabel","type":"ReactNode","required":false,"defaultValue":null,"description":"Text of the expand button. Default: \"Show more\""},{"name":"lessLabel","type":"ReactNode","required":false,"defaultValue":null,"description":"Text of the collapse button. Default: \"Show less\""},{"name":"contentClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the clamped text wrapper."},{"name":"triggerClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the show more button."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageBubbleContent","props":[{"name":"render","type":"ReactElement<unknown, string | JSXElementConstructor<any>>","required":false,"defaultValue":null,"description":"Replaces the content element while preserving bubble styling."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageBubbleGroup","props":[{"name":"spacing","type":"\"default\" | \"compact\"","required":false,"defaultValue":"compact","description":"Gap between bubbles. Default: \"compact\""},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"MessageScroller","props":[{"name":"followOutput","type":"boolean","required":false,"defaultValue":"true","description":"Keep streamed output pinned while the reader remains near the end."},{"name":"followThreshold","type":"number","required":false,"defaultValue":"56","description":"Distance from the end that still counts as following the output."},{"name":"smooth","type":"boolean","required":false,"defaultValue":"true","description":"Smoothly follow growing content."},{"name":"onFollowChange","type":"((following: boolean) => void)","required":false,"defaultValue":null,"description":"Reports when the reader leaves or returns to the live edge."},{"name":"label","type":"string","required":false,"defaultValue":null,"description":"Accessible label for the scrollable transcript."},{"name":"busy","type":"boolean","required":false,"defaultValue":null,"description":"Marks the transcript as waiting for more streamed content."},{"name":"navigation","type":"\"rail\"","required":false,"defaultValue":null,"description":"Adds a compact rail for navigating between rendered Message rows."},{"name":"jumpButton","type":"boolean","required":false,"defaultValue":"true","description":"Shows a button back to the latest message once the reader scrolls up. Default true."},{"name":"navigationLabel","type":"string","required":false,"defaultValue":null,"description":"Accessible label for the optional message navigation rail."},{"name":"viewportClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the scrolling viewport."},{"name":"contentClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the log element that wraps the messages."},{"name":"railClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the navigation rail, used with `navigation=\"rail\"`."},{"name":"viewportRef","type":"Ref<HTMLElement>","required":false,"defaultValue":null,"description":"Ref to the scrolling viewport element."},{"name":"viewportProps","type":"Omit<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, \"children\" | \"className\" | \"ref\">","required":false,"defaultValue":null,"description":"Extra props for the scrolling viewport. Its event handlers still run."},{"name":"contentProps","type":"Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, \"children\" | \"className\" | \"ref\">","required":false,"defaultValue":null,"description":"Extra props for the log element that wraps the messages."},{"name":"labels","type":"Partial<{ label: string; jumpToLatest: string; navigationLabel: string; preview: string; goToUser: string; goToAssistant: string; goToMessage: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"PromptInput","props":[{"name":"value","type":"string","required":false,"defaultValue":null,"description":"The prompt text, for controlled use."},{"name":"defaultValue","type":"string","required":false,"defaultValue":"","description":"The initial prompt text when uncontrolled. Default: \"\""},{"name":"onValueChange","type":"((value: string) => void)","required":false,"defaultValue":null,"description":"Called with the new text on every edit."},{"name":"models","type":"PromptModel[]","required":false,"defaultValue":"[]","description":"Models listed in the model menu. Hidden when empty."},{"name":"model","type":"string","required":false,"defaultValue":null,"description":"The selected model's value, for controlled use."},{"name":"defaultModel","type":"string","required":false,"defaultValue":null,"description":"The initial model when uncontrolled. Default: the first model"},{"name":"onModelChange","type":"((model: string) => void)","required":false,"defaultValue":null,"description":"Called with the model's value when a model is picked."},{"name":"actions","type":"PromptAction[]","required":false,"defaultValue":"[]","description":"Items in the add menu next to the input. Hidden when empty."},{"name":"onAction","type":"((action: string) => void)","required":false,"defaultValue":null,"description":"Called with the action's value when an add menu item is chosen."},{"name":"commands","type":"PromptCommand[]","required":false,"defaultValue":"[]","description":"Slash commands. Typing `/` at the start of a word lists them above the input. Hidden when empty."},{"name":"onCommand","type":"((command: string) => void)","required":false,"defaultValue":null,"description":"Called with the command's value when a slash command is picked."},{"name":"onSubmit","type":"((value: string, model?: string) => void | Promise<void>)","required":false,"defaultValue":null,"description":"Called with the trimmed prompt and selected model on Enter or the send button."},{"name":"loading","type":"boolean","required":false,"defaultValue":"false","description":"Swaps send for a stop button and blocks new prompts. Default: false"},{"name":"onStop","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the stop button is pressed while loading."},{"name":"minRows","type":"number","required":false,"defaultValue":"2","description":"Height of the empty input, in text rows. Default: 2"},{"name":"maxRows","type":"number","required":false,"defaultValue":"8","description":"Rows the input grows to before it scrolls. Default: 8"},{"name":"leadingAction","type":"ReactNode","required":false,"defaultValue":null,"description":"Extra controls placed between the add menu and the model menu."},{"name":"labels","type":"Partial<{ placeholder: string; label: string; addToPrompt: string; chooseModel: string; send: string; stop: string; commands: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the form element."}]},{"displayName":"StreamingResponse","props":[{"name":"children","type":"ReactNode","required":true,"defaultValue":null,"description":"Rendered response content. Pass plain text or the output of a Markdown renderer."},{"name":"status","type":"\"error\" | \"streaming\" | \"complete\"","required":false,"defaultValue":"streaming","description":"Stream state; actions appear once it leaves \"streaming\". Default: \"streaming\""},{"name":"copyText","type":"string","required":false,"defaultValue":null,"description":"Plain-text value copied by the built-in copy action."},{"name":"onCopy","type":"(() => void | Promise<void>)","required":false,"defaultValue":null,"description":"Overrides the built-in clipboard action."},{"name":"onRetry","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the retry action is pressed. The action shows only when set."},{"name":"sources","type":"CitationItem[]","required":false,"defaultValue":"[]","description":"Optional sources shown as a compact footer disclosure after streaming."},{"name":"sourcesOpen","type":"boolean","required":false,"defaultValue":null,"description":"Whether the sources list is expanded, for controlled use."},{"name":"defaultSourcesOpen","type":"boolean","required":false,"defaultValue":"false","description":"Whether the sources list starts expanded when uncontrolled. Default: false"},{"name":"onSourcesOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the next state when the sources list expands or collapses."},{"name":"sourceIdPrefix","type":"string","required":false,"defaultValue":null,"description":"Prefix for source row ids that `Citation` markers link to. Generated when omitted."},{"name":"feedback","type":"StreamingResponseFeedback","required":false,"defaultValue":null,"description":"The thumbs up or down rating, for controlled use."},{"name":"defaultFeedback","type":"StreamingResponseFeedback","required":false,"defaultValue":"null","description":"The initial rating when uncontrolled. Default: null"},{"name":"onFeedbackChange","type":"((feedback: StreamingResponseFeedback) => void)","required":false,"defaultValue":null,"description":"Called with the new rating, or `null` when it is toggled off."},{"name":"announce","type":"boolean","required":false,"defaultValue":"true","description":"Set false when a surrounding conversation log announces streamed text."},{"name":"showActions","type":"boolean","required":false,"defaultValue":"true","description":"Hides the built-in completion actions without changing response status."},{"name":"labels","type":"Partial<{ copy: string; copied: string; retry: string; helpful: string; notHelpful: string; source: string; sources: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string. `{count}` fills `source` (one) and `sources` (many)."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."},{"name":"contentClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the wrapper around the response content."},{"name":"actionsClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the row of completion actions."}]},{"displayName":"TodoList","props":[{"name":"items","type":"TodoItem[]","required":true,"defaultValue":null,"description":"The tasks, each with a status."},{"name":"title","type":"ReactNode","required":false,"defaultValue":null,"description":"Header text. Default: \"To-dos\""},{"name":"open","type":"boolean","required":false,"defaultValue":null,"description":"Whether the list is expanded, for controlled use."},{"name":"defaultOpen","type":"boolean","required":false,"defaultValue":"true","description":"Whether the list starts expanded when uncontrolled. Default: true"},{"name":"onOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the new state when the list expands or collapses."},{"name":"collapseOnComplete","type":"boolean","required":false,"defaultValue":"true","description":"Collapses the list once every task is completed. Default: true"},{"name":"maxHeight","type":"number","required":false,"defaultValue":"248","description":"Height in px before the task list scrolls. Default: 248"},{"name":"labels","type":"Partial<{ title: string; label: string; progress: string; empty: string; pending: string; inProgress: string; completed: string; cancelled: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string. `{completed}` and `{total}` fill `progress`."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"ToolApprovalCode","props":[{"name":"code","type":"string","required":true,"defaultValue":null,"description":"Source text to show, wrapped rather than scrolled."},{"name":"language","type":"\"text\" | \"bash\" | \"diff\" | \"json\" | \"tsx\" | \"typescript\"","required":false,"defaultValue":"bash","description":"Language used for syntax highlighting. Default: \"bash\""},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the code block."}]},{"displayName":"ToolApproval","props":[{"name":"tool","type":"ReactNode","required":true,"defaultValue":null,"description":"Tool name shown in monospace under the title."},{"name":"title","type":"ReactNode","required":false,"defaultValue":null,"description":"Heading for the request. Default: \"Allow this tool to run?\""},{"name":"description","type":"ReactNode","required":false,"defaultValue":null,"description":"Short explanation of what the tool will do."},{"name":"parameters","type":"ToolApprovalParameter[]","required":false,"defaultValue":"[]","description":"Arguments listed in the expandable details panel."},{"name":"status","type":"\"error\" | \"complete\" | \"pending\" | \"approved\" | \"running\" | \"approving\" | \"denied\"","required":false,"defaultValue":"pending","description":"Request state, which sets the icon, badge and action buttons. Default: \"pending\""},{"name":"open","type":"boolean","required":false,"defaultValue":null,"description":"Whether the details panel is expanded, for controlled use."},{"name":"defaultOpen","type":"boolean","required":false,"defaultValue":"false","description":"Whether the details panel starts expanded when uncontrolled. Default: false"},{"name":"onOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the new state when the details panel opens or closes."},{"name":"onApprove","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the \"Allow once\" button is pressed."},{"name":"onAlwaysAllow","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when \"Always allow\" is pressed. The button shows only when set."},{"name":"onDeny","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the \"Deny\" button is pressed."},{"name":"labels","type":"Partial<{ title: string; viewDetails: string; allowOnce: string; alwaysAllow: string; deny: string; pending: string; approving: string; approved: string; denied: string; running: string; complete: string; error: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"ToolResultOutput","props":[{"name":"language","type":"\"text\" | \"bash\" | \"diff\" | \"json\" | \"tsx\" | \"typescript\"","required":false,"defaultValue":"bash","description":"Syntax highlighting language for the output. Default: \"bash\""},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the code element."}]},{"displayName":"ToolResult","props":[{"name":"tool","type":"ReactNode","required":true,"defaultValue":null,"description":"Tool name, shown in small monospace after the title."},{"name":"title","type":"ReactNode","required":true,"defaultValue":null,"description":"Heading in the header row, rolls to the new text when it changes."},{"name":"status","type":"\"success\" | \"error\" | \"running\" | \"cancelled\"","required":false,"defaultValue":"running","description":"Run state, sets the status badge and auto open or fold. Default: \"running\""},{"name":"kind","type":"\"custom\" | \"terminal\" | \"request\"","required":false,"defaultValue":"custom","description":"Picks the header icon when no `icon` is given. Default: \"custom\""},{"name":"meta","type":"ReactNode","required":false,"defaultValue":null,"description":"Short muted detail after the title, e.g. a duration or count."},{"name":"icon","type":"ReactNode","required":false,"defaultValue":null,"description":"Replaces the icon chosen by `kind`."},{"name":"open","type":"boolean","required":false,"defaultValue":null,"description":"Whether the output panel is open, for controlled use."},{"name":"defaultOpen","type":"boolean","required":false,"defaultValue":"true","description":"Whether the output panel starts open when uncontrolled. Default: true"},{"name":"onOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the new open state when the panel opens or closes."},{"name":"collapseOnComplete","type":"boolean","required":false,"defaultValue":"true","description":"Folds the panel when the status leaves \"running\". Default: true"},{"name":"maxHeight","type":"number","required":false,"defaultValue":"220","description":"Maximum height of the scrolling output area, in px. Default: 220"},{"name":"copyText","type":"string","required":false,"defaultValue":null,"description":"Text the copy button writes to the clipboard. Shows the copy button."},{"name":"onCopy","type":"(() => void | Promise<void>)","required":false,"defaultValue":null,"description":"Runs instead of the clipboard write when copy is pressed. Shows the copy button."},{"name":"onRetry","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the retry button is pressed. Shows the retry button."},{"name":"labels","type":"Partial<{ running: string; success: string; error: string; cancelled: string; copy: string; copied: string; retry: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."},{"name":"contentClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the padded box around the output."}]}],"types":[{"name":"SidebarResource","file":"components/agents/ai-sidebar/types.ts","fields":[{"name":"id","type":"string","required":true,"description":"Unique key for the row, used for selection, expansion and moves."},{"name":"label","type":"string","required":true,"description":"Name shown in the row and edited on rename."},{"name":"kind","type":"SidebarResourceKind","required":true,"description":"Picks the row icon; folders and projects can hold children."},{"name":"children","type":"SidebarResource[]","required":false,"description":"Nested rows shown when a folder or project is expanded."},{"name":"disabled","type":"boolean","required":false,"description":"Dims the row and blocks selecting, renaming, dragging and dropping into it."}]},{"name":"SidebarResourceMove","file":"components/agents/ai-sidebar/types.ts","fields":[{"name":"itemId","type":"string","required":true,"description":"Id of the row being moved."},{"name":"targetId","type":"string | null","required":true,"description":"Id of the row it lands next to or inside, or null for the end of the root."},{"name":"position","type":"SidebarResourceDropPosition","required":true,"description":"Where the row lands relative to the target."}]},{"name":"SidebarResourceMenuControls","file":"components/agents/ai-sidebar/types.ts","fields":[{"name":"close","type":"() => void","required":true,"description":"Closes the row menu."},{"name":"rename","type":"() => void","required":true,"description":"Closes the menu and starts renaming the row in place."},{"name":"moves","type":"SidebarResourceMoveCommands","required":true,"description":"The moves this row can make right now."}]},{"name":"SidebarResourceMoveCommands","file":"components/agents/ai-sidebar/types.ts","fields":[{"name":"up","type":"() => void","required":false,"description":"Moves the row above the row before it."},{"name":"down","type":"() => void","required":false,"description":"Moves the row below the row after it."},{"name":"into","type":"{ label: string; run: () => void }","required":false,"description":"Moves the row into the folder or project above it, named by `label`."},{"name":"out","type":"() => void","required":false,"description":"Moves the row out of its parent, just after it."}]},{"name":"ApprovalCardQuestion","file":"components/agents/approval-card/types.ts","fields":[{"name":"id","type":"string","required":true,"description":"Unique key; the question's answer is stored under it."},{"name":"title","type":"ReactNode","required":true,"description":"Question text, shown as the card heading on its step."},{"name":"description","type":"ReactNode","required":false,"description":"Supporting text under the question."},{"name":"options","type":"ApprovalCardOption[]","required":false,"description":"Choices shown as radios, or checkboxes when `multiple` is set."},{"name":"multiple","type":"boolean","required":false,"description":"Allows picking more than 1 option, shown as checkboxes."},{"name":"autoAdvance","type":"boolean","required":false,"description":"Set to false to stay on the step after a single choice is picked."},{"name":"allowCustom","type":"boolean","required":false,"description":"Adds a text field for a free-form answer."},{"name":"customPlaceholder","type":"string","required":false,"description":"Placeholder of the free-form field. Default: \"Add another response…\""}]},{"name":"ApprovalCardOption","file":"components/agents/approval-card/types.ts","fields":[{"name":"value","type":"string","required":true,"description":"Value stored in the answer's `selected` list when picked."},{"name":"label","type":"string","required":true,"description":"Text shown next to the radio or checkbox."},{"name":"description","type":"string","required":false,"description":"Plain supporting text rendered under the label."},{"name":"disabled","type":"boolean","required":false,"description":"Stops the option from being picked."}]},{"name":"FileDiffLine","file":"components/agents/file-diff.tsx","fields":[{"name":"id","type":"string","required":true,"description":"Stable key, so streamed lines keep their place."},{"name":"type","type":"FileDiffLineType","required":false,"description":"Marks the line added (green, +), removed (red, −) or unchanged. Default: \"context\""},{"name":"oldLine","type":"number","required":false,"description":"Line number in the old file, shown in the first gutter. Blank when not set."},{"name":"newLine","type":"number","required":false,"description":"Line number in the new file, shown in the second gutter. Blank when not set."},{"name":"content","type":"string","required":true,"description":"The line's code, without the + or − marker. Syntax highlighted."}]},{"name":"PromptModel","file":"components/agents/prompt-input.tsx","fields":[{"name":"value","type":"string","required":true,"description":"Unique key, passed to `onModelChange` and `onSubmit`."},{"name":"label","type":"ReactNode","required":true,"description":"Name shown in the model menu and on its trigger when selected."},{"name":"icon","type":"ReactNode","required":false,"description":"Icon before the label in the menu and on the trigger."},{"name":"disabled","type":"boolean","required":false,"description":"Stops the model from being picked."}]},{"name":"PromptAction","file":"components/agents/prompt-input.tsx","fields":[{"name":"value","type":"string","required":true,"description":"Unique key, passed to `onAction` when the item is chosen."},{"name":"label","type":"ReactNode","required":true,"description":"Item text in the add menu."},{"name":"description","type":"ReactNode","required":false,"description":"Muted line under the label."},{"name":"icon","type":"ReactNode","required":false,"description":"Icon before the label."},{"name":"disabled","type":"boolean","required":false,"description":"Stops the item from being chosen."}]},{"name":"PromptCommand","file":"components/agents/prompt-input.tsx","fields":[{"name":"value","type":"string","required":true,"description":"What follows the slash: typing `/value` finds it, and picking it writes `/value ` into the prompt."},{"name":"label","type":"string","required":true,"description":"Name shown in the command list. Also matched while typing."},{"name":"description","type":"ReactNode","required":false,"description":"Muted line beside the label."},{"name":"icon","type":"ReactNode","required":false,"description":"Icon before the label."}]},{"name":"CitationItem","file":"components/agents/citations.tsx","fields":[{"name":"id","type":"string","required":true,"description":"Unique key for the source, matched by a `Citation` marker's `citationId`."},{"name":"title","type":"ReactNode","required":true,"description":"Source name shown as the row's main text."},{"name":"domain","type":"ReactNode","required":false,"description":"Muted text after the title, such as the site's host."},{"name":"url","type":"string","required":false,"description":"Link opened in a new tab and the favicon source. Omit for a plain row."},{"name":"icon","type":"ReactNode","required":false,"description":"Replaces the URL favicon, e.g. a document icon for non-web sources. An svg\nchild is sized to match the favicon; falsy values fall back to the favicon."}]},{"name":"TodoItem","file":"components/agents/todo-list.tsx","fields":[{"name":"id","type":"string","required":true,"description":"Unique key for the row."},{"name":"title","type":"ReactNode","required":true,"description":"Task text; struck through when completed."},{"name":"status","type":"TodoItemStatus","required":false,"description":"Task state; sets the icon and text tone. Default: \"pending\""},{"name":"progress","type":"number","required":false,"description":"Ring fill from 0 to 100 while in progress; unset spins a partial ring."},{"name":"detail","type":"ReactNode","required":false,"description":"Muted text at the end of the row, such as a time or count."}]},{"name":"ToolApprovalParameter","file":"components/agents/tool-approval.tsx","fields":[{"name":"id","type":"string","required":true,"description":"Unique key for the row."},{"name":"label","type":"ReactNode","required":true,"description":"Parameter name, shown muted in the left column of the details."},{"name":"value","type":"ReactNode","required":true,"description":"Parameter value, shown in monospace in the right column."}]}],"files":[{"path":"components/agents/chat-app.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport { useEffect, useLayoutEffect, useRef } from \"react\";\nimport {\n  AnimatedSidebarProvider,\n  type AnimatedSidebarProviderProps,\n  useAnimatedSidebar,\n} from \"@/components/motion/animated-sidebar\";\nimport { cn } from \"@/lib/utils\";\n\n/**\n * Shell width below which a docked sidebar leaves too little room for the\n * conversation: the default sidebar is 17rem, so under 600px the conversation\n * pane is left with barely 330px - narrower than a phone.\n *\n * Deliberately not AnimatedSidebar's own 767px mobile query: that one asks\n * whether the *viewport* is a phone (and swaps the sidebar for an off-canvas\n * sheet), this one asks whether the *shell's own box* - which may be a column,\n * a split view or a panel inside a much wider page - still fits both panes.\n */\nconst MIN_DOCKED_WIDTH = 600;\n\nexport interface ChatAppProps extends AnimatedSidebarProviderProps {\n  /** Docked sidebar width as a CSS length. Default `17rem`. */\n  sidebarWidth?: string;\n  /**\n   * Shell width in px under which the sidebar folds off-canvas. Ignored while\n   * `open` is controlled - the consumer owns the state then.\n   */\n  collapseSidebarBelow?: number;\n}\n\n/**\n * Folds the sidebar away while the shell is too narrow to carry both panes,\n * and brings it back when it isn't. Only crossings are acted on, so a manual\n * toggle at either size stays put until the shell actually changes shape.\n *\n * Mount is not a crossing in the opening direction: a shell that merely has\n * room says nothing about whether the caller wanted the sidebar open, so the\n * first measurement leaves `defaultOpen` alone. Too narrow at mount *is* the\n * fold condition itself, so that half applies immediately.\n */\nfunction ShellFit({ minWidth }: { minWidth: number }) {\n  const { open, setOpen } = useAnimatedSidebar();\n  const markerRef = useRef<HTMLDivElement>(null);\n  const narrowRef = useRef<boolean | null>(null);\n  const openRef = useRef(open);\n  useLayoutEffect(() => {\n    openRef.current = open;\n  });\n\n  useEffect(() => {\n    const shell = markerRef.current?.parentElement;\n    if (!shell) return;\n    const observer = new ResizeObserver(([entry]) => {\n      const narrow = entry.contentRect.width < minWidth;\n      if (narrowRef.current === narrow) return;\n      const first = narrowRef.current === null;\n      narrowRef.current = narrow;\n      if (first && !narrow) return;\n      const wanted = !narrow;\n      // Already where the shell wants it - saying so again would only be an\n      // onOpenChange the caller never asked for.\n      if (openRef.current === wanted) return;\n      setOpen(wanted);\n    });\n    observer.observe(shell);\n    return () => observer.disconnect();\n  }, [minWidth, setOpen]);\n\n  return <div ref={markerRef} className=\"hidden\" />;\n}\n\nexport function ChatApp({\n  children,\n  className,\n  sidebarWidth = \"17rem\",\n  collapseSidebarBelow = MIN_DOCKED_WIDTH,\n  style,\n  ...props\n}: ChatAppProps) {\n  return (\n    <AnimatedSidebarProvider\n      {...props}\n      style={{ ...style, \"--sidebar-width\": sidebarWidth }}\n      className={cn(\n        \"min-h-0 w-full overflow-hidden rounded-2xl border border-border bg-background\",\n        className,\n      )}\n    >\n      {/* A controlled `open` is the consumer's to change; fitting the shell\n          would fire an onOpenChange they never asked for. */}\n      {props.open === undefined ? (\n        <ShellFit minWidth={collapseSidebarBelow} />\n      ) : null}\n      {children}\n    </AnimatedSidebarProvider>\n  );\n}\n"},{"path":"components/agents/agent-activity/index.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport { ChevronDown } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { type ReactNode, useId, useLayoutEffect, useRef, useState } from \"react\";\nimport { AgentDisclosure } from \"@/components/agents/agent-disclosure\";\nimport { ThinkingShimmer } from \"@/components/agents/loading-states/thinking-shimmer\";\nimport {\n  EASE_OUT,\n  SPRING_LAYOUT,\n  SPRING_SWAP,\n} from \"@/lib/ease\";\nimport { useStatusOpen } from \"@/lib/hooks/use-status-open\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\nimport { ActivityRow } from \"./activity-row\";\nimport {\n  type AgentActivityTranslate,\n  agentActivityMessages,\n} from \"./messages\";\nimport type {\n  AgentActivityContentType,\n  AgentActivityItem,\n  AgentActivityProps,\n} from \"./types\";\n\nexport {\n  type AgentActivityMessages,\n  agentActivityMessages,\n} from \"./messages\";\nexport type {\n  AgentActivityContentType,\n  AgentActivityItem,\n  AgentActivityProps,\n  AgentActivitySearch,\n  AgentActivityStatus,\n  AgentActivityStep,\n  AgentActivityText,\n  AgentActivityTool,\n  AgentActivityTrace,\n  AgentSearchResult,\n  AgentStepStatus,\n  AgentTraceKind,\n} from \"./types\";\n\nfunction formatDuration(duration: number, t: AgentActivityTranslate) {\n  const seconds = Math.max(0, Math.round(duration));\n  if (seconds < 60) return t(\"seconds\", { seconds });\n\n  const minutes = Math.floor(seconds / 60);\n  const remainder = seconds % 60;\n  return remainder === 0\n    ? t(\"minutes\", { minutes })\n    : t(\"minutesSeconds\", { minutes, seconds: remainder });\n}\n\nfunction getContentType(items: AgentActivityItem[]): AgentActivityContentType {\n  const first = items[0]?.type;\n  return first && items.every((item) => item.type === first) ? first : \"mixed\";\n}\n\nfunction getActiveLabel(\n  type: AgentActivityContentType,\n  t: AgentActivityTranslate,\n) {\n  if (type === \"search\") return t(\"searching\");\n  if (type === \"tool\") return t(\"runningTools\");\n  if (type === \"trace\") return t(\"workingTrace\");\n  if (type === \"mixed\") return t(\"workingMixed\");\n  return t(\"thinking\");\n}\n\nfunction getSummary(\n  type: AgentActivityContentType,\n  items: AgentActivityItem[],\n  duration: number,\n  t: AgentActivityTranslate,\n): ReactNode {\n  const count = items.length;\n  if (type === \"step\" || type === \"text\") {\n    // Raw template, split around the placeholder so the duration keeps its tabular figures.\n    const [before, after = \"\"] = t(\"thoughtFor\").split(\"{duration}\");\n    return (\n      <>\n        {before}\n        <span className=\"tabular-nums\">{formatDuration(duration, t)}</span>\n        {after}\n      </>\n    );\n  }\n  if (type === \"search\") return t(\"searched\");\n  if (type === \"tool\") {\n    return t(count === 1 ? \"ranToolsOne\" : \"ranToolsOther\", { count });\n  }\n  if (type === \"trace\") {\n    const messages = items.filter(\n      (item) =>\n        item.type === \"trace\" &&\n        (item.kind === \"thinking\" || item.kind === \"message\"),\n    ).length;\n    const tools = count - messages;\n    return t(\"traceSummary\", {\n      toolCalls: t(tools === 1 ? \"toolCallsOne\" : \"toolCallsOther\", {\n        count: tools,\n      }),\n      messages: t(messages === 1 ? \"messagesOne\" : \"messagesOther\", {\n        count: messages,\n      }),\n    });\n  }\n  return t(count === 1 ? \"completedStepsOne\" : \"completedStepsOther\", {\n    count,\n  });\n}\n\nexport function AgentActivity({\n  items,\n  contentType: initialContentType,\n  status = \"working\",\n  duration = 0,\n  open,\n  defaultOpen = false,\n  onOpenChange,\n  collapseOnComplete = true,\n  activeLabel,\n  summary,\n  renderWorkingStatus,\n  renderCompletedStatus,\n  maxHeight = 208,\n  labels,\n  className,\n  contentClassName,\n}: AgentActivityProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"agentActivity\", agentActivityMessages, labels);\n  const baseId = useId();\n  const triggerId = `${baseId}-trigger`;\n  const contentId = `${baseId}-content`;\n  const contentRef = useRef<HTMLDivElement>(null);\n  const viewportRef = useRef<HTMLDivElement>(null);\n  const [contentHeight, setContentHeight] = useState(0);\n  // When the work completes, the panel stays open or folds as asked.\n  const [currentOpen, setOpen] = useStatusOpen({\n    status,\n    open,\n    defaultOpen,\n    onOpenChange,\n    decide: (previous, next) =>\n      previous === \"working\" && next === \"complete\" ? !collapseOnComplete : undefined,\n  });\n  const working = status === \"working\";\n  const expanded = working || currentOpen;\n  const contentType = items.length\n    ? getContentType(items)\n    : (initialContentType ?? \"mixed\");\n  const cappedHeight = Math.min(contentHeight, Math.max(0, maxHeight));\n  const viewportHeight = working ? Math.max(0, maxHeight) : cappedHeight;\n  const capped = contentHeight > maxHeight;\n  const streamOffset = working\n    ? Math.min(0, viewportHeight - contentHeight)\n    : 0;\n\n  useLayoutEffect(() => {\n    const node = contentRef.current;\n    if (!node) return;\n\n    const measure = () => setContentHeight(node.offsetHeight);\n    measure();\n\n    if (typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(measure);\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, []);\n\n  const toggle = () => {\n    const next = !currentOpen;\n    setOpen(next);\n    if (next) requestAnimationFrame(() => viewportRef.current?.scrollTo({ top: 0 }));\n  };\n\n  const liveLabel = activeLabel ?? getActiveLabel(contentType, t);\n  const completedSummary = summary ?? getSummary(contentType, items, duration, t);\n  const maskImage = capped\n    ? working\n      ? \"linear-gradient(to bottom, transparent, black 12px)\"\n      : \"linear-gradient(to bottom, transparent, black 12px, black calc(100% - 12px), transparent)\"\n    : undefined;\n\n  return (\n    <div\n      data-state={working ? \"working\" : expanded ? \"open\" : \"closed\"}\n      data-content={contentType}\n      aria-busy={working}\n      className={cn(\"w-full text-sm\", className)}\n    >\n      {working ? (\n        <div\n          id={triggerId}\n          role=\"status\"\n          className=\"flex h-7 min-w-0 items-center text-muted-foreground\"\n        >\n          {renderWorkingStatus\n            ? renderWorkingStatus({ label: liveLabel, duration })\n            : <ThinkingShimmer>{liveLabel}</ThinkingShimmer>}\n        </div>\n      ) : (\n        <button\n          id={triggerId}\n          type=\"button\"\n          aria-expanded={expanded}\n          aria-controls={contentId}\n          onClick={toggle}\n          className=\"group flex h-7 min-w-0 items-center gap-1.5 rounded-full text-left font-medium text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\"\n        >\n          <span className=\"truncate\">\n            {renderCompletedStatus\n              ? renderCompletedStatus({ summary: completedSummary, duration })\n              : completedSummary}\n          </span>\n          <motion.span\n            aria-hidden=\"true\"\n            animate={{ rotate: expanded ? 180 : 0 }}\n            transition={reduce ? { duration: 0 } : SPRING_SWAP}\n            className=\"inline-flex shrink-0 text-muted-foreground/70 group-hover:text-foreground\"\n          >\n            <ChevronDown className=\"size-3.5\" />\n          </motion.span>\n        </button>\n      )}\n\n      <AgentDisclosure\n        id={contentId}\n        role=\"region\"\n        aria-labelledby={triggerId}\n        open={expanded}\n        openHeight={viewportHeight}\n      >\n        <div\n          ref={viewportRef}\n          className={cn(\n            \"scrollbar-hide pr-1\",\n            capped && expanded && !working ? \"overflow-y-auto\" : \"overflow-y-hidden\",\n          )}\n          style={{ height: viewportHeight, maskImage, WebkitMaskImage: maskImage }}\n        >\n          <motion.div\n            ref={contentRef}\n            role=\"list\"\n            initial={false}\n            animate={{ y: streamOffset }}\n            transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n            className={cn(\"space-y-0.5 py-2\", contentClassName)}\n          >\n            <AnimatePresence mode=\"popLayout\">\n              {items.map((item) => (\n                <motion.div\n                  layout=\"position\"\n                  key={item.id}\n                  role=\"listitem\"\n                  initial={reduce ? { opacity: 1 } : { opacity: 0, y: 6 }}\n                  animate={{ opacity: 1, y: 0 }}\n                  exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3 }}\n                  transition={\n                    reduce\n                      ? { duration: 0 }\n                      : {\n                          opacity: { duration: 0.18, ease: EASE_OUT },\n                          y: SPRING_LAYOUT,\n                          layout: SPRING_LAYOUT,\n                        }\n                  }\n                >\n                  <ActivityRow item={item} t={t} />\n                </motion.div>\n              ))}\n            </AnimatePresence>\n          </motion.div>\n        </div>\n      </AgentDisclosure>\n    </div>\n  );\n}\n"},{"path":"components/agents/ai-sidebar.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport { AnimatePresence } from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  useCallback,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\nimport { type AISidebarMessages, aiSidebarMessages } from \"./ai-sidebar/messages\";\nimport { ResourceRow } from \"./ai-sidebar/resource-row\";\nimport {\n  canContain,\n  containsResource,\n  findResource,\n  flattenResources,\n  moveResource,\n  renameResource,\n} from \"./ai-sidebar/tree\";\nimport type {\n  AISidebarProps,\n  DropTarget,\n  FlatResource,\n  SidebarResource,\n  SidebarResourceDropPosition,\n  SidebarResourceMove,\n  SidebarResourceMoveCommands,\n} from \"./ai-sidebar/types\";\n\nexport { type AISidebarMessages, aiSidebarMessages } from \"./ai-sidebar/messages\";\nexport type {\n  AISidebarProps,\n  SidebarResource,\n  SidebarResourceDropPosition,\n  SidebarResourceKind,\n  SidebarResourceMenuControls,\n  SidebarResourceMove,\n  SidebarResourceMoveCommands,\n} from \"./ai-sidebar/types\";\n\nconst MOVED_MESSAGE = {\n  before: \"movedBefore\",\n  inside: \"movedInside\",\n  after: \"movedAfter\",\n} as const satisfies Record<SidebarResourceDropPosition, keyof AISidebarMessages>;\n\nexport function AISidebar({\n  items,\n  defaultItems = [],\n  onItemsChange,\n  onMove,\n  onMoveError,\n  onRename,\n  activeId,\n  defaultActiveId = null,\n  onActiveChange,\n  defaultExpandedIds = [],\n  renderIcon,\n  renderMenu,\n  ariaLabel,\n  className,\n  labels,\n}: AISidebarProps) {\n  const t = useMessages(\"aiSidebar\", aiSidebarMessages, labels);\n  const [internalItems, setInternalItems] = useState(defaultItems);\n  // A move shows at once. When `items` is controlled, it shows on top of the\n  // items it was made from until the parent passes new ones.\n  const [optimistic, setOptimistic] = useState<{\n    base: SidebarResource[];\n    items: SidebarResource[];\n  } | null>(null);\n  const [internalActiveId, setInternalActiveId] = useState(defaultActiveId);\n  const [expandedIds, setExpandedIds] = useState(\n    () => new Set(defaultExpandedIds),\n  );\n  const [focusedId, setFocusedId] = useState<string | null>(\n    activeId ?? defaultActiveId,\n  );\n  const [draggingId, setDraggingId] = useState<string | null>(null);\n  const [dropTarget, setDropTarget] = useState<DropTarget | null>(null);\n  const [menuOpenId, setMenuOpenId] = useState<string | null>(null);\n  const [renamingId, setRenamingId] = useState<string | null>(null);\n  const [announcement, setAnnouncement] = useState(\"\");\n  const rowRefs = useRef(new Map<string, HTMLDivElement>());\n  const movePendingRef = useRef(false);\n  if (optimistic && optimistic.base !== items) setOptimistic(null);\n  const renderedItems =\n    items === undefined\n      ? internalItems\n      : optimistic?.base === items\n        ? optimistic.items\n        : items;\n  const selectedId = activeId !== undefined ? activeId : internalActiveId;\n\n  const flat = useMemo(\n    () => flattenResources(renderedItems, expandedIds),\n    [expandedIds, renderedItems],\n  );\n\n  // Which row carries the roving tabindex is resolved during render, never in\n  // a passive effect: an effect lands after the browser paints, so the first\n  // commit - and, on a server-rendered page, the markup itself - would have no\n  // tabbable row and Tab would skip the whole tree. The same hole opens again\n  // whenever a collapse or a rolled-back move takes the focused row out of it.\n  const focusedRow =\n    focusedId !== null && flat.some((row) => row.item.id === focusedId)\n      ? focusedId\n      : (flat[0]?.item.id ?? null);\n  if (focusedId !== focusedRow) setFocusedId(focusedRow);\n\n  useEffect(() => {\n    if (!menuOpenId) return;\n    const frame = requestAnimationFrame(() => {\n      const menus = Array.from(\n        document.querySelectorAll<HTMLElement>(\"[data-sidebar-resource-menu]\"),\n      );\n      menus\n        .find((menu) => menu.dataset.sidebarResourceMenu === menuOpenId)\n        ?.querySelector<HTMLElement>(\"button, a[href]\")\n        ?.focus();\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [menuOpenId]);\n\n  const updateItems = useCallback(\n    (next: SidebarResource[]) => {\n      if (items === undefined) setInternalItems(next);\n      else setOptimistic(next === items ? null : { base: items, items: next });\n      onItemsChange?.(next);\n    },\n    [items, onItemsChange],\n  );\n\n  const performMove = useCallback(\n    async (move: SidebarResourceMove) => {\n      if (movePendingRef.current) {\n        setAnnouncement(t(\"movePending\"));\n        return;\n      }\n      const before = renderedItems;\n      const next = moveResource(before, move);\n      if (!next || next === before) return;\n\n      movePendingRef.current = true;\n      updateItems(next);\n      setDropTarget(null);\n      setDraggingId(null);\n      const moved = findResource(before, move.itemId);\n      const target = move.targetId ? findResource(before, move.targetId) : null;\n      const item = moved?.label ?? t(\"unnamedItem\");\n      setAnnouncement(\n        target\n          ? t(MOVED_MESSAGE[move.position], { item, target: target.label })\n          : t(\"movedToTop\", { item }),\n      );\n\n      try {\n        await onMove?.(move);\n      } catch (error) {\n        updateItems(before);\n        setAnnouncement(t(\"moveFailed\", { item }));\n        onMoveError?.(error, move);\n      } finally {\n        movePendingRef.current = false;\n      }\n    },\n    [onMove, onMoveError, renderedItems, t, updateItems],\n  );\n\n  const focusRow = useCallback((id: string) => {\n    setFocusedId(id);\n    requestAnimationFrame(() => rowRefs.current.get(id)?.focus());\n  }, []);\n\n  const select = useCallback(\n    (id: string) => {\n      if (activeId === undefined) setInternalActiveId(id);\n      onActiveChange?.(id);\n    },\n    [activeId, onActiveChange],\n  );\n\n  const toggle = useCallback((id: string) => {\n    setExpandedIds((current) => {\n      const next = new Set(current);\n      if (next.has(id)) next.delete(id);\n      else next.add(id);\n      return next;\n    });\n  }, []);\n\n  // The same four moves `Alt+Shift+Arrow` performs, handed to the row menu so\n  // they survive on a device with no drag and no modifier keys.\n  const moveCommands = useCallback(\n    (row: FlatResource): SidebarResourceMoveCommands => {\n      if (row.item.disabled) return {};\n      const index = flat.findIndex(({ item }) => item.id === row.item.id);\n      const previous = flat[index - 1];\n      const next = flat[index + 1];\n      const parentId = row.parentId;\n      const commands: SidebarResourceMoveCommands = {};\n\n      if (previous) {\n        commands.up = () =>\n          void performMove({\n            itemId: row.item.id,\n            targetId: previous.item.id,\n            position: \"before\",\n          });\n      }\n      if (next) {\n        commands.down = () =>\n          void performMove({\n            itemId: row.item.id,\n            targetId: next.item.id,\n            position: \"after\",\n          });\n      }\n      // Only offer the reparent when it lands somewhere new - the row above a\n      // folder's first child is the folder it already lives in.\n      if (previous && canContain(previous.item) && previous.item.id !== parentId) {\n        commands.into = {\n          label: previous.item.label,\n          run: () => {\n            setExpandedIds((current) => new Set(current).add(previous.item.id));\n            void performMove({\n              itemId: row.item.id,\n              targetId: previous.item.id,\n              position: \"inside\",\n            });\n          },\n        };\n      }\n      if (parentId) {\n        commands.out = () =>\n          void performMove({\n            itemId: row.item.id,\n            targetId: parentId,\n            position: \"after\",\n          });\n      }\n\n      return commands;\n    },\n    [flat, performMove],\n  );\n\n  const handleKeyDown = useCallback(\n    (event: KeyboardEvent<HTMLDivElement>, row: FlatResource) => {\n      const index = flat.findIndex(({ item }) => item.id === row.item.id);\n      const previous = flat[index - 1];\n      const next = flat[index + 1];\n      const moveModifier = event.altKey && event.shiftKey;\n\n      if (event.key === \"ArrowDown\" && !moveModifier && next) {\n        event.preventDefault();\n        focusRow(next.item.id);\n        return;\n      }\n      if (event.key === \"ArrowUp\" && !moveModifier && previous) {\n        event.preventDefault();\n        focusRow(previous.item.id);\n        return;\n      }\n      if (event.key === \"Home\" && flat[0]) {\n        event.preventDefault();\n        focusRow(flat[0].item.id);\n        return;\n      }\n      if (event.key === \"End\" && flat.at(-1)) {\n        event.preventDefault();\n        focusRow(flat.at(-1)?.item.id ?? row.item.id);\n        return;\n      }\n\n      if (row.item.disabled) {\n        if (event.key === \"ArrowLeft\" && row.parentId) {\n          event.preventDefault();\n          focusRow(row.parentId);\n        } else if (\n          moveModifier ||\n          [\"ArrowRight\", \"Enter\", \" \", \"F2\", \"ContextMenu\"].includes(\n            event.key,\n          ) ||\n          (event.shiftKey && event.key === \"F10\")\n        ) {\n          event.preventDefault();\n        }\n        return;\n      }\n\n      if (moveModifier && event.key === \"ArrowUp\" && previous) {\n        event.preventDefault();\n        void performMove({ itemId: row.item.id, targetId: previous.item.id, position: \"before\" });\n        return;\n      }\n      if (moveModifier && event.key === \"ArrowDown\" && next) {\n        event.preventDefault();\n        void performMove({ itemId: row.item.id, targetId: next.item.id, position: \"after\" });\n        return;\n      }\n      if (moveModifier && event.key === \"ArrowRight\" && previous && canContain(previous.item)) {\n        event.preventDefault();\n        setExpandedIds((current) => new Set(current).add(previous.item.id));\n        void performMove({ itemId: row.item.id, targetId: previous.item.id, position: \"inside\" });\n        return;\n      }\n      if (moveModifier && event.key === \"ArrowLeft\" && row.parentId) {\n        event.preventDefault();\n        void performMove({ itemId: row.item.id, targetId: row.parentId, position: \"after\" });\n        return;\n      }\n\n      if (event.key === \"ArrowRight\" && canContain(row.item)) {\n        event.preventDefault();\n        if (!expandedIds.has(row.item.id)) toggle(row.item.id);\n        else if (next?.parentId === row.item.id) focusRow(next.item.id);\n      } else if (event.key === \"ArrowLeft\") {\n        event.preventDefault();\n        if (expandedIds.has(row.item.id)) toggle(row.item.id);\n        else if (row.parentId) focusRow(row.parentId);\n      } else if (event.key === \"Enter\" || event.key === \" \") {\n        event.preventDefault();\n        if (canContain(row.item)) toggle(row.item.id);\n        else select(row.item.id);\n      } else if (event.key === \"F2\") {\n        event.preventDefault();\n        setRenamingId(row.item.id);\n      } else if (event.key === \"ContextMenu\" || (event.shiftKey && event.key === \"F10\")) {\n        event.preventDefault();\n        setMenuOpenId(row.item.id);\n      }\n    },\n    [expandedIds, flat, focusRow, performMove, select, toggle],\n  );\n\n  return (\n    <>\n      <div\n      role=\"tree\"\n      aria-label={ariaLabel ?? t(\"label\")}\n      aria-multiselectable=\"false\"\n      onDragOver={(event) => {\n        if (!draggingId || event.target !== event.currentTarget) return;\n        event.preventDefault();\n        setDropTarget({ id: null, position: \"after\" });\n      }}\n      onDrop={(event) => {\n        event.preventDefault();\n        if (draggingId && dropTarget) {\n          void performMove({\n            itemId: draggingId,\n            targetId: dropTarget.id,\n            position: dropTarget.position,\n          });\n        }\n      }}\n      className={cn(\n        \"relative flex min-w-0 flex-col gap-0.5 [overflow-anchor:none] group-data-[state=collapsed]/sidebar:hidden\",\n        draggingId && \"select-none pb-9\",\n        className,\n      )}\n    >\n      <AnimatePresence initial={false}>\n        {flat.map((row) => (\n          <ResourceRow\n            key={row.item.id}\n            row={row}\n            active={selectedId === row.item.id}\n            expanded={expandedIds.has(row.item.id)}\n            focused={focusedRow === row.item.id}\n            draggingId={draggingId}\n            dropTarget={dropTarget}\n            menuOpen={menuOpenId === row.item.id}\n            moves={moveCommands(row)}\n            renaming={renamingId === row.item.id}\n            onFocus={() => setFocusedId(row.item.id)}\n            onSelect={() => select(row.item.id)}\n            onToggle={() => toggle(row.item.id)}\n            onKeyDown={(event) => handleKeyDown(event, row)}\n            onRenameStart={() => setRenamingId(row.item.id)}\n            onRenameCancel={() => setRenamingId(null)}\n            onRenameCommit={(label) => {\n              const trimmed = label.trim();\n              setRenamingId(null);\n              if (!trimmed || trimmed === row.item.label) return;\n              const before = renderedItems;\n              updateItems(renameResource(before, row.item.id, trimmed));\n              void Promise.resolve(onRename?.(row.item, trimmed)).catch(() => {\n                updateItems(before);\n                setAnnouncement(\n                  t(\"renameFailed\", { item: row.item.label }),\n                );\n              });\n            }}\n            onMenuOpenChange={(open) => {\n              setMenuOpenId(open ? row.item.id : null);\n              if (!open) focusRow(row.item.id);\n            }}\n            onDragStart={(event, id) => {\n              setDraggingId(id);\n              event.dataTransfer.effectAllowed = \"move\";\n              event.dataTransfer.setData(\"text/plain\", id);\n            }}\n            onDragEnd={() => {\n              setDraggingId(null);\n              setDropTarget(null);\n            }}\n            onDragOver={(event, targetRow) => {\n              if (!draggingId || draggingId === targetRow.item.id) return;\n              const source = findResource(renderedItems, draggingId);\n              if (source && containsResource(source, targetRow.item.id)) return;\n              event.preventDefault();\n              event.stopPropagation();\n              const rect = event.currentTarget.getBoundingClientRect();\n              const ratio = (event.clientY - rect.top) / rect.height;\n              const position =\n                !targetRow.item.disabled &&\n                canContain(targetRow.item) &&\n                ratio >= 0.25 &&\n                ratio <= 0.75\n                  ? \"inside\"\n                  : ratio < 0.5\n                    ? \"before\"\n                    : \"after\";\n              setDropTarget({ id: targetRow.item.id, position });\n            }}\n            onDrop={(event) => {\n              event.preventDefault();\n              event.stopPropagation();\n              if (draggingId && dropTarget) {\n                void performMove({\n                  itemId: draggingId,\n                  targetId: dropTarget.id,\n                  position: dropTarget.position,\n                });\n              }\n            }}\n            renderIcon={renderIcon}\n            renderMenu={renderMenu}\n            t={t}\n            setRef={(node) => {\n              if (node) rowRefs.current.set(row.item.id, node);\n              else rowRefs.current.delete(row.item.id);\n            }}\n          />\n        ))}\n      </AnimatePresence>\n\n      {draggingId ? (\n        <div\n          aria-hidden=\"true\"\n          data-active={dropTarget?.id === null || undefined}\n          className=\"absolute inset-x-1 bottom-0 flex h-8 items-center justify-center rounded-lg border border-dashed border-border text-[11px] text-muted-foreground data-[active=true]:border-primary/50 data-[active=true]:bg-muted data-[active=true]:text-foreground\"\n        >\n          {t(\"moveToTop\")}\n        </div>\n      ) : null}\n\n      </div>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {announcement}\n      </span>\n    </>\n  );\n}\n"},{"path":"components/agents/approval-card/index.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport {\n  ArrowLeft,\n  ArrowRight,\n  Check,\n  CircleHelp,\n  LoaderCircle,\n  MessageSquareText,\n  X,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion, type Variants } from \"motion/react\";\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { ClipResizeFrame } from \"@/components/agents/clip-resize-frame\";\nimport { IconSwap } from \"@/components/agents/icon-swap\";\nimport { ActionSwapRollText } from \"@/components/motion/action-swap-roll\";\nimport { Button } from \"@/components/motion/button\";\nimport { Checkbox } from \"@/components/motion/checkbox\";\nimport { Input } from \"@/components/motion/input\";\nimport { RadioGroup, RadioGroupItem } from \"@/components/motion/radio\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { EASE_OUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\nimport { type ApprovalCardMessages, approvalCardMessages } from \"./messages\";\nimport type {\n  ApprovalCardAnswer,\n  ApprovalCardAnswers,\n  ApprovalCardProps,\n  ApprovalCardQuestion,\n  ApprovalCardStatus,\n} from \"./types\";\n\nexport { type ApprovalCardMessages, approvalCardMessages } from \"./messages\";\nexport type {\n  ApprovalCardAnswer,\n  ApprovalCardAnswers,\n  ApprovalCardOption,\n  ApprovalCardProps,\n  ApprovalCardQuestion,\n  ApprovalCardStatus,\n} from \"./types\";\n\nconst EMPTY_ANSWER: ApprovalCardAnswer = { selected: [], custom: \"\" };\n\n// `custom` is the step direction (1 forward, -1 back). The leaving question\n// goes faster than the new one arrives.\nconst QUESTION_VARIANTS: Variants = {\n  enter: (direction: number) => ({ opacity: 0, x: 10 * direction }),\n  center: { opacity: 1, x: 0, transition: { duration: 0.2, ease: EASE_OUT } },\n  exit: (direction: number) => ({\n    opacity: 0,\n    x: -8 * direction,\n    transition: { duration: 0.12, ease: EASE_OUT },\n  }),\n};\n\nconst STATUS_MESSAGE = {\n  pending: \"inputRequired\",\n  submitting: \"submitting\",\n  approved: \"approved\",\n  rejected: \"rejected\",\n  \"changes-requested\": \"changesRequested\",\n  answered: \"answered\",\n} as const satisfies Record<ApprovalCardStatus, keyof ApprovalCardMessages>;\n\nfunction getStatusClass(status: ApprovalCardStatus) {\n  if (status === \"approved\" || status === \"answered\") {\n    return \"text-emerald-600 dark:text-emerald-400\";\n  }\n  if (status === \"rejected\") return \"text-rose-600 dark:text-rose-400\";\n  if (status === \"changes-requested\") {\n    return \"text-amber-600 dark:text-amber-400\";\n  }\n  return \"text-muted-foreground\";\n}\n\nfunction getStatusBadgeClass(status: ApprovalCardStatus) {\n  if (status === \"pending\" || status === \"changes-requested\") {\n    return \"border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400\";\n  }\n  if (status === \"submitting\") {\n    return \"border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400\";\n  }\n  if (status === \"approved\" || status === \"answered\") {\n    return \"border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400\";\n  }\n  return \"border-rose-500/30 bg-rose-500/10 text-rose-600 dark:text-rose-400\";\n}\n\nfunction isAnswered(answer: ApprovalCardAnswer) {\n  return answer.selected.length > 0 || Boolean(answer.custom?.trim());\n}\n\nfunction QuestionOptions({\n  question,\n  answer,\n  disabled,\n  placeholder,\n  onChange,\n  onSingleSelect,\n}: {\n  question: ApprovalCardQuestion;\n  answer: ApprovalCardAnswer;\n  disabled: boolean;\n  placeholder: string;\n  onChange: (answer: ApprovalCardAnswer) => void;\n  onSingleSelect?: () => void;\n}) {\n  const custom = answer.custom ?? \"\";\n\n  return (\n    <div className=\"mt-3\">\n      {question.options?.length ? (\n        question.multiple ? (\n          <div className=\"grid gap-0.5\">\n            {question.options.map((option) => (\n              <Checkbox\n                key={option.value}\n                checked={answer.selected.includes(option.value)}\n                disabled={disabled || option.disabled}\n                label={option.label}\n                description={option.description}\n                onCheckedChange={(checked) =>\n                  onChange({\n                    ...answer,\n                    selected: checked\n                      ? [...answer.selected, option.value]\n                      : answer.selected.filter((value) => value !== option.value),\n                  })\n                }\n                className=\"min-h-9 rounded-lg px-1.5 py-1\"\n              />\n            ))}\n          </div>\n        ) : (\n          <RadioGroup\n            value={answer.selected[0] ?? \"\"}\n            onValueChange={(value) => {\n              onChange({ selected: [value], custom: \"\" });\n              onSingleSelect?.();\n            }}\n            className=\"gap-0.5\"\n          >\n            {question.options.map((option) => (\n              <RadioGroupItem\n                key={option.value}\n                value={option.value}\n                label={option.label}\n                description={option.description}\n                disabled={disabled || option.disabled}\n                className=\"min-h-9 rounded-lg px-1.5 py-1\"\n              />\n            ))}\n          </RadioGroup>\n        )\n      ) : null}\n\n      {question.allowCustom ? (\n        <Input\n          value={custom}\n          disabled={disabled}\n          placeholder={question.customPlaceholder ?? placeholder}\n          onChange={(value) =>\n            onChange({\n              selected: question.multiple ? answer.selected : [],\n              custom: value,\n            })\n          }\n          className={cn(\"p-0.5\", question.options?.length && \"mt-1.5\")}\n          classNames={{\n            field: \"h-10 rounded-full border border-border bg-transparent\",\n            input: \"px-4 text-sm\",\n          }}\n        />\n      ) : null}\n    </div>\n  );\n}\n\nfunction ProgressDots({\n  current,\n  ids,\n  label,\n}: {\n  current: number;\n  ids: string[];\n  label: string;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  return (\n    <span className=\"flex gap-1.5\">\n      <span className=\"sr-only\">{label}</span>\n      {ids.map((id, index) => (\n        <motion.span\n          key={id}\n          aria-hidden=\"true\"\n          initial={{\n            scale: reduce || index === current ? 1 : 0.75,\n            opacity: index <= current ? 1 : 0.35,\n          }}\n          animate={{\n            scale: reduce || index === current ? 1 : 0.75,\n            opacity: index <= current ? 1 : 0.35,\n          }}\n          transition={SPRING_SWAP}\n          className=\"size-1.5 rounded-full bg-foreground\"\n        />\n      ))}\n    </span>\n  );\n}\n\nexport function ApprovalCard({\n  title,\n  description,\n  children,\n  questions = [],\n  status = \"pending\",\n  answers,\n  defaultAnswers = {},\n  onAnswersChange,\n  step,\n  defaultStep = 0,\n  onStepChange,\n  onSubmit,\n  onApprove,\n  onReject,\n  onRequestChanges,\n  onDismiss,\n  approveLabel,\n  submitLabel,\n  result,\n  labels,\n  className,\n}: ApprovalCardProps) {\n  const t = useMessages(\"approvalCard\", approvalCardMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const [internalAnswers, setInternalAnswers] =\n    useState<ApprovalCardAnswers>(defaultAnswers);\n  const [internalStep, setInternalStep] = useState(defaultStep);\n  const autoAdvanceTimer = useRef<number | undefined>(undefined);\n  const currentAnswers = answers ?? internalAnswers;\n  const currentStep = Math.min(\n    Math.max(0, step ?? internalStep),\n    Math.max(0, questions.length - 1),\n  );\n  const question = questions[currentStep];\n  const questionMode = questions.length > 0;\n  const multipleQuestions = questions.length > 1;\n  const pending = status === \"pending\";\n  const busy = status === \"submitting\";\n  const interactive = pending || busy;\n  const currentAnswer = question\n    ? (currentAnswers[question.id] ?? EMPTY_ANSWER)\n    : EMPTY_ANSWER;\n  const displayTitle = question?.title ?? title ?? t(\"title\");\n  const titleKey = question?.id ?? String(status);\n  const statusLabel = t(STATUS_MESSAGE[status]);\n\n  const clearAutoAdvance = useCallback(() => {\n    if (autoAdvanceTimer.current === undefined) return;\n    window.clearTimeout(autoAdvanceTimer.current);\n    autoAdvanceTimer.current = undefined;\n  }, []);\n\n  useEffect(() => clearAutoAdvance, [clearAutoAdvance]);\n\n  const setAnswers = useCallback(\n    (next: ApprovalCardAnswers) => {\n      if (answers === undefined) setInternalAnswers(next);\n      onAnswersChange?.(next);\n    },\n    [answers, onAnswersChange],\n  );\n\n  // Which way the last step went: 1 forward, -1 back. Set before the step\n  // changes, so the question that leaves and the one that enters agree.\n  const [direction, setDirection] = useState<1 | -1>(1);\n\n  const setStep = (next: number) => {\n    clearAutoAdvance();\n    setDirection(next < currentStep ? -1 : 1);\n    if (step === undefined) setInternalStep(next);\n    onStepChange?.(next);\n  };\n\n  // Two answers set in one batch would otherwise both spread the answers\n  // from this render, and the second would drop the first.\n  const answersRef = useRef(currentAnswers);\n  useLayoutEffect(() => {\n    answersRef.current = currentAnswers;\n  });\n  const updateCurrentAnswer = (next: ApprovalCardAnswer) => {\n    if (!question) return;\n    const merged = { ...answersRef.current, [question.id]: next };\n    answersRef.current = merged;\n    setAnswers(merged);\n  };\n\n  const continueQuestion = () => {\n    if (currentStep < questions.length - 1) {\n      setStep(currentStep + 1);\n      return;\n    }\n    onSubmit?.(currentAnswers);\n  };\n\n  const queueAutoAdvance = () => {\n    if (\n      !question ||\n      question.multiple ||\n      question.autoAdvance === false ||\n      currentStep >= questions.length - 1 ||\n      busy\n    ) {\n      return;\n    }\n\n    clearAutoAdvance();\n    const queuedFor = question.id;\n    autoAdvanceTimer.current = window.setTimeout(() => {\n      autoAdvanceTimer.current = undefined;\n      // Read the card as it is now: the question may have changed, or the\n      // card may no longer be waiting for an answer.\n      const now = latest.current;\n      if (!now.pending || now.questionId !== queuedFor) return;\n      if (now.currentStep >= now.questionCount - 1) return;\n      now.setStep(now.currentStep + 1);\n    }, 240);\n  };\n  const latest = useRef({\n    pending,\n    questionId: question?.id,\n    currentStep,\n    questionCount: questions.length,\n    setStep,\n  });\n  useLayoutEffect(() => {\n    latest.current = {\n      pending,\n      questionId: question?.id,\n      currentStep,\n      questionCount: questions.length,\n      setStep,\n    };\n  });\n\n  return (\n    // The card's bottom edge glides when it grows or shrinks (a step with\n    // more options, or the form folding away on submit) instead of jumping.\n    <ClipResizeFrame\n      data-state={status}\n      aria-busy={busy}\n      className={cn(\"w-full text-sm\", className)}\n      contentClassName=\"p-4\"\n    >\n      <div className=\"flex items-start gap-3\">\n        <span\n          aria-hidden=\"true\"\n          className={cn(\n            \"grid size-5 shrink-0 place-items-center text-muted-foreground\",\n            getStatusClass(status),\n          )}\n        >\n          <IconSwap id={busy ? \"busy\" : interactive ? \"ask\" : status}>\n            {busy ? (\n              <LoaderCircle className={cn(\"size-4\", !reduce && \"animate-spin\")} />\n            ) : interactive ? (\n              questionMode ? (\n                <CircleHelp className=\"size-4\" />\n              ) : (\n                <MessageSquareText className=\"size-4\" />\n              )\n            ) : status === \"rejected\" ? (\n              <X className=\"size-4\" />\n            ) : (\n              <Check className=\"size-4\" />\n            )}\n          </IconSwap>\n        </span>\n\n        <div className=\"relative min-w-0 flex-1\">\n          <div className=\"flex min-w-0 items-start gap-3\">\n            <h3 className=\"min-w-0 flex-1 text-base font-medium leading-5 text-foreground\">\n              <ActionSwapRollText value={titleKey}>\n                {displayTitle}\n              </ActionSwapRollText>\n            </h3>\n            {questionMode && interactive ? (\n              multipleQuestions ? (\n                <span className=\"shrink-0 text-xs tabular-nums text-muted-foreground/65\">\n                  {t(\"stepCount\", {\n                    current: currentStep + 1,\n                    total: questions.length,\n                  })}\n                </span>\n              ) : null\n            ) : (\n              <span\n                className={cn(\n                  \"shrink-0 rounded-full border px-2 py-0.5 text-[11px] font-medium transition-colors\",\n                  getStatusBadgeClass(status),\n                )}\n              >\n                <ActionSwapRollText value={status}>{statusLabel}</ActionSwapRollText>\n              </span>\n            )}\n            {onDismiss ? (\n              <Tooltip content={t(\"dismiss\")} side=\"top\">\n                <button\n                  type=\"button\"\n                  aria-label={t(\"dismiss\")}\n                  onClick={onDismiss}\n                  className=\"grid size-5 shrink-0 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n                >\n                  <X className=\"size-4\" />\n                </button>\n              </Tooltip>\n            ) : null}\n          </div>\n\n          {/* On submit the form leaves the layout at once (popLayout) and\n              fades out while the card's edge glides up over it. */}\n          <AnimatePresence initial={false} mode=\"popLayout\">\n          {interactive ? (\n          <motion.div\n            key=\"form\"\n            exit={{ opacity: 0, transition: { duration: 0.14, ease: EASE_OUT } }}\n          >\n            {questionMode && question ? (\n              // Forward slides in from the right, back from the left, so the\n              // steps read as a row the card moves along. The old question\n              // leaves fast, so the next one is never kept waiting.\n              <AnimatePresence initial={false} mode=\"wait\" custom={direction}>\n                <motion.div\n                  key={question.id}\n                  custom={direction}\n                  variants={QUESTION_VARIANTS}\n                  initial={reduce ? false : \"enter\"}\n                  animate=\"center\"\n                  exit={reduce ? { opacity: 0, transition: { duration: 0 } } : \"exit\"}\n                >\n                  {question.description ? (\n                    <p className=\"mt-1 leading-5 text-muted-foreground\">\n                      {question.description}\n                    </p>\n                  ) : null}\n                  <QuestionOptions\n                    question={question}\n                    answer={currentAnswer}\n                    disabled={busy}\n                    placeholder={t(\"customPlaceholder\")}\n                    onChange={updateCurrentAnswer}\n                    onSingleSelect={queueAutoAdvance}\n                  />\n                </motion.div>\n              </AnimatePresence>\n            ) : (\n              <div>\n                {description ? (\n                  <p className=\"mt-1 leading-5 text-muted-foreground\">\n                    {description}\n                  </p>\n                ) : null}\n                {children ? <div className=\"mt-3\">{children}</div> : null}\n              </div>\n            )}\n\n            {questionMode ? (\n              <div className=\"mt-4 flex items-center gap-3\">\n                {multipleQuestions ? (\n                  <>\n                    <Tooltip content={t(\"previousQuestion\")} side=\"top\">\n                      <Button\n                        variant=\"ghost\"\n                        size=\"icon\"\n                        aria-label={t(\"previousQuestion\")}\n                        disabled={busy || currentStep === 0}\n                        onClick={() => setStep(currentStep - 1)}\n                        className=\"rounded-full\"\n                      >\n                        <ArrowLeft className=\"size-4\" />\n                      </Button>\n                    </Tooltip>\n                    <ProgressDots\n                      current={currentStep}\n                      ids={questions.map((item) => item.id)}\n                      label={t(\"questionProgress\", {\n                        current: currentStep + 1,\n                        total: questions.length,\n                      })}\n                    />\n                  </>\n                ) : null}\n                <Tooltip\n                  // The last step's button carries its own text label.\n                  content={currentStep === questions.length - 1 ? null : t(\"nextQuestion\")}\n                  side=\"top\"\n                >\n                  <Button\n                    size={currentStep === questions.length - 1 ? \"sm\" : \"icon\"}\n                    aria-label={\n                      currentStep === questions.length - 1\n                        ? t(\"submit\")\n                        : t(\"nextQuestion\")\n                    }\n                    disabled={busy || !isAnswered(currentAnswer)}\n                    onClick={continueQuestion}\n                    className=\"ml-auto rounded-full\"\n                  >\n                    {busy ? (\n                      <LoaderCircle className={cn(\"size-4\", !reduce && \"animate-spin\")} />\n                    ) : currentStep === questions.length - 1 ? (\n                      <>\n                        {submitLabel ?? t(\"submit\")}\n                        <ArrowRight className=\"size-3.5\" />\n                      </>\n                    ) : (\n                      <ArrowRight className=\"size-4\" />\n                    )}\n                  </Button>\n                </Tooltip>\n              </div>\n            ) : (\n              <div className=\"mt-4 flex flex-wrap items-center gap-2\">\n                <Button\n                  size=\"sm\"\n                  disabled={busy}\n                  onClick={onApprove}\n                  className=\"rounded-full\"\n                >\n                  {approveLabel ?? t(\"approve\")}\n                </Button>\n                {onRequestChanges ? (\n                  <Button\n                    variant=\"secondary\"\n                    size=\"sm\"\n                    disabled={busy}\n                    onClick={onRequestChanges}\n                    className=\"rounded-full\"\n                  >\n                    {t(\"requestChanges\")}\n                  </Button>\n                ) : null}\n                {onReject ? (\n                  <Button\n                    variant=\"ghost\"\n                    size=\"sm\"\n                    disabled={busy}\n                    onClick={onReject}\n                    className=\"rounded-full text-muted-foreground hover:text-rose-600 dark:hover:text-rose-400\"\n                  >\n                    {t(\"reject\")}\n                  </Button>\n                ) : null}\n              </div>\n            )}\n          </motion.div>\n          ) : (\n            <motion.p\n              key=\"result\"\n              initial={{ opacity: 0 }}\n              animate={{ opacity: 1, transition: { duration: 0.2, delay: 0.06, ease: EASE_OUT } }}\n              className=\"mt-1 text-sm text-muted-foreground\"\n            >\n              {result ?? statusLabel}\n            </motion.p>\n          )}\n          </AnimatePresence>\n        </div>\n      </div>\n    </ClipResizeFrame>\n  );\n}\n"},{"path":"components/agents/code-block.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport { Check, Copy, FileCode2, LoaderCircle } from \"lucide-react\";\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { type ReactNode, useLayoutEffect, useMemo, useRef } from \"react\";\nimport {\n  type AgentCodeLanguage,\n  AgentCodeLine,\n  useAgentCodeTokens,\n} from \"@/components/agents/agent-code\";\nimport { IconSwap } from \"@/components/agents/icon-swap\";\nimport { ActionSwapRollText } from \"@/components/motion/action-swap-roll\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { SPRING_PRESS } from \"@/lib/ease\";\nimport { useCopy } from \"@/lib/hooks/use-copy\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport const codeBlockMessages = {\n  writing: \"Writing\",\n  ready: \"Ready\",\n  copy: \"Copy code\",\n  copied: \"Copied\",\n};\n\nexport type CodeBlockMessages = typeof codeBlockMessages;\n\nexport type CodeBlockStatus = \"streaming\" | \"complete\";\n\n/** One identity for the default, so the highlighted-line Set stays memoized. */\nconst NO_LINES: number[] = [];\n\nexport interface CodeBlockProps {\n  /** The source code to show. May grow while `status` is \"streaming\". */\n  code: string;\n  /** Language for syntax highlighting, also shown in the header. Default: \"typescript\" */\n  language?: AgentCodeLanguage;\n  /** File name shown in the header. */\n  filename?: ReactNode;\n  /** \"streaming\" shows Writing and follows new lines, \"complete\" shows Ready. Default: \"complete\" */\n  status?: CodeBlockStatus;\n  /** Shows a line number gutter. Default: true */\n  showLineNumbers?: boolean;\n  /** 1-based line numbers to tint. */\n  highlightLines?: number[];\n  /** Height in px before the code scrolls. Default: 280 */\n  maxHeight?: number;\n  /** Wraps long lines instead of scrolling sideways. Default: false */\n  wrap?: boolean;\n  /** Shows the copy button. Default: true */\n  copyable?: boolean;\n  /** Runs in place of the clipboard write when copy is pressed. Shows the copy button. */\n  onCopy?: () => void | Promise<void>;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Override any built-in string. */\n  labels?: Partial<CodeBlockMessages>;\n}\n\nexport function CodeBlock({\n  code,\n  language = \"typescript\",\n  filename,\n  status = \"complete\",\n  showLineNumbers = true,\n  highlightLines = NO_LINES,\n  maxHeight = 280,\n  wrap = false,\n  copyable = true,\n  onCopy,\n  className,\n  labels,\n}: CodeBlockProps) {\n  const t = useMessages(\"codeBlock\", codeBlockMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const viewportRef = useRef<HTMLDivElement>(null);\n  const { copied, copy: handleCopy } = useCopy({ text: code, onCopy });\n  const streaming = status === \"streaming\";\n  const tokens = useAgentCodeTokens(code, language);\n  const highlighted = useMemo(\n    () => new Set(highlightLines),\n    [highlightLines],\n  );\n  let offset = 0;\n  const lines = code.split(\"\\n\").map((content) => {\n    const line = { content, offset };\n    offset += content.length + 1;\n    return line;\n  });\n\n  useLayoutEffect(() => {\n    const viewport = viewportRef.current;\n    if (!viewport || !streaming) return;\n\n    const frame = requestAnimationFrame(() => {\n      if (viewport.scrollHeight <= viewport.clientHeight) return;\n      if (typeof viewport.scrollTo === \"function\") {\n        viewport.scrollTo({\n          top: viewport.scrollHeight,\n          behavior: reduce ? \"auto\" : \"smooth\",\n        });\n      } else {\n        viewport.scrollTop = viewport.scrollHeight;\n      }\n    });\n    return () => cancelAnimationFrame(frame);\n  });\n\n  return (\n    <div\n      data-state={status}\n      aria-busy={streaming}\n      className={cn(\n        \"w-full overflow-hidden rounded-2xl bg-muted/80 text-sm\",\n        className,\n      )}\n    >\n      <div className=\"flex h-10 items-center gap-2.5 px-3\">\n        <FileCode2\n          aria-hidden=\"true\"\n          className=\"size-3.5 shrink-0 text-muted-foreground/70\"\n        />\n        {filename ? (\n          <span className=\"min-w-0 truncate font-mono text-xs text-foreground/80\">\n            {filename}\n          </span>\n        ) : null}\n        <span className=\"text-[11px] font-medium uppercase tracking-wide text-muted-foreground/55\">\n          {language}\n        </span>\n        <span\n          className={cn(\n            \"ml-auto inline-flex shrink-0 items-center gap-1 text-[11px] font-medium\",\n            streaming\n              ? \"text-blue-600 dark:text-blue-400\"\n              : \"text-emerald-600 dark:text-emerald-400\",\n          )}\n        >\n          <IconSwap id={streaming ? \"writing\" : \"ready\"}>\n            {streaming ? (\n              <LoaderCircle className={cn(\"size-3\", !reduce && \"animate-spin\")} />\n            ) : (\n              <Check className=\"size-3\" />\n            )}\n          </IconSwap>\n          <ActionSwapRollText value={status}>\n            {streaming ? t(\"writing\") : t(\"ready\")}\n          </ActionSwapRollText>\n        </span>\n        {copyable || onCopy ? (\n          <Tooltip content={copied ? t(\"copied\") : t(\"copy\")} side=\"top\">\n            <motion.button\n              type=\"button\"\n              aria-label={copied ? t(\"copied\") : t(\"copy\")}\n              onClick={handleCopy}\n              whileTap={reduce ? undefined : { scale: 0.95 }}\n              transition={SPRING_PRESS}\n              className=\"grid size-7 shrink-0 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-background/70 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n            >\n              <IconSwap id={copied ? \"copied\" : \"copy\"}>\n                {copied ? (\n                  <Check className=\"size-3.5\" />\n                ) : (\n                  <Copy className=\"size-3.5\" />\n                )}\n              </IconSwap>\n            </motion.button>\n          </Tooltip>\n        ) : null}\n      </div>\n\n      <div\n        ref={viewportRef}\n        role={streaming ? \"log\" : undefined}\n        aria-live={streaming ? \"polite\" : undefined}\n        className=\"scrollbar-hide overflow-auto border-t border-foreground/[0.06] py-2\"\n        style={{ maxHeight }}\n      >\n        <pre className=\"m-0 min-w-max font-mono text-xs leading-5 text-foreground/85\">\n          <code>\n            {lines.map((line, index) => {\n              const lineNumber = index + 1;\n              return (\n                <span\n                  key={line.offset}\n                  className={cn(\n                    \"grid min-h-5\",\n                    showLineNumbers\n                      ? \"grid-cols-[2.75rem_minmax(0,1fr)]\"\n                      : \"grid-cols-1\",\n                    // Tint plus a 2px edge, like changed lines in File Diff:\n                    // a tint alone melts into the panel.\n                    highlighted.has(lineNumber) &&\n                      \"bg-blue-500/10 shadow-[inset_2px_0_0_var(--color-blue-500)]\",\n                  )}\n                >\n                  {showLineNumbers ? (\n                    <span className=\"select-none pr-3 text-right tabular-nums text-muted-foreground/35\">\n                      {lineNumber}\n                    </span>\n                  ) : null}\n                  <AgentCodeLine\n                    code={line.content}\n                    tokens={tokens?.[index]}\n                    className={cn(\n                      \"pr-4\",\n                      showLineNumbers ? \"pl-1\" : \"pl-4\",\n                      wrap ? \"whitespace-pre-wrap break-words\" : \"whitespace-pre\",\n                    )}\n                  />\n                </span>\n              );\n            })}\n          </code>\n        </pre>\n      </div>\n    </div>\n  );\n}\n"},{"path":"components/agents/file-diff.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport {\n  Check,\n  ChevronDown,\n  Copy,\n  FileCode2,\n  LoaderCircle,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { type ReactNode, useId, useLayoutEffect, useRef } from \"react\";\nimport {\n  type AgentCodeLanguage,\n  AgentCodeLine,\n  useAgentCodeTokens,\n} from \"@/components/agents/agent-code\";\nimport { AgentDisclosure } from \"@/components/agents/agent-disclosure\";\nimport { IconSwap } from \"@/components/agents/icon-swap\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from \"@/lib/ease\";\n\nconst DIFFSTAT_BLOCKS = 5;\n\n// A streamed line settles quickly: lines can arrive many times a second.\nconst LINE_IN = { duration: 0.18, ease: EASE_OUT } as const;\n\nimport { useCopy } from \"@/lib/hooks/use-copy\";\nimport { useStatusOpen } from \"@/lib/hooks/use-status-open\";\nimport { formatNumber, useLocale, useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport type FileDiffStatus = \"streaming\" | \"complete\";\nexport type FileDiffLineType = \"added\" | \"removed\" | \"context\";\n\nexport interface FileDiffLine {\n  /** Stable key, so streamed lines keep their place. */\n  id: string;\n  /** Marks the line added (green, +), removed (red, −) or unchanged. Default: \"context\" */\n  type?: FileDiffLineType;\n  /** Line number in the old file, shown in the first gutter. Blank when not set. */\n  oldLine?: number;\n  /** Line number in the new file, shown in the second gutter. Blank when not set. */\n  newLine?: number;\n  /** The line's code, without the + or − marker. Syntax highlighted. */\n  content: string;\n}\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const fileDiffMessages = {\n  applying: \"Applying changes\",\n  applied: \"Changes applied\",\n  changes: \"File changes\",\n  copy: \"Copy diff\",\n  copied: \"Copied\",\n};\n\nexport type FileDiffMessages = typeof fileDiffMessages;\n\nexport interface FileDiffProps {\n  /** File name or path shown in the header. */\n  file: ReactNode;\n  /** Diff lines, each added, removed or context, with optional line numbers. */\n  lines: FileDiffLine[];\n  /** \"streaming\" while lines arrive, \"complete\" once the edit lands. Default: \"streaming\" */\n  status?: FileDiffStatus;\n  /** Whether the diff is expanded, for controlled use. */\n  open?: boolean;\n  /** Whether the diff starts expanded when uncontrolled. Default: true */\n  defaultOpen?: boolean;\n  /** Called with the new state when the diff expands or collapses. */\n  onOpenChange?: (open: boolean) => void;\n  /** Fold the diff when status moves from streaming to complete. Default: true */\n  collapseOnComplete?: boolean;\n  /** Tallest the line viewport grows before it scrolls (px). Default: 220 */\n  maxHeight?: number;\n  /** Language used for syntax highlighting. Default: \"typescript\" */\n  language?: AgentCodeLanguage;\n  /** Text the copy button writes to the clipboard. Shows the button when set. */\n  copyText?: string;\n  /** Runs instead of the clipboard write when the copy button is pressed. */\n  onCopy?: () => void | Promise<void>;\n  /** Override any built-in string. */\n  labels?: Partial<FileDiffMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nfunction ChangeCount({ value, type }: { value: number; type: \"added\" | \"removed\" }) {\n  const { locale } = useLocale();\n  if (!value) return null;\n  return (\n    <span\n      className={cn(\n        \"font-mono text-xs tabular-nums\",\n        type === \"added\"\n          ? \"text-emerald-600 dark:text-emerald-400\"\n          : \"text-rose-600 dark:text-rose-400\",\n      )}\n    >\n      {type === \"added\" ? \"+\" : \"−\"}\n      {formatNumber(value, locale)}\n    </span>\n  );\n}\n\n/**\n * Five blocks split between additions and deletions, so the size and shape\n * of the change reads at a glance. The counts beside it carry the numbers.\n */\nfunction DiffStat({ additions, deletions }: { additions: number; deletions: number }) {\n  const total = additions + deletions;\n  if (!total) return null;\n  const added = Math.round((additions / total) * DIFFSTAT_BLOCKS);\n  return (\n    <span aria-hidden=\"true\" className=\"flex shrink-0 gap-0.5\">\n      {Array.from({ length: DIFFSTAT_BLOCKS }, (_, index) => (\n        <span\n          // biome-ignore lint/suspicious/noArrayIndexKey: fixed blocks\n          key={index}\n          className={cn(\n            \"size-1.5 rounded-[2px] transition-colors duration-200\",\n            index < added ? \"bg-emerald-500\" : \"bg-rose-500\",\n          )}\n        />\n      ))}\n    </span>\n  );\n}\n\nexport function FileDiff({\n  file,\n  lines,\n  status = \"streaming\",\n  open,\n  defaultOpen = true,\n  onOpenChange,\n  collapseOnComplete = true,\n  maxHeight = 220,\n  language = \"typescript\",\n  copyText,\n  onCopy,\n  labels,\n  className,\n}: FileDiffProps) {\n  const t = useMessages(\"fileDiff\", fileDiffMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const triggerId = `${baseId}-trigger`;\n  const contentId = `${baseId}-content`;\n  const viewportRef = useRef<HTMLDivElement>(null);\n  const { copied, copy: handleCopy } = useCopy({ text: copyText, onCopy });\n  // Opens when streaming starts; folds when it completes, if asked to.\n  const [currentOpen, setOpen] = useStatusOpen({\n    status,\n    open,\n    defaultOpen,\n    onOpenChange,\n    decide: (previous, next) => {\n      if (previous !== \"streaming\" && next === \"streaming\") return true;\n      if (previous === \"streaming\" && next === \"complete\" && collapseOnComplete) return false;\n      return undefined;\n    },\n  });\n  const streaming = status === \"streaming\";\n  const additions = lines.filter((line) => line.type === \"added\").length;\n  const deletions = lines.filter((line) => line.type === \"removed\").length;\n  const canCopy = Boolean(copyText || onCopy);\n  const code = lines.map((line) => line.content).join(\"\\n\");\n  const tokens = useAgentCodeTokens(code, language);\n\n  useLayoutEffect(() => {\n    const viewport = viewportRef.current;\n    if (!viewport || !currentOpen || !streaming) return;\n\n    const frame = requestAnimationFrame(() => {\n      if (viewport.scrollHeight <= viewport.clientHeight) return;\n      if (typeof viewport.scrollTo === \"function\") {\n        viewport.scrollTo({\n          top: viewport.scrollHeight,\n          behavior: reduce ? \"auto\" : \"smooth\",\n        });\n      } else {\n        viewport.scrollTop = viewport.scrollHeight;\n      }\n    });\n    return () => cancelAnimationFrame(frame);\n  });\n\n  return (\n    <div\n      data-state={status}\n      aria-busy={streaming}\n      className={cn(\"w-full text-sm\", className)}\n    >\n      <button\n        id={triggerId}\n        type=\"button\"\n        aria-expanded={currentOpen}\n        aria-controls={contentId}\n        onClick={() => setOpen(!currentOpen)}\n        className=\"group flex min-h-9 w-full items-center gap-2 rounded-full py-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\"\n      >\n        <FileCode2\n          aria-hidden=\"true\"\n          className=\"size-4 shrink-0 text-muted-foreground\"\n        />\n        <span className=\"min-w-0 flex-1 truncate font-mono text-xs text-foreground/80\">\n          {file}\n        </span>\n        <span className=\"flex shrink-0 items-center gap-2\">\n          <ChangeCount value={additions} type=\"added\" />\n          <ChangeCount value={deletions} type=\"removed\" />\n          <DiffStat additions={additions} deletions={deletions} />\n        </span>\n        <span className=\"grid size-4 shrink-0 place-items-center text-muted-foreground/60\">\n          <IconSwap id={streaming ? \"applying\" : \"applied\"}>\n            {streaming ? (\n              <LoaderCircle\n                aria-label={t(\"applying\")}\n                className={cn(\"size-3.5\", !reduce && \"animate-spin\")}\n              />\n            ) : (\n              <Check aria-label={t(\"applied\")} className=\"size-3.5\" />\n            )}\n          </IconSwap>\n        </span>\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: currentOpen ? 180 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n          className=\"shrink-0 text-muted-foreground/45 transition-colors group-hover:text-muted-foreground\"\n        >\n          <ChevronDown className=\"size-3.5\" />\n        </motion.span>\n      </button>\n\n      <AgentDisclosure\n        id={contentId}\n        role=\"region\"\n        aria-labelledby={triggerId}\n        open={currentOpen}\n      >\n        <div className=\"pl-6 pt-1.5\">\n          <div className=\"group/diff relative overflow-hidden rounded-xl bg-muted/80\">\n            <div\n              ref={viewportRef}\n              data-slot=\"file-diff-viewport\"\n              aria-live=\"polite\"\n              className=\"scrollbar-hide overflow-auto\"\n              style={{ maxHeight }}\n            >\n              <div className=\"font-mono text-xs leading-5\">\n                <span className=\"sr-only\">{t(\"changes\")}</span>\n                {/* Lines that stream in fade in, opacity only: a moving line\n                    fights the auto-scroll that follows the stream. Lines\n                    already there when the diff mounts are simply shown. */}\n                <AnimatePresence initial={false}>\n                {lines.map((line, index) => {\n                  const type = line.type ?? \"context\";\n                  // A streamed line waits for its syntax colours before it\n                  // shows: shown at once, it would flash as plain text and\n                  // then recolour mid-fade. Before the highlighter has run at\n                  // all (`tokens` null), lines show plain.\n                  const ready = tokens === null || Boolean(tokens[index]);\n                  return (\n                    <motion.div\n                      key={line.id}\n                      initial={{ opacity: 0 }}\n                      animate={{ opacity: ready ? 1 : 0 }}\n                      transition={LINE_IN}\n                      className={cn(\n                        \"grid grid-cols-[2.25rem_2.25rem_1rem_minmax(0,1fr)]\",\n                        // A tint plus a 2px edge: the edge still marks the\n                        // line where a faint tint melts into the panel.\n                        type === \"added\" &&\n                          \"bg-emerald-500/10 shadow-[inset_2px_0_0_var(--color-emerald-500)]\",\n                        type === \"removed\" &&\n                          \"bg-rose-500/10 shadow-[inset_2px_0_0_var(--color-rose-500)]\",\n                      )}\n                    >\n                      <span className=\"select-none pr-2 text-right tabular-nums text-muted-foreground/40\">\n                        {line.oldLine}\n                      </span>\n                      <span className=\"select-none pr-2 text-right tabular-nums text-muted-foreground/40\">\n                        {line.newLine}\n                      </span>\n                      <span\n                        className={cn(\n                          \"select-none text-center text-muted-foreground/45\",\n                          type === \"added\" &&\n                            \"text-emerald-600 dark:text-emerald-400\",\n                          type === \"removed\" &&\n                            \"text-rose-600 dark:text-rose-400\",\n                        )}\n                      >\n                        {type === \"added\"\n                          ? \"+\"\n                          : type === \"removed\"\n                            ? \"−\"\n                            : \"\"}\n                      </span>\n                      <AgentCodeLine\n                        code={line.content}\n                        tokens={tokens?.[index]}\n                        className=\"min-w-0 whitespace-pre px-1.5\"\n                      />\n                    </motion.div>\n                  );\n                })}\n                </AnimatePresence>\n              </div>\n            </div>\n\n            {canCopy ? (\n              // Floats in the corner instead of taking a row of its own. It\n              // shows on hover or focus where there is a pointer, always on\n              // touch, and stays while \"Copied\" is showing.\n              <div\n                className={cn(\n                  \"absolute top-1.5 right-1.5 transition-opacity duration-150 group-focus-within/diff:opacity-100 group-hover/diff:opacity-100 [@media(hover:none)]:opacity-100\",\n                  copied ? \"opacity-100\" : \"opacity-0\",\n                )}\n              >\n                <Tooltip content={copied ? t(\"copied\") : t(\"copy\")} side=\"top\">\n                  <motion.button\n                    type=\"button\"\n                    aria-label={copied ? t(\"copied\") : t(\"copy\")}\n                    onClick={handleCopy}\n                    whileTap={reduce ? undefined : { scale: 0.95 }}\n                    transition={SPRING_PRESS}\n                    className=\"grid size-7 place-items-center rounded-full border border-border bg-background text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n                  >\n                    <IconSwap id={copied ? \"copied\" : \"copy\"}>\n                      {copied ? (\n                        <Check className=\"size-3.5\" />\n                      ) : (\n                        <Copy className=\"size-3.5\" />\n                      )}\n                    </IconSwap>\n                  </motion.button>\n                </Tooltip>\n              </div>\n            ) : null}\n          </div>\n        </div>\n      </AgentDisclosure>\n    </div>\n  );\n}\n"},{"path":"components/agents/image-generation.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport { Check, CircleAlert, RotateCcw } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { useEffect, useRef } from \"react\";\nimport { IconSwap } from \"@/components/agents/icon-swap\";\nimport { EASE_IN_OUT, EASE_OUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ImageGenerationStatus =\n  | \"queued\"\n  | \"generating\"\n  | \"refining\"\n  | \"complete\"\n  | \"error\";\n\nexport interface ImageGenerationProps {\n  /** The completed media. Pass an img, Next Image, canvas, video, or custom preview. */\n  children?: ReactNode;\n  /** Generation stage. Sets the dither overlay, media blur and status line. Default: \"generating\" */\n  status?: ImageGenerationStatus;\n  /** Accessible description. Defaults to a description derived from prompt. */\n  label?: string;\n  /** The prompt, shown in quotes under the status line. */\n  prompt?: string;\n  /** Badge in the top right corner. Default: \"1024 × 1024\" */\n  resolution?: string;\n  /** CSS aspect ratio reserved before generated media is available. */\n  aspectRatio?: CSSProperties[\"aspectRatio\"];\n  /** \"compact\" caps the width at 208px, \"fluid\" fills the container. Default: \"compact\" */\n  size?: \"compact\" | \"fluid\";\n  /** Lets the active dither cluster follow fine-pointer movement. */\n  interactive?: boolean;\n  /** Replaces the built-in status line text for the current status. */\n  statusText?: string;\n  /** Shows the status line under the media. Default: true */\n  showStatus?: boolean;\n  /** Called from the retry button, which shows only when status is \"error\". */\n  onRetry?: () => void;\n  /** Override any built-in string. `{status}` and `{prompt}` fill `labelWithPrompt`; `{prompt}` fills `quotedPrompt`. */\n  labels?: Partial<ImageGenerationMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes merged onto the layer that holds the media. */\n  mediaClassName?: string;\n  /** Classes merged onto the status line. */\n  statusClassName?: string;\n}\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const imageGenerationMessages = {\n  queued: \"Waiting to generate\",\n  generating: \"Generating image\",\n  refining: \"Refining details\",\n  complete: \"Image ready\",\n  error: \"Generation failed\",\n  labelWithPrompt: \"{status}: {prompt}\",\n  quotedPrompt: \"“{prompt}”\",\n  retry: \"Try again\",\n};\n\nexport type ImageGenerationMessages = typeof imageGenerationMessages;\n\nconst MEDIA_STATE: Record<\n  ImageGenerationStatus,\n  { filter: string; opacity: number; scale: number }\n> = {\n  queued: { filter: \"blur(4px) saturate(0.75)\", opacity: 0, scale: 1.02 },\n  generating: { filter: \"blur(3px) saturate(0.85)\", opacity: 0, scale: 1.015 },\n  refining: { filter: \"blur(1.5px) saturate(0.95)\", opacity: 0.62, scale: 1.005 },\n  complete: { filter: \"blur(0px) saturate(1)\", opacity: 1, scale: 1 },\n  error: { filter: \"blur(2px) saturate(0.5)\", opacity: 0.28, scale: 1 },\n};\n\nconst OVERLAY_OPACITY: Record<ImageGenerationStatus, number> = {\n  queued: 1,\n  generating: 1,\n  refining: 0.48,\n  complete: 0,\n  error: 0,\n};\n\nconst DOT_GAP = 10;\nconst TWO_PI = Math.PI * 2;\n\nfunction DitherMark({\n  status,\n  reduce,\n}: {\n  status: ImageGenerationStatus;\n  reduce: boolean;\n}) {\n  if (status === \"complete\") {\n    return <Check aria-hidden=\"true\" className=\"size-3.5\" />;\n  }\n\n  if (status === \"error\") {\n    return <CircleAlert aria-hidden=\"true\" className=\"size-3.5\" />;\n  }\n\n  return (\n    <motion.span\n      aria-hidden=\"true\"\n      animate={reduce ? undefined : { rotate: 360 }}\n      transition={{\n        duration: 2.4,\n        ease: EASE_IN_OUT,\n        repeat: Number.POSITIVE_INFINITY,\n      }}\n      className=\"grid size-3.5 grid-cols-2 place-items-center gap-0.5\"\n    >\n      <span className=\"size-1 rounded-[1px] bg-current\" />\n      <span className=\"size-1 rounded-[1px] bg-current opacity-55\" />\n      <span className=\"size-1 rounded-[1px] bg-current opacity-55\" />\n      <span className=\"size-1 rounded-[1px] bg-current\" />\n    </motion.span>\n  );\n}\n\nfunction DitherField({\n  interactive,\n  reduce,\n  status,\n}: {\n  interactive: boolean;\n  reduce: boolean;\n  status: ImageGenerationStatus;\n}) {\n  const canHover = useHoverCapable();\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    const context = canvas?.getContext(\"2d\");\n    if (!canvas || !context) return;\n\n    let frame = 0;\n    let width = 0;\n    let height = 0;\n    let dotColor = \"currentColor\";\n    const pointer = {\n      x: 0,\n      y: 0,\n      targetX: 0,\n      targetY: 0,\n      inside: false,\n    };\n    const pointerEnabled = interactive && canHover && !reduce;\n\n    const resize = () => {\n      const rect = canvas.getBoundingClientRect();\n      width = rect.width || canvas.clientWidth || 208;\n      height = rect.height || canvas.clientHeight || 208;\n      const dpr = Math.min(window.devicePixelRatio || 1, 2);\n\n      canvas.width = Math.round(width * dpr);\n      canvas.height = Math.round(height * dpr);\n      context.setTransform(dpr, 0, 0, dpr, 0, 0);\n      dotColor = window.getComputedStyle(canvas).color;\n      pointer.x = width / 2;\n      pointer.y = height / 2;\n      pointer.targetX = pointer.x;\n      pointer.targetY = pointer.y;\n      // Sizing the canvas clears it, and reduced motion has no frame loop to repaint.\n      if (reduce) draw(0);\n    };\n\n    const draw = (time: number) => {\n      context.clearRect(0, 0, width, height);\n\n      if (!pointer.inside) {\n        pointer.targetX =\n          width / 2 + (reduce ? 0 : Math.sin(time / 1700) * width * 0.12);\n        pointer.targetY =\n          height / 2 + (reduce ? 0 : Math.cos(time / 2100) * height * 0.1);\n      }\n\n      const follow = reduce ? 1 : pointer.inside ? 0.16 : 0.045;\n      pointer.x += (pointer.targetX - pointer.x) * follow;\n      pointer.y += (pointer.targetY - pointer.y) * follow;\n\n      const radius = Math.min(width, height) * 0.38;\n      const columns = Math.ceil(width / DOT_GAP) + 1;\n      const rows = Math.ceil(height / DOT_GAP) + 1;\n      const offsetX = (width - (columns - 1) * DOT_GAP) / 2;\n      const offsetY = (height - (rows - 1) * DOT_GAP) / 2;\n\n      context.fillStyle = dotColor;\n\n      for (let row = 0; row < rows; row += 1) {\n        for (let column = 0; column < columns; column += 1) {\n          const anchorX = offsetX + column * DOT_GAP;\n          const anchorY = offsetY + row * DOT_GAP;\n          const deltaX = anchorX - pointer.x;\n          const deltaY = anchorY - pointer.y;\n          const distance = Math.hypot(deltaX, deltaY);\n          const proximity = Math.max(0, 1 - distance / radius);\n          const influence = proximity * proximity * (3 - 2 * proximity);\n          const displacement = influence * influence * 9;\n          const directionX = distance > 0 ? deltaX / distance : 0;\n          const directionY = distance > 0 ? deltaY / distance : 0;\n          const x = anchorX + directionX * displacement;\n          const y = anchorY + directionY * displacement;\n          const dotRadius = 0.65 + influence * 0.85;\n\n          context.globalAlpha = 0.17 + influence * 0.72;\n          context.beginPath();\n          context.arc(x, y, dotRadius, 0, TWO_PI);\n          context.fill();\n        }\n      }\n\n      context.globalAlpha = 1;\n      if (!reduce) frame = window.requestAnimationFrame(draw);\n    };\n\n    const handlePointerMove = (event: PointerEvent) => {\n      if (!pointerEnabled) return;\n      const rect = canvas.getBoundingClientRect();\n      pointer.inside = true;\n      pointer.targetX = event.clientX - rect.left;\n      pointer.targetY = event.clientY - rect.top;\n    };\n\n    const handlePointerLeave = () => {\n      pointer.inside = false;\n    };\n\n    const resizeObserver =\n      typeof ResizeObserver === \"undefined\"\n        ? null\n        : new ResizeObserver(resize);\n\n    resize();\n    resizeObserver?.observe(canvas);\n    canvas.addEventListener(\"pointermove\", handlePointerMove, { passive: true });\n    canvas.addEventListener(\"pointerleave\", handlePointerLeave);\n    draw(0);\n\n    return () => {\n      if (frame) window.cancelAnimationFrame(frame);\n      resizeObserver?.disconnect();\n      canvas.removeEventListener(\"pointermove\", handlePointerMove);\n      canvas.removeEventListener(\"pointerleave\", handlePointerLeave);\n    };\n  }, [canHover, interactive, reduce]);\n\n  return (\n    <motion.div\n      aria-hidden=\"true\"\n      initial={false}\n      animate={{ opacity: OVERLAY_OPACITY[status] }}\n      transition={{ duration: reduce ? 0 : 0.4, ease: EASE_OUT }}\n      className=\"absolute inset-0 overflow-hidden bg-muted\"\n    >\n      <canvas\n        ref={canvasRef}\n        className=\"absolute inset-0 size-full text-foreground\"\n      />\n    </motion.div>\n  );\n}\n\nexport function ImageGeneration({\n  children,\n  status = \"generating\",\n  label,\n  prompt,\n  resolution = \"1024 × 1024\",\n  aspectRatio = \"1 / 1\",\n  size = \"compact\",\n  interactive = true,\n  statusText,\n  showStatus = true,\n  onRetry,\n  labels,\n  className,\n  mediaClassName,\n  statusClassName,\n}: ImageGenerationProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"imageGeneration\", imageGenerationMessages, labels);\n  const active =\n    status === \"queued\" || status === \"generating\" || status === \"refining\";\n  const mediaState = MEDIA_STATE[status];\n  const resolvedStatusText = statusText ?? t(status);\n  const resolvedLabel =\n    label ??\n    (prompt\n      ? t(\"labelWithPrompt\", { status: resolvedStatusText, prompt })\n      : resolvedStatusText);\n\n  return (\n    <div\n      data-slot=\"image-generation\"\n      data-state={status}\n      aria-busy={active}\n      className={cn(\"w-full\", className)}\n    >\n      <div\n        className={cn(\n          \"w-full\",\n          size === \"compact\" && \"mx-auto max-w-52\",\n        )}\n      >\n        <div\n          role=\"img\"\n          aria-label={resolvedLabel}\n          style={{ aspectRatio }}\n          className=\"relative isolate w-full overflow-hidden rounded-2xl bg-muted\"\n        >\n          <motion.div\n            aria-hidden={children ? undefined : true}\n            initial={false}\n            animate={\n              reduce\n                ? { opacity: mediaState.opacity }\n                : {\n                    filter: mediaState.filter,\n                    opacity: mediaState.opacity,\n                    scale: mediaState.scale,\n                  }\n            }\n            transition={\n              reduce ? { duration: 0 } : { duration: 0.4, ease: EASE_OUT }\n            }\n            className={cn(\n              \"absolute inset-0 [&>*]:size-full [&>*]:object-cover [&_img]:size-full [&_img]:object-cover\",\n              mediaClassName,\n            )}\n          >\n            {children}\n          </motion.div>\n\n          <AnimatePresence initial={false}>\n            {active ? (\n              <motion.div\n                key=\"dither-field\"\n                initial={{ opacity: 0 }}\n                animate={{ opacity: 1 }}\n                exit={{ opacity: 0 }}\n                transition={{ duration: reduce ? 0 : 0.25, ease: EASE_OUT }}\n                className=\"absolute inset-0\"\n              >\n                <DitherField\n                  interactive={interactive}\n                  reduce={reduce}\n                  status={status}\n                />\n              </motion.div>\n            ) : null}\n          </AnimatePresence>\n\n          {resolution ? (\n            <span className=\"absolute top-2 right-2 z-10 rounded-full bg-background/75 px-2 py-0.5 font-mono text-[11px] tabular-nums text-muted-foreground\">\n              {resolution}\n            </span>\n          ) : null}\n        </div>\n\n        {showStatus || prompt ? (\n          <div className=\"mt-3 text-left\">\n            {showStatus ? (\n              <div\n                aria-live=\"polite\"\n                className={cn(\n                  \"flex min-h-5 items-center gap-2 text-sm font-medium text-foreground\",\n                  status === \"error\" && \"text-destructive\",\n                  statusClassName,\n                )}\n              >\n                <IconSwap id={active ? \"active\" : status}>\n                  <DitherMark status={status} reduce={reduce} />\n                </IconSwap>\n                <AnimatePresence mode=\"popLayout\" initial={false}>\n                  <motion.span\n                    key={resolvedStatusText}\n                    initial={reduce ? false : { opacity: 0, y: 4 }}\n                    animate={{ opacity: 1, y: 0 }}\n                    exit={reduce ? undefined : { opacity: 0, y: -4 }}\n                    transition={{\n                      duration: reduce ? 0 : 0.15,\n                      ease: EASE_OUT,\n                    }}\n                  >\n                    {resolvedStatusText}\n                  </motion.span>\n                </AnimatePresence>\n              </div>\n            ) : null}\n            {prompt ? (\n              <p className=\"mt-0.5 truncate text-xs text-muted-foreground\">\n                {t(\"quotedPrompt\", { prompt })}\n              </p>\n            ) : null}\n          </div>\n        ) : null}\n\n        {status === \"error\" && onRetry ? (\n          <motion.button\n            type=\"button\"\n            onClick={onRetry}\n            whileTap={reduce ? undefined : { scale: 0.96 }}\n            transition={SPRING_PRESS}\n            className=\"mt-3 inline-flex min-h-10 items-center gap-2 rounded-full px-3 text-sm font-medium text-foreground outline-none transition-colors hover:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring\"\n          >\n            <RotateCcw aria-hidden=\"true\" className=\"size-4\" />\n            {t(\"retry\")}\n          </motion.button>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n"},{"path":"components/agents/loading-states/thinking-shimmer.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport type { ReactNode } from \"react\";\nimport { TextShimmer } from \"@/components/motion/text-shimmer\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\nimport { type LoadingStatesMessages, loadingStatesMessages } from \"./messages\";\n\nexport interface ThinkingShimmerProps {\n  /** Loading message shown to the user. */\n  children?: ReactNode;\n  /** Seconds taken for one shimmer pass. */\n  duration?: number;\n  /** Override any built-in string. */\n  labels?: Partial<LoadingStatesMessages>;\n  /** Classes merged onto the shimmering text. */\n  className?: string;\n}\n\nexport function ThinkingShimmer({\n  children,\n  duration = 1.8,\n  labels,\n  className,\n}: ThinkingShimmerProps) {\n  const t = useMessages(\"loadingStates\", loadingStatesMessages, labels);\n\n  return (\n    <TextShimmer\n      as=\"span\"\n      duration={duration}\n      className={cn(\"font-medium\", className)}\n    >\n      {children ?? t(\"thinking\")}\n    </TextShimmer>\n  );\n}\n"},{"path":"components/agents/message.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport { motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentPropsWithRef,\n  createContext,\n  type ReactNode,\n  useContext,\n} from \"react\";\nimport { MessageSideContext } from \"@/components/agents/message-context\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport {\n  MessageBubble,\n  MessageBubbleCollapsible,\n  MessageBubbleContent,\n  MessageBubbleGroup,\n} from \"@/components/agents/message-bubble\";\nexport type { MessageScrollerProps } from \"@/components/agents/message-scroller\";\nexport { MessageScroller } from \"@/components/agents/message-scroller\";\n\nexport type MessageFrom = \"user\" | \"assistant\";\n\nexport const messageMessages = {\n  user: \"user message\",\n  assistant: \"assistant message\",\n  typing: \"Responding\",\n};\n\nexport type MessageMessages = typeof messageMessages;\n\ninterface MessageContextValue {\n  from: MessageFrom;\n}\n\nconst MessageContext = createContext<MessageContextValue>({\n  from: \"assistant\",\n});\n\nexport interface MessageProps\n  extends Omit<ComponentPropsWithRef<typeof motion.article>, \"children\"> {\n  /** Who sent it; \"user\" rows align to the end, \"assistant\" rows to the start. */\n  from: MessageFrom;\n  /** Plays a trailing-edge pop-up once when this message row mounts. */\n  animateIn?: boolean;\n  children: ReactNode;\n  /** Override any built-in string. */\n  labels?: Partial<MessageMessages>;\n}\n\nexport interface MessageGroupProps extends ComponentPropsWithRef<\"div\"> {\n  /** Gap between messages: 6 px for \"compact\", 16 px for \"default\". Default: \"compact\" */\n  spacing?: \"compact\" | \"default\";\n}\n\nexport interface MessageAvatarProps extends ComponentPropsWithRef<\"div\"> {\n  /** Keep an empty avatar slot so grouped messages remain aligned. */\n  placeholder?: boolean;\n}\n\nexport type MessageContentProps = ComponentPropsWithRef<\"div\">;\nexport type MessageHeaderProps = ComponentPropsWithRef<\"div\">;\nexport type MessageFooterProps = ComponentPropsWithRef<\"div\">;\n\nexport type MessageMarkerProps = ComponentPropsWithRef<\"div\">;\n\nexport interface MessageTypingProps extends ComponentPropsWithRef<\"span\"> {\n  /** Screen reader text for the typing dots. Default: \"Responding\" */\n  label?: string;\n}\n\n// A sent row should rise from the live edge without changing measured layout.\nconst MESSAGE_POP_UP = {\n  type: \"spring\",\n  stiffness: 480,\n  damping: 32,\n  mass: 0.62,\n} as const;\n\nexport function Message({\n  from,\n  animateIn = false,\n  children,\n  className,\n  initial,\n  animate,\n  transition,\n  exit,\n  style,\n  labels,\n  ...props\n}: MessageProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"message\", messageMessages, labels);\n\n  return (\n    <MessageSideContext.Provider value={from === \"user\" ? \"end\" : \"start\"}>\n      <MessageContext.Provider value={{ from }}>\n        <motion.article\n          data-slot=\"message\"\n          data-from={from}\n          aria-label={props[\"aria-label\"] ?? t(from)}\n          initial={\n            initial ??\n            (animateIn && !reduce\n              ? {\n                  opacity: 0,\n                  transform: \"translateY(8px) scale(0.95)\",\n                }\n              : false)\n          }\n          animate={\n            animate ??\n            (animateIn && !reduce\n              ? {\n                  opacity: 1,\n                  transform: \"translateY(0px) scale(1)\",\n                }\n              : { opacity: 1 })\n          }\n          exit={\n            exit ??\n            (reduce\n              ? { opacity: 0 }\n              : {\n                  opacity: 0,\n                  transform: \"translateY(-3px) scale(0.99)\",\n                })\n          }\n          transition={\n            transition ?? (reduce ? { duration: 0.12 } : MESSAGE_POP_UP)\n          }\n          style={{\n            transformOrigin: from === \"user\" ? \"100% 100%\" : \"0% 100%\",\n            ...style,\n          }}\n          className={cn(\n            \"group/message flex w-full items-start gap-2\",\n            from === \"user\" ? \"flex-row-reverse\" : \"flex-row\",\n            className,\n          )}\n          {...props}\n        >\n          {children}\n        </motion.article>\n      </MessageContext.Provider>\n    </MessageSideContext.Provider>\n  );\n}\n\nexport function MessageGroup({\n  spacing = \"compact\",\n  className,\n  ...props\n}: MessageGroupProps) {\n  return (\n    <div\n      data-slot=\"message-group\"\n      className={cn(\n        \"flex w-full flex-col\",\n        spacing === \"compact\" ? \"gap-1.5\" : \"gap-4\",\n        // A message that follows one from the same speaker tightens its\n        // bubble's top corner on that side, so the run reads as one turn.\n        \"[&>[data-from=user]+[data-from=user]_[data-slot=message-bubble-content]]:rounded-se-md\",\n        \"[&>[data-from=assistant]+[data-from=assistant]_[data-slot=message-bubble-content]]:rounded-ss-md\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport function MessageAvatar({\n  placeholder = false,\n  children,\n  className,\n  ...props\n}: MessageAvatarProps) {\n  return (\n    <div\n      data-slot=\"message-avatar\"\n      aria-hidden={placeholder || undefined}\n      className={cn(\n        \"grid size-7 shrink-0 place-items-center overflow-hidden rounded-full bg-muted text-xs font-medium text-muted-foreground [&_img]:size-full [&_img]:object-cover [&_svg]:size-3.5\",\n        placeholder && \"invisible\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </div>\n  );\n}\n\nexport function MessageContent({ className, ...props }: MessageContentProps) {\n  const { from } = useContext(MessageContext);\n\n  return (\n    <div\n      data-slot=\"message-content\"\n      className={cn(\n        \"flex min-w-0 flex-1 flex-col gap-1.5\",\n        from === \"user\" ? \"items-end\" : \"items-start\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport function MessageHeader({ className, ...props }: MessageHeaderProps) {\n  const { from } = useContext(MessageContext);\n\n  return (\n    <div\n      data-slot=\"message-header\"\n      className={cn(\n        // No inset: the label lines up with the edge of the bubble or text\n        // below it, whichever variant is used.\n        \"flex items-center gap-1.5 text-[11px] leading-none text-muted-foreground\",\n        from === \"user\" ? \"justify-end\" : \"justify-start\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport function MessageFooter({ className, ...props }: MessageFooterProps) {\n  const { from } = useContext(MessageContext);\n\n  return (\n    <div\n      data-slot=\"message-footer\"\n      className={cn(\n        \"flex min-h-5 items-center gap-1 text-[11px] text-muted-foreground\",\n        from === \"user\" ? \"justify-end\" : \"justify-start\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport function MessageMarker({ className, ...props }: MessageMarkerProps) {\n  return (\n    <div\n      data-slot=\"message-marker\"\n      className={cn(\n        \"mx-auto flex w-fit max-w-[88%] items-center gap-1.5 rounded-full bg-muted/70 px-2.5 py-1 text-center text-xs text-muted-foreground\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport function MessageTyping({\n  label,\n  className,\n  ...props\n}: MessageTypingProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"message\", messageMessages);\n\n  return (\n    <span\n      data-slot=\"message-typing\"\n      className={cn(\"inline-flex h-5 items-center gap-1\", className)}\n      {...props}\n    >\n      <span className=\"sr-only\">{label ?? t(\"typing\")}</span>\n      {[0, 1, 2].map((index) => (\n        <motion.span\n          key={index}\n          aria-hidden=\"true\"\n          className=\"size-1 rounded-full bg-current\"\n          animate={\n            reduce\n              ? { opacity: 0.45 }\n              : { opacity: [0.28, 0.85, 0.28], y: [0, -2, 0] }\n          }\n          transition={{\n            duration: 1.05,\n            ease: EASE_OUT,\n            repeat: Number.POSITIVE_INFINITY,\n            delay: index * 0.14,\n          }}\n        />\n      ))}\n    </span>\n  );\n}\n"},{"path":"components/agents/message-bubble.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport { ChevronDown } from \"lucide-react\";\nimport {\n  animate,\n  type HTMLMotionProps,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  type ComponentPropsWithRef,\n  cloneElement,\n  createContext,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useCallback,\n  useContext,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { MessageSideContext } from \"@/components/agents/message-context\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { mergeRefs } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\n\nexport type MessageBubbleVariant =\n  | \"solid\"\n  | \"soft\"\n  | \"tint\"\n  | \"outline\"\n  | \"ghost\"\n  | \"danger\";\nexport type MessageBubbleAlign = \"start\" | \"end\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const messageBubbleMessages = {\n  showMore: \"Show more\",\n  showLess: \"Show less\",\n};\n\nexport type MessageBubbleMessages = typeof messageBubbleMessages;\n\ninterface MessageBubbleContextValue {\n  align?: MessageBubbleAlign;\n  animateIn: boolean;\n  variant: MessageBubbleVariant;\n  labels?: Partial<MessageBubbleMessages>;\n}\n\nconst MessageBubbleContext = createContext<MessageBubbleContextValue>({\n  animateIn: true,\n  variant: \"soft\",\n});\n\nexport interface MessageBubbleProps\n  extends Omit<HTMLMotionProps<\"div\">, \"children\"> {\n  /** Fill and border style of the bubble. Default: \"soft\" */\n  variant?: MessageBubbleVariant;\n  /** Defaults to the surrounding Message alignment when omitted. */\n  align?: MessageBubbleAlign;\n  /** Plays the bubble entrance once when this component mounts. */\n  animateIn?: boolean;\n  /** Override any built-in string. */\n  labels?: Partial<MessageBubbleMessages>;\n  children?: ReactNode;\n}\n\nexport interface MessageBubbleContentProps\n  extends ComponentPropsWithRef<\"div\"> {\n  /** Replaces the content element while preserving bubble styling. */\n  render?: ReactElement;\n}\n\nexport interface MessageBubbleGroupProps extends ComponentPropsWithRef<\"div\"> {\n  /** Gap between bubbles. Default: \"compact\" */\n  spacing?: \"compact\" | \"default\";\n}\n\nexport interface MessageBubbleCollapsibleProps\n  extends ComponentPropsWithRef<\"div\"> {\n  /** Whether the full text shows, for controlled use. */\n  open?: boolean;\n  /** Whether the full text shows at first when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new state when the text expands or collapses. */\n  onOpenChange?: (open: boolean) => void;\n  /** Lines shown while collapsed. Default: 4 */\n  collapsedLines?: 2 | 3 | 4 | 5 | 6;\n  /** Text of the expand button. Default: \"Show more\" */\n  moreLabel?: ReactNode;\n  /** Text of the collapse button. Default: \"Show less\" */\n  lessLabel?: ReactNode;\n  /** Classes merged onto the clamped text wrapper. */\n  contentClassName?: string;\n  /** Classes merged onto the show more button. */\n  triggerClassName?: string;\n  children?: ReactNode;\n}\n\nconst BUBBLE_CONTENT_REVEAL = {\n  duration: 0.12,\n  ease: EASE_OUT,\n  delay: 0.04,\n} as const;\n\n// Expanded text wipes in top to bottom, quick enough to read straight on.\nconst REVEAL = { duration: 0.32, ease: EASE_OUT } as const;\n// Clamped text stays solid to here (%), then fades out by the bottom.\nconst CLAMP_SOLID = 68;\n// How soft the moving edge of the wipe is, in % of the text's height.\nconst WIPE_EDGE = 12;\n\n// Sent bubbles should pop into place quickly with one restrained overshoot.\nconst BUBBLE_POP = {\n  type: \"spring\",\n  stiffness: 520,\n  damping: 27,\n  mass: 0.52,\n} as const;\n\nexport function MessageBubble({\n  variant = \"soft\",\n  align,\n  animateIn = false,\n  labels,\n  className,\n  children,\n  initial,\n  animate,\n  exit,\n  transition,\n  layout,\n  ...props\n}: MessageBubbleProps) {\n  const reduce = useReducedMotion() ?? false;\n  const messageSide = useContext(MessageSideContext);\n  const resolvedAlign = align ?? messageSide ?? \"start\";\n\n  return (\n    <MessageBubbleContext.Provider\n      value={{ align: resolvedAlign, animateIn, variant, labels }}\n    >\n      <motion.div\n        data-slot=\"message-bubble\"\n        data-align={resolvedAlign}\n        data-variant={variant}\n        layout={layout}\n        initial={initial ?? false}\n        animate={animate}\n        exit={\n          exit ??\n          (reduce ? { opacity: 0 } : { opacity: 0, y: -3, scale: 0.99 })\n        }\n        transition={transition ?? (reduce ? { duration: 0.12 } : SPRING_LAYOUT)}\n        className={cn(\n          \"group/bubble flex w-full flex-col\",\n          resolvedAlign === \"end\" ? \"items-end\" : \"items-start\",\n          className,\n        )}\n        {...props}\n      >\n        {children}\n      </motion.div>\n    </MessageBubbleContext.Provider>\n  );\n}\n\nfunction bubbleContentClass(\n  variant: MessageBubbleVariant,\n  align: MessageBubbleAlign,\n  interactive: boolean,\n) {\n  return cn(\n    \"relative z-0 min-w-9 max-w-[82%] rounded-2xl px-3.5 py-2.5 text-sm leading-6 text-foreground\",\n    // The corner by the speaker is tighter, so a bubble points at who said it.\n    align === \"end\" ? \"rounded-ee-md\" : \"rounded-es-md\",\n    \"[&_a]:font-medium [&_a]:underline [&_a]:underline-offset-4 [&_code]:rounded [&_code]:bg-background/60 [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.9em] [&_ol]:my-2 [&_ol]:list-decimal [&_ol]:pl-5 [&_p+p]:mt-2 [&_pre]:my-2 [&_pre]:overflow-x-auto [&_pre]:rounded-xl [&_pre]:bg-background/60 [&_pre]:p-3 [&_ul]:my-2 [&_ul]:list-disc [&_ul]:pl-5\",\n    variant === \"solid\" &&\n      \"text-primary-foreground [&_code]:bg-primary-foreground/15 [&_pre]:bg-primary-foreground/15\",\n    variant === \"ghost\" && \"w-full max-w-none rounded-none px-0 py-0\",\n    variant === \"danger\" && \"text-destructive\",\n    interactive &&\n      \"cursor-pointer text-left outline-none transition-[background-color,color,transform] duration-150 hover:brightness-[0.98] focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.99]\",\n  );\n}\n\nfunction bubbleSurfaceClass(\n  variant: MessageBubbleVariant,\n  align: MessageBubbleAlign,\n) {\n  return cn(\n    \"pointer-events-none absolute inset-0 -z-10 rounded-[inherit]\",\n    align === \"end\" ? \"origin-bottom-right\" : \"origin-bottom-left\",\n    variant === \"solid\" && \"bg-primary\",\n    variant === \"soft\" && \"bg-muted\",\n    variant === \"tint\" && \"bg-muted\",\n    variant === \"outline\" && \"border border-border/70 bg-background\",\n    variant === \"danger\" && \"bg-destructive/10\",\n  );\n}\n\nexport function MessageBubbleContent({\n  render,\n  className,\n  children,\n  ref,\n  ...props\n}: MessageBubbleContentProps) {\n  const reduce = useReducedMotion() ?? false;\n  const { align = \"start\", animateIn, variant } =\n    useContext(MessageBubbleContext);\n  const interactive =\n    render?.type === \"button\" || render?.type === \"a\";\n  const classes = cn(\n    bubbleContentClass(variant, align, interactive),\n    className,\n  );\n  const composedChildren = (\n    <>\n      {/* The surface pops in once, then always matches its text: a surface\n          that springs after its content leaves streamed lines and expanded\n          text hanging outside the bubble. */}\n      {variant !== \"ghost\" ? (\n        <motion.span\n          aria-hidden=\"true\"\n          initial={\n            animateIn && !reduce\n              ? {\n                  opacity: 0,\n                  scale: 0.92,\n                }\n              : false\n          }\n          animate={{ opacity: 1, scale: 1 }}\n          transition={\n            reduce\n              ? { duration: 0 }\n              : {\n                  opacity: { duration: 0.12, ease: EASE_OUT },\n                  scale: BUBBLE_POP,\n                }\n          }\n          className={bubbleSurfaceClass(variant, align)}\n        />\n      ) : null}\n      <motion.div\n        initial={animateIn ? { opacity: 0 } : false}\n        animate={{ opacity: 1 }}\n        transition={\n          reduce ? { duration: 0.12, ease: EASE_OUT } : BUBBLE_CONTENT_REVEAL\n        }\n        className=\"relative\"\n      >\n        {children}\n      </motion.div>\n    </>\n  );\n\n  if (render) {\n    const child = render as ReactElement<\n      Record<string, unknown> & { className?: string; ref?: Ref<HTMLElement> }\n    >;\n\n    return cloneElement(child, {\n      ...props,\n      ref: mergeRefs(child.props.ref, ref as Ref<HTMLElement> | undefined),\n      className: cn(classes, child.props.className),\n      children: composedChildren,\n      \"data-slot\": \"message-bubble-content\",\n    });\n  }\n\n  return (\n    <div\n      ref={ref}\n      data-slot=\"message-bubble-content\"\n      className={classes}\n      {...props}\n    >\n      {composedChildren}\n    </div>\n  );\n}\n\nexport function MessageBubbleGroup({\n  spacing = \"compact\",\n  className,\n  ...props\n}: MessageBubbleGroupProps) {\n  return (\n    <div\n      data-slot=\"message-bubble-group\"\n      className={cn(\n        \"flex w-full flex-col\",\n        spacing === \"compact\" ? \"gap-1.5\" : \"gap-3\",\n        // A bubble that follows one from the same speaker tightens its top\n        // corner on that side too, so the run reads as one turn.\n        \"[&>[data-align=end]+[data-align=end]_[data-slot=message-bubble-content]]:rounded-se-md\",\n        \"[&>[data-align=start]+[data-align=start]_[data-slot=message-bubble-content]]:rounded-ss-md\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nconst LINE_CLAMP_CLASS = {\n  2: \"line-clamp-2\",\n  3: \"line-clamp-3\",\n  4: \"line-clamp-4\",\n  5: \"line-clamp-5\",\n  6: \"line-clamp-6\",\n} as const;\n\nexport function MessageBubbleCollapsible({\n  open,\n  defaultOpen = false,\n  onOpenChange,\n  collapsedLines = 4,\n  moreLabel,\n  lessLabel,\n  contentClassName,\n  triggerClassName,\n  className,\n  children,\n  ...props\n}: MessageBubbleCollapsibleProps) {\n  const reduce = useReducedMotion() ?? false;\n  const contentId = useId();\n  const t = useMessages(\n    \"messageBubble\",\n    messageBubbleMessages,\n    useContext(MessageBubbleContext).labels,\n  );\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const currentOpen = open ?? internalOpen;\n  const contentRef = useRef<HTMLDivElement>(null);\n  // Where the clamped text ended, as a share of the full text: the reveal\n  // starts there, so the lines already on screen never blink.\n  const clampedHeight = useRef(0);\n  // The fade mask, from solid (`solid`%) to clear (`clear`%). Clamped, it\n  // softens the last lines; open, it wipes down until the text is all solid.\n  const solid = useMotionValue(currentOpen ? 100 : CLAMP_SOLID);\n  const clear = useMotionValue(currentOpen ? 100 + WIPE_EDGE : 100);\n  const mask = useMotionTemplate`linear-gradient(to bottom, #000 ${solid}%, transparent ${clear}%)`;\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (next) clampedHeight.current = contentRef.current?.offsetHeight ?? 0;\n      if (open === undefined) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [onOpenChange, open],\n  );\n\n  // Opening shows the whole text at once (no height animation) and wipes the\n  // new lines in from the top; closing clamps straight back.\n  useLayoutEffect(() => {\n    if (!currentOpen) {\n      solid.set(CLAMP_SOLID);\n      clear.set(100);\n      return;\n    }\n    const full = contentRef.current?.offsetHeight ?? 0;\n    const start =\n      reduce || !full || !clampedHeight.current\n        ? 100\n        : Math.min(100, (clampedHeight.current / full) * 100 - WIPE_EDGE);\n    solid.set(start);\n    clear.set(start + WIPE_EDGE);\n    if (start >= 100) return;\n    const toSolid = animate(solid, 100, REVEAL);\n    const toClear = animate(clear, 100 + WIPE_EDGE, REVEAL);\n    return () => {\n      toSolid.stop();\n      toClear.stop();\n    };\n  }, [currentOpen, reduce, solid, clear]);\n\n  return (\n    <div\n      data-slot=\"message-bubble-collapsible\"\n      data-state={currentOpen ? \"open\" : \"closed\"}\n      className={cn(\"w-full\", className)}\n      {...props}\n    >\n      <motion.div\n        ref={contentRef}\n        id={contentId}\n        style={{ maskImage: mask, WebkitMaskImage: mask }}\n        className={cn(\n          !currentOpen && LINE_CLAMP_CLASS[collapsedLines],\n          contentClassName,\n        )}\n      >\n        {children}\n      </motion.div>\n      <button\n        type=\"button\"\n        aria-expanded={currentOpen}\n        aria-controls={contentId}\n        onClick={() => setOpen(!currentOpen)}\n        className={cn(\n          \"mt-2 inline-flex h-7 items-center gap-1 rounded-full px-2 text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n          triggerClassName,\n        )}\n      >\n        <span>{currentOpen\n            ? (lessLabel ?? t(\"showLess\"))\n            : (moreLabel ?? t(\"showMore\"))}</span>\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: currentOpen ? 180 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n        >\n          <ChevronDown className=\"size-3.5\" />\n        </motion.span>\n      </button>\n    </div>\n  );\n}\n"},{"path":"components/agents/message-scroller.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport { ArrowDown } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentPropsWithRef,\n  type Ref,\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport {\n  PreviewRail,\n  type PreviewRailItem,\n} from \"@/components/motion/preview-rail\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\n// The jump button rises in from the bottom edge and drops back out, faster.\nconst JUMP_IN = { duration: 0.2, ease: EASE_OUT } as const;\nconst JUMP_OUT = { duration: 0.14, ease: EASE_OUT } as const;\n\nexport const messageScrollerMessages = {\n  label: \"Conversation\",\n  jumpToLatest: \"Jump to latest\",\n  navigationLabel: \"Message navigation\",\n  preview: \"Message\",\n  goToUser: \"Go to user message {index} of {total}\",\n  goToAssistant: \"Go to assistant message {index} of {total}\",\n  goToMessage: \"Go to conversation message {index} of {total}\",\n};\n\nexport type MessageScrollerMessages = typeof messageScrollerMessages;\n\nconst PREVIEW_TITLE_LENGTH = 56;\nconst PREVIEW_DESCRIPTION_LENGTH = 88;\n\nfunction truncateMessageText(text: string, limit: number) {\n  if (text.length <= limit) return text;\n  const excerpt = text.slice(0, limit);\n  const boundary = excerpt.lastIndexOf(\" \");\n  return `${excerpt.slice(0, boundary > limit * 0.65 ? boundary : limit).trim()}…`;\n}\n\nfunction getMessageText(message: HTMLElement) {\n  const surface =\n    message.querySelector<HTMLElement>('[data-slot=\"message-bubble-content\"]') ??\n    message.querySelector<HTMLElement>('[data-slot=\"message-content\"]') ??\n    message;\n  return (surface.textContent ?? \"\").replace(/\\s+/g, \" \").trim();\n}\n\nfunction getMessagePreview(\n  message: HTMLElement,\n  emptyLabel: string,\n  assistantResponse?: HTMLElement,\n) {\n  const text = getMessageText(message);\n  if (!text) {\n    return { label: emptyLabel, description: undefined };\n  }\n\n  if (text.length <= PREVIEW_TITLE_LENGTH) {\n    const responseText = assistantResponse\n      ? getMessageText(assistantResponse)\n      : \"\";\n    return {\n      label: text,\n      description: responseText\n        ? truncateMessageText(responseText, PREVIEW_DESCRIPTION_LENGTH)\n        : undefined,\n    };\n  }\n\n  const titleExcerpt = text.slice(0, PREVIEW_TITLE_LENGTH);\n  const titleBoundary = titleExcerpt.lastIndexOf(\" \");\n  const titleEnd =\n    titleBoundary > PREVIEW_TITLE_LENGTH * 0.65\n      ? titleBoundary\n      : PREVIEW_TITLE_LENGTH;\n  const label = `${text.slice(0, titleEnd).trim()}…`;\n  const responseText = assistantResponse\n    ? getMessageText(assistantResponse)\n    : text.slice(titleEnd).trim();\n  return {\n    label,\n    description: responseText\n      ? truncateMessageText(responseText, PREVIEW_DESCRIPTION_LENGTH)\n      : undefined,\n  };\n}\n\nexport interface MessageScrollerProps extends ComponentPropsWithRef<\"div\"> {\n  /** Keep streamed output pinned while the reader remains near the end. */\n  followOutput?: boolean;\n  /** Distance from the end that still counts as following the output. */\n  followThreshold?: number;\n  /** Smoothly follow growing content. */\n  smooth?: boolean;\n  /** Reports when the reader leaves or returns to the live edge. */\n  onFollowChange?: (following: boolean) => void;\n  /** Accessible label for the scrollable transcript. */\n  label?: string;\n  /** Marks the transcript as waiting for more streamed content. */\n  busy?: boolean;\n  /** Adds a compact rail for navigating between rendered Message rows. */\n  navigation?: \"rail\";\n  /** Shows a button back to the latest message once the reader scrolls up. Default true. */\n  jumpButton?: boolean;\n  /** Accessible label for the optional message navigation rail. */\n  navigationLabel?: string;\n  /** Classes merged onto the scrolling viewport. */\n  viewportClassName?: string;\n  /** Classes merged onto the log element that wraps the messages. */\n  contentClassName?: string;\n  /** Classes merged onto the navigation rail, used with `navigation=\"rail\"`. */\n  railClassName?: string;\n  /** Ref to the scrolling viewport element. */\n  viewportRef?: Ref<HTMLElement>;\n  /** Extra props for the scrolling viewport. Its event handlers still run. */\n  viewportProps?: Omit<\n    ComponentPropsWithRef<\"section\">,\n    \"children\" | \"className\" | \"ref\"\n  >;\n  /** Extra props for the log element that wraps the messages. */\n  contentProps?: Omit<\n    ComponentPropsWithRef<\"div\">,\n    \"children\" | \"className\" | \"ref\"\n  >;\n  /** Override any built-in string. */\n  labels?: Partial<MessageScrollerMessages>;\n}\n\nexport function MessageScroller({\n  followOutput = true,\n  followThreshold = 56,\n  smooth = true,\n  onFollowChange,\n  label,\n  busy,\n  navigation,\n  jumpButton = true,\n  navigationLabel,\n  viewportClassName,\n  contentClassName,\n  railClassName,\n  viewportRef: externalViewportRef,\n  viewportProps,\n  contentProps,\n  className,\n  children,\n  labels,\n  ...props\n}: MessageScrollerProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"messageScroller\", messageScrollerMessages, labels);\n  // Read by the stable rail sync so inline `labels` don't rebuild it each render.\n  const tRef = useRef(t);\n  const viewportRef = useRef<HTMLElement>(null);\n  const contentRef = useRef<HTMLDivElement>(null);\n  const followingRef = useRef(followOutput);\n  const programmaticScrollRef = useRef(false);\n  const scrollTimerRef = useRef<number | undefined>(undefined);\n  const frameRef = useRef<number | undefined>(undefined);\n  const railFrameRef = useRef<number | undefined>(undefined);\n  const railIdRef = useRef(new WeakMap<HTMLElement, string>());\n  const railIdCounterRef = useRef(0);\n  const railTargetsRef = useRef(new Map<string, HTMLElement>());\n  const [railItems, setRailItems] = useState<PreviewRailItem[]>([]);\n  const [activeRailId, setActiveRailId] = useState(\"\");\n  const [railOverflowing, setRailOverflowing] = useState(false);\n  // Mirrors followingRef for rendering: the jump button shows while false.\n  const [atLiveEdge, setAtLiveEdge] = useState(true);\n  const {\n    onScroll: onViewportScroll,\n    onWheel: onViewportWheel,\n    onTouchStart: onViewportTouchStart,\n    onKeyDown: onViewportKeyDown,\n    ...restViewportProps\n  } = viewportProps ?? {};\n\n  const setViewportRef = useCallback(\n    (node: HTMLElement | null) => {\n      viewportRef.current = node;\n      if (typeof externalViewportRef === \"function\") {\n        externalViewportRef(node);\n      } else if (externalViewportRef) {\n        externalViewportRef.current = node;\n      }\n    },\n    [externalViewportRef],\n  );\n\n  const setFollowing = useCallback(\n    (next: boolean) => {\n      if (followingRef.current === next) return;\n      followingRef.current = next;\n      setAtLiveEdge(next);\n      onFollowChange?.(next);\n    },\n    [onFollowChange],\n  );\n\n  const updateActiveRailItem = useCallback(() => {\n    if (navigation !== \"rail\") return;\n    const viewport = viewportRef.current;\n    const targets = [...railTargetsRef.current.entries()];\n    if (!viewport || targets.length === 0) return;\n\n    const viewportRect = viewport.getBoundingClientRect();\n    if (viewport.scrollTop <= followThreshold) {\n      const firstId = targets[0]?.[0] ?? \"\";\n      setActiveRailId((current) => (current === firstId ? current : firstId));\n      return;\n    }\n\n    const distanceFromEnd =\n      viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;\n    if (distanceFromEnd <= followThreshold) {\n      const lastId = targets.at(-1)?.[0] ?? \"\";\n      setActiveRailId((current) => (current === lastId ? current : lastId));\n      return;\n    }\n\n    const viewportCenter = viewportRect.top + viewportRect.height / 2;\n    let nearestId = targets[0]?.[0] ?? \"\";\n    let nearestDistance = Number.POSITIVE_INFINITY;\n\n    for (const [id, element] of targets) {\n      const rect = element.getBoundingClientRect();\n      const messageCenter = rect.top + rect.height / 2;\n      const distance = Math.abs(messageCenter - viewportCenter);\n      if (distance < nearestDistance) {\n        nearestDistance = distance;\n        nearestId = id;\n      }\n    }\n\n    setActiveRailId((current) =>\n      current === nearestId ? current : nearestId,\n    );\n  }, [followThreshold, navigation]);\n\n  const syncRailItems = useCallback(() => {\n    if (navigation !== \"rail\") return;\n    const content = contentRef.current;\n    const viewport = viewportRef.current;\n    if (!content || !viewport) return;\n\n    const messages = Array.from(\n      content.querySelectorAll<HTMLElement>('[data-slot=\"message\"]'),\n    );\n    const targets = new Map<string, HTMLElement>();\n    const nextItems = messages.map((message, index) => {\n      let id = railIdRef.current.get(message);\n      if (!id) {\n        railIdCounterRef.current += 1;\n        id = `message-rail-${railIdCounterRef.current}`;\n        railIdRef.current.set(message, id);\n      }\n      targets.set(id, message);\n      const sender = message.dataset.from ?? \"conversation\";\n      const assistantResponse =\n        sender === \"user\"\n          ? messages\n              .slice(index + 1)\n              .find((candidate) => candidate.dataset.from === \"assistant\")\n          : undefined;\n      const preview = getMessagePreview(\n        message,\n        tRef.current(\"preview\"),\n        assistantResponse,\n      );\n\n      return {\n        id,\n        label: preview.label,\n        description: preview.description,\n        ariaLabel: tRef.current(\n          sender === \"user\"\n            ? \"goToUser\"\n            : sender === \"assistant\"\n              ? \"goToAssistant\"\n              : \"goToMessage\",\n          { index: index + 1, total: messages.length },\n        ),\n      };\n    });\n\n    railTargetsRef.current = targets;\n    setRailItems((current) => {\n      const unchanged =\n        current.length === nextItems.length &&\n        current.every(\n          (item, index) =>\n            item.id === nextItems[index]?.id &&\n            item.label === nextItems[index]?.label &&\n            item.description === nextItems[index]?.description &&\n            item.ariaLabel === nextItems[index]?.ariaLabel,\n        );\n      return unchanged ? current : nextItems;\n    });\n    setRailOverflowing(\n      viewport.scrollHeight > viewport.clientHeight + 1 && messages.length > 1,\n    );\n  }, [navigation]);\n\n  const scheduleRailSync = useCallback(() => {\n    if (navigation !== \"rail\") return;\n    if (railFrameRef.current) cancelAnimationFrame(railFrameRef.current);\n    railFrameRef.current = requestAnimationFrame(() => {\n      syncRailItems();\n      updateActiveRailItem();\n    });\n  }, [navigation, syncRailItems, updateActiveRailItem]);\n\n  useLayoutEffect(() => {\n    tRef.current = t;\n    scheduleRailSync();\n  }, [t, scheduleRailSync]);\n\n  // A scroll this component started must not read as the reader scrolling\n  // away. A smooth scroll can outlast any fixed guess, so the flag clears on\n  // `scrollend`; the timer is the fallback where that event doesn't exist.\n  const releaseAfterScroll = useCallback(\n    (viewport: HTMLElement, behavior: ScrollBehavior) => {\n      if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);\n      const release = () => {\n        programmaticScrollRef.current = false;\n        viewport.removeEventListener(\"scrollend\", release);\n        if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);\n      };\n      if (behavior !== \"smooth\") {\n        scrollTimerRef.current = window.setTimeout(release, 0);\n        return;\n      }\n      const hasScrollEnd = \"onscrollend\" in window;\n      if (hasScrollEnd) viewport.addEventListener(\"scrollend\", release);\n      scrollTimerRef.current = window.setTimeout(release, hasScrollEnd ? 1200 : 320);\n    },\n    [],\n  );\n\n  const scrollToEnd = useCallback(\n    (behavior: ScrollBehavior) => {\n      const viewport = viewportRef.current;\n      if (!viewport) return;\n\n      programmaticScrollRef.current = true;\n      if (typeof viewport.scrollTo === \"function\") {\n        viewport.scrollTo({ top: viewport.scrollHeight, behavior });\n      } else {\n        viewport.scrollTop = viewport.scrollHeight;\n      }\n      releaseAfterScroll(viewport, behavior);\n    },\n    [releaseAfterScroll],\n  );\n\n  const handleScroll = useCallback(() => {\n    const viewport = viewportRef.current;\n    if (!viewport || programmaticScrollRef.current) return;\n\n    const distance =\n      viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;\n    setFollowing(distance <= followThreshold);\n    updateActiveRailItem();\n  }, [followThreshold, setFollowing, updateActiveRailItem]);\n\n  const leaveLiveEdge = useCallback(() => {\n    programmaticScrollRef.current = false;\n  }, []);\n\n  useLayoutEffect(() => {\n    followingRef.current = followOutput;\n    if (!followOutput) return;\n\n    frameRef.current = requestAnimationFrame(() => scrollToEnd(\"auto\"));\n    return () => {\n      if (frameRef.current) cancelAnimationFrame(frameRef.current);\n    };\n  }, [followOutput, scrollToEnd]);\n\n  useEffect(() => {\n    const content = contentRef.current;\n    if (!content || typeof ResizeObserver === \"undefined\") return;\n\n    const observer = new ResizeObserver(() => {\n      scheduleRailSync();\n      if (!followOutput || !followingRef.current) return;\n      scrollToEnd(reduce || !smooth ? \"auto\" : \"smooth\");\n    });\n    observer.observe(content);\n\n    return () => observer.disconnect();\n  }, [followOutput, reduce, scheduleRailSync, scrollToEnd, smooth]);\n\n  useEffect(() => {\n    if (navigation !== \"rail\") {\n      railTargetsRef.current.clear();\n      setRailItems([]);\n      setRailOverflowing(false);\n      return;\n    }\n\n    const content = contentRef.current;\n    const viewport = viewportRef.current;\n    if (!content || !viewport) return;\n\n    scheduleRailSync();\n    const mutationObserver =\n      typeof MutationObserver === \"undefined\"\n        ? null\n        : new MutationObserver(scheduleRailSync);\n    mutationObserver?.observe(content, {\n      childList: true,\n      characterData: true,\n      subtree: true,\n    });\n\n    const resizeObserver =\n      typeof ResizeObserver === \"undefined\"\n        ? null\n        : new ResizeObserver(scheduleRailSync);\n    resizeObserver?.observe(content);\n    resizeObserver?.observe(viewport);\n\n    return () => {\n      mutationObserver?.disconnect();\n      resizeObserver?.disconnect();\n    };\n  }, [navigation, scheduleRailSync]);\n\n  useEffect(\n    () => () => {\n      if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);\n      if (frameRef.current) cancelAnimationFrame(frameRef.current);\n      if (railFrameRef.current) cancelAnimationFrame(railFrameRef.current);\n    },\n    [],\n  );\n\n  const scrollToRailItem = useCallback(\n    (item: PreviewRailItem) => {\n      const viewport = viewportRef.current;\n      const target = railTargetsRef.current.get(item.id);\n      if (!viewport || !target) return;\n\n      const lastItem = railItems.at(-1)?.id === item.id;\n      setActiveRailId(item.id);\n      if (lastItem) {\n        setFollowing(true);\n        scrollToEnd(reduce || !smooth ? \"auto\" : \"smooth\");\n        return;\n      }\n\n      setFollowing(false);\n      programmaticScrollRef.current = true;\n      const viewportRect = viewport.getBoundingClientRect();\n      const targetRect = target.getBoundingClientRect();\n      const top =\n        viewport.scrollTop +\n        targetRect.top -\n        viewportRect.top -\n        (viewport.clientHeight - targetRect.height) / 2;\n      const behavior = reduce || !smooth ? \"auto\" : \"smooth\";\n\n      if (typeof viewport.scrollTo === \"function\") {\n        viewport.scrollTo({ top, behavior });\n      } else {\n        viewport.scrollTop = top;\n      }\n      releaseAfterScroll(viewport, behavior);\n    },\n    [railItems, reduce, releaseAfterScroll, scrollToEnd, setFollowing, smooth],\n  );\n\n  const viewport = (\n    <section\n      ref={setViewportRef}\n      aria-label={label ?? t(\"label\")}\n      {...restViewportProps}\n      onScroll={(event) => {\n        handleScroll();\n        onViewportScroll?.(event);\n      }}\n      onWheel={(event) => {\n        leaveLiveEdge();\n        onViewportWheel?.(event);\n      }}\n      onTouchStart={(event) => {\n        leaveLiveEdge();\n        onViewportTouchStart?.(event);\n      }}\n      onKeyDown={(event) => {\n        if ([\"ArrowUp\", \"PageUp\", \"Home\"].includes(event.key)) {\n          leaveLiveEdge();\n        }\n        onViewportKeyDown?.(event);\n      }}\n      className={cn(\n        \"h-full overflow-y-auto overscroll-contain outline-none [overflow-anchor:none] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring\",\n        navigation === \"rail\"\n          ? \"[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n          : \"[scrollbar-gutter:stable]\",\n        viewportClassName,\n        navigation === \"rail\" && railOverflowing && \"pr-10\",\n      )}\n    >\n      <div\n        ref={contentRef}\n        role=\"log\"\n        aria-live=\"polite\"\n        aria-relevant=\"additions text\"\n        aria-busy={busy}\n        className={contentClassName}\n        {...contentProps}\n      >\n        {children}\n      </div>\n    </section>\n  );\n\n  const jumpToLatest = () => {\n    setFollowing(true);\n    scrollToEnd(reduce || !smooth ? \"auto\" : \"smooth\");\n  };\n  const showJump = jumpButton && followOutput && !atLiveEdge;\n\n  return (\n    <div\n      data-slot=\"message-scroller\"\n      className={cn(\"relative min-h-0\", className)}\n      {...props}\n    >\n      {navigation === \"rail\" ? (\n        <PreviewRail\n          items={railOverflowing ? railItems : []}\n          label={navigationLabel ?? t(\"navigationLabel\")}\n          activeId={activeRailId}\n          onItemSelect={scrollToRailItem}\n          previewSide=\"before\"\n          highlightActive\n          itemSize={14}\n          className=\"h-full min-h-0 overflow-hidden\"\n          previewContainerClassName=\"right-8 left-3\"\n          previewClassName=\"mr-1 w-64 max-w-full [&_[data-slot=preview-rail-card]]:h-20 [&_[data-slot=preview-rail-card]]:overflow-hidden [&_[data-slot=preview-rail-card]]:p-3 [&_[data-slot=preview-rail-title]]:line-clamp-1 [&_[data-slot=preview-rail-title]]:text-xs [&_[data-slot=preview-rail-title]]:leading-4 [&_[data-slot=preview-rail-description]]:line-clamp-2 [&_[data-slot=preview-rail-description]]:text-xs [&_[data-slot=preview-rail-description]]:leading-4\"\n          railClassName={cn(\n            \"absolute inset-y-3 right-1 w-7 content-center py-1 [&_[data-slot=preview-rail-item]]:w-7 [&_[data-slot=preview-rail-item]]:justify-end [&_[data-slot=preview-rail-tick]]:h-px [&_[data-slot=preview-rail-tick]]:w-4 [&_[data-slot=preview-rail-tick]]:origin-right\",\n            railOverflowing\n              ? \"pointer-events-auto opacity-100\"\n              : \"pointer-events-none opacity-0\",\n            railClassName,\n          )}\n        >\n          {viewport}\n        </PreviewRail>\n      ) : (\n        viewport\n      )}\n      {/* Back to the live edge, once the reader has scrolled away from it. */}\n      <AnimatePresence>\n        {showJump ? (\n          <motion.div\n            key=\"jump\"\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 8, scale: 0.95 }}\n            animate={{ opacity: 1, y: 0, scale: 1, transition: JUMP_IN }}\n            exit={reduce ? { opacity: 0, transition: JUMP_OUT } : { opacity: 0, y: 8, scale: 0.95, transition: JUMP_OUT }}\n            className=\"pointer-events-none absolute inset-x-0 bottom-3 flex justify-center\"\n          >\n            <Tooltip content={t(\"jumpToLatest\")} side=\"top\">\n              <button\n                type=\"button\"\n                onClick={jumpToLatest}\n                aria-label={t(\"jumpToLatest\")}\n                // Card fill and the strong border: it floats over messages\n                // that share the background, and must read as a control.\n                className=\"pointer-events-auto inline-flex size-8 items-center justify-center rounded-full border border-(--color-border-strong) bg-card text-muted-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)] outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.97]\"\n              >\n                <ArrowDown aria-hidden=\"true\" className=\"size-4\" />\n              </button>\n            </Tooltip>\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n    </div>\n  );\n}\n"},{"path":"components/agents/prompt-input.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport { ArrowUp, ChevronDown, Plus, Square } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type FormEvent,\n  type KeyboardEvent,\n  type ReactNode,\n  type TextareaHTMLAttributes,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { ClipResizeFrame } from \"@/components/agents/clip-resize-frame\";\nimport { Button } from \"@/components/motion/button\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuRadioGroup,\n  DropdownMenuRadioItem,\n  DropdownMenuTrigger,\n} from \"@/components/motion/dropdown-menu\";\nimport { MENU_ITEM_CLASS, MenuItemHighlight } from \"@/components/motion/menu/menu-item-highlight\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useRowCursor } from \"@/lib/hooks/use-row-cursor\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\n/** One identity for the default, so the filtered list stays stable. */\nconst NO_COMMANDS: PromptCommand[] = [];\n\n// The slash list rises in and drops away faster; rows fade in and out as the\n// filter changes, and the rest slide into place.\nconst LIST_IN = { duration: 0.18, ease: EASE_OUT } as const;\nconst LIST_OUT = { duration: 0.12, ease: EASE_OUT } as const;\nconst ROW_OUT = { duration: 0.1, ease: EASE_OUT } as const;\nconst ROW_MOVE = { layout: SPRING_LAYOUT, opacity: { duration: 0.16, ease: EASE_OUT } } as const;\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const promptInputMessages = {\n  placeholder: \"Ask the agent to do something…\",\n  label: \"Prompt\",\n  addToPrompt: \"Add to prompt\",\n  chooseModel: \"Choose model\",\n  send: \"Send prompt\",\n  stop: \"Stop generating\",\n  commands: \"Commands\",\n};\n\nexport type PromptInputMessages = typeof promptInputMessages;\n\nexport interface PromptModel {\n  /** Unique key, passed to `onModelChange` and `onSubmit`. */\n  value: string;\n  /** Name shown in the model menu and on its trigger when selected. */\n  label: ReactNode;\n  /** Icon before the label in the menu and on the trigger. */\n  icon?: ReactNode;\n  /** Stops the model from being picked. */\n  disabled?: boolean;\n}\n\nexport interface PromptAction {\n  /** Unique key, passed to `onAction` when the item is chosen. */\n  value: string;\n  /** Item text in the add menu. */\n  label: ReactNode;\n  /** Muted line under the label. */\n  description?: ReactNode;\n  /** Icon before the label. */\n  icon?: ReactNode;\n  /** Stops the item from being chosen. */\n  disabled?: boolean;\n}\n\nexport interface PromptCommand {\n  /** What follows the slash: typing `/value` finds it, and picking it writes `/value ` into the prompt. */\n  value: string;\n  /** Name shown in the command list. Also matched while typing. */\n  label: string;\n  /** Muted line beside the label. */\n  description?: ReactNode;\n  /** Icon before the label. */\n  icon?: ReactNode;\n}\n\nexport interface PromptInputProps extends Omit<\n  TextareaHTMLAttributes<HTMLTextAreaElement>,\n  \"value\" | \"defaultValue\" | \"onChange\" | \"onSubmit\" | \"children\"\n> {\n  /** The prompt text, for controlled use. */\n  value?: string;\n  /** The initial prompt text when uncontrolled. Default: \"\" */\n  defaultValue?: string;\n  /** Called with the new text on every edit. */\n  onValueChange?: (value: string) => void;\n  /** Models listed in the model menu. Hidden when empty. */\n  models?: PromptModel[];\n  /** The selected model's value, for controlled use. */\n  model?: string;\n  /** The initial model when uncontrolled. Default: the first model */\n  defaultModel?: string;\n  /** Called with the model's value when a model is picked. */\n  onModelChange?: (model: string) => void;\n  /** Items in the add menu next to the input. Hidden when empty. */\n  actions?: PromptAction[];\n  /** Called with the action's value when an add menu item is chosen. */\n  onAction?: (action: string) => void;\n  /** Slash commands. Typing `/` at the start of a word lists them above the input. Hidden when empty. */\n  commands?: PromptCommand[];\n  /** Called with the command's value when a slash command is picked. */\n  onCommand?: (command: string) => void;\n  /** Called with the trimmed prompt and selected model on Enter or the send button. */\n  onSubmit?: (value: string, model?: string) => void | Promise<void>;\n  /** Swaps send for a stop button and blocks new prompts. Default: false */\n  loading?: boolean;\n  /** Called when the stop button is pressed while loading. */\n  onStop?: () => void;\n  /** Height of the empty input, in text rows. Default: 2 */\n  minRows?: number;\n  /** Rows the input grows to before it scrolls. Default: 8 */\n  maxRows?: number;\n  /** Extra controls placed between the add menu and the model menu. */\n  leadingAction?: ReactNode;\n  /** Override any built-in string. */\n  labels?: Partial<PromptInputMessages>;\n  /** Classes merged onto the form element. */\n  className?: string;\n}\n\nexport function PromptInput({\n  value,\n  defaultValue = \"\",\n  onValueChange,\n  models = [],\n  model,\n  defaultModel,\n  onModelChange,\n  actions = [],\n  onAction,\n  commands = NO_COMMANDS,\n  onCommand,\n  onSubmit,\n  loading = false,\n  onStop,\n  minRows = 2,\n  maxRows = 8,\n  leadingAction,\n  labels,\n  className,\n  disabled,\n  placeholder,\n  \"aria-label\": ariaLabel,\n  onKeyDown,\n  ...textareaProps\n}: PromptInputProps) {\n  const t = useMessages(\"promptInput\", promptInputMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n  const measurementRef = useRef<HTMLDivElement>(null);\n  const [internalValue, setInternalValue] = useState(defaultValue);\n  const [internalModel, setInternalModel] = useState(\n    defaultModel ?? models[0]?.value,\n  );\n  const [actionsOpen, setActionsOpen] = useState(false);\n  const [modelsOpen, setModelsOpen] = useState(false);\n  const currentValue = value ?? internalValue;\n  const currentModelValue = model ?? internalModel;\n  const currentModel = models.find(\n    (option) => option.value === currentModelValue,\n  );\n  const canSubmit = Boolean(currentValue.trim()) && !disabled && !loading;\n\n  // Slash commands: the word before the caret, when it starts with `/`.\n  const [caret, setCaret] = useState(currentValue.length);\n  // Escape closes the list for the slash it was opened by, until another one.\n  const [dismissedAt, setDismissedAt] = useState(-1);\n  const baseId = useId();\n  const slash = commands.length\n    ? /(?:^|\\s)\\/([\\w-]*)$/.exec(currentValue.slice(0, caret))\n    : null;\n  const query = slash ? slash[1].toLowerCase() : \"\";\n  const slashAt = slash ? caret - slash[1].length - 1 : -1;\n  const matches = slash\n    ? commands.filter(\n        (command) =>\n          command.value.toLowerCase().includes(query) ||\n          command.label.toLowerCase().includes(query),\n      )\n    : NO_COMMANDS;\n  const slashOpen = matches.length > 0 && slashAt !== dismissedAt && !disabled;\n  const commandRows = matches.map((command) => ({ id: command.value }));\n  const { activeIndex, moveTo, moveActive } = useRowCursor(commandRows, query);\n  const activeCommand = slashOpen ? matches[activeIndex] : undefined;\n  const listId = `${baseId}-commands`;\n  const optionId = (value: string) => `${baseId}-command-${value}`;\n  // Pointer moves glide the highlight; arrow keys jump it, a spring would\n  // only trail behind fast arrowing.\n  const [glide, setGlide] = useState(false);\n\n  const pickCommand = (command: PromptCommand) => {\n    const inserted = `/${command.value} `;\n    const next =\n      currentValue.slice(0, slashAt) + inserted + currentValue.slice(caret);\n    const nextCaret = slashAt + inserted.length;\n    setValue(next);\n    setCaret(nextCaret);\n    onCommand?.(command.value);\n    requestAnimationFrame(() => {\n      textareaRef.current?.focus({ preventScroll: true });\n      textareaRef.current?.setSelectionRange(nextCaret, nextCaret);\n    });\n  };\n\n  const resizeTextarea = useCallback(() => {\n    const textarea = textareaRef.current;\n    const measurement = measurementRef.current;\n    if (!textarea || !measurement || textarea.value !== currentValue) return;\n\n    const lineHeight = 24;\n    const nextHeight = Math.min(\n      Math.max(measurement.scrollHeight, minRows * lineHeight),\n      maxRows * lineHeight,\n    );\n    const height = `${nextHeight}px`;\n    if (textarea.style.height !== height) textarea.style.height = height;\n  }, [currentValue, maxRows, minRows]);\n\n  useLayoutEffect(() => {\n    resizeTextarea();\n  }, [resizeTextarea]);\n\n  useEffect(() => {\n    const textarea = textareaRef.current;\n    if (!textarea || typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(resizeTextarea);\n    observer.observe(textarea);\n    return () => observer.disconnect();\n  }, [resizeTextarea]);\n\n  const setValue = (next: string) => {\n    if (value === undefined) setInternalValue(next);\n    onValueChange?.(next);\n  };\n\n  const setModel = (next: string) => {\n    if (model === undefined) setInternalModel(next);\n    onModelChange?.(next);\n  };\n\n  const submit = (event?: FormEvent) => {\n    event?.preventDefault();\n    const prompt = currentValue.trim();\n    if (!prompt || disabled || loading) return;\n\n    onSubmit?.(prompt, currentModelValue);\n    if (value === undefined) setInternalValue(\"\");\n    textareaRef.current?.focus({ preventScroll: true });\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n    onKeyDown?.(event);\n    if (slashOpen && !event.defaultPrevented && !event.nativeEvent.isComposing) {\n      if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n        event.preventDefault();\n        setGlide(false);\n        moveActive(event.key === \"ArrowDown\" ? 1 : -1);\n        return;\n      }\n      if ((event.key === \"Enter\" && !event.shiftKey) || event.key === \"Tab\") {\n        event.preventDefault();\n        if (activeCommand) pickCommand(activeCommand);\n        return;\n      }\n      if (event.key === \"Escape\") {\n        event.preventDefault();\n        setDismissedAt(slashAt);\n        return;\n      }\n    }\n    if (\n      event.defaultPrevented ||\n      event.key !== \"Enter\" ||\n      event.shiftKey ||\n      event.nativeEvent.isComposing\n    ) {\n      return;\n    }\n    event.preventDefault();\n    submit();\n  };\n\n  return (\n    <form\n      onSubmit={submit}\n      className={cn(\n        \"relative w-full rounded-3xl border border-border/80 bg-background p-2 transition-colors focus-within:border-foreground/25\",\n        disabled && \"opacity-60\",\n        className,\n      )}\n    >\n      <div\n        ref={measurementRef}\n        aria-hidden=\"true\"\n        className=\"pointer-events-none invisible absolute inset-x-2 top-0 whitespace-pre-wrap px-2 text-sm leading-6 [overflow-wrap:break-word]\"\n      >\n        {`${currentValue}\\u200b`}\n      </div>\n\n      {/* The list rises a few px out of the input as it fades in, and drops\n          back faster. Focus stays in the input, which drives it with the arrow\n          keys. As you filter, its top edge glides (the list is anchored at its\n          bottom, above the input), leaving rows fade and the rest slide into\n          place, instead of the edge and rows jumping. */}\n      <AnimatePresence>\n        {slashOpen ? (\n          <motion.div\n            key=\"commands\"\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6, scale: 0.98 }}\n            animate={{ opacity: 1, y: 0, scale: 1 }}\n            exit={\n              reduce\n                ? { opacity: 0, pointerEvents: \"none\", transition: LIST_OUT }\n                : { opacity: 0, y: 4, pointerEvents: \"none\", transition: LIST_OUT }\n            }\n            transition={LIST_IN}\n            style={{ transformOrigin: \"bottom left\" }}\n            className=\"absolute inset-x-0 bottom-full z-20 mb-2\"\n          >\n            <ClipResizeFrame edge=\"top\" contentClassName=\"p-2\">\n              <div\n                id={listId}\n                role=\"listbox\"\n                aria-label={t(\"commands\")}\n                className=\"relative max-h-60 overflow-y-auto overscroll-contain\"\n              >\n                <AnimatePresence initial={false} mode=\"popLayout\">\n            {matches.map((command, index) => {\n              const active = index === activeIndex;\n              return (\n                <motion.button\n                  layout={reduce ? false : \"position\"}\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: 1 }}\n                  exit={{ opacity: 0, transition: ROW_OUT }}\n                  transition={ROW_MOVE}\n                  key={command.value}\n                  id={optionId(command.value)}\n                  type=\"button\"\n                  role=\"option\"\n                  aria-selected={active}\n                  tabIndex={-1}\n                  onPointerMove={() => {\n                    if (active) return;\n                    setGlide(true);\n                    moveTo(command.value);\n                  }}\n                  onPointerDown={(event) => event.preventDefault()}\n                  onClick={() => pickCommand(command)}\n                  className={cn(MENU_ITEM_CLASS, \"cursor-default gap-2.5 text-foreground\")}\n                >\n                  {active ? (\n                    <MenuItemHighlight\n                      layoutId={`${baseId}-command-highlight`}\n                      reduce={reduce}\n                      instant={!glide}\n                    />\n                  ) : null}\n                  {command.icon ? (\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"flex shrink-0 text-muted-foreground [&_svg]:size-4\"\n                    >\n                      {command.icon}\n                    </span>\n                  ) : null}\n                  <span className=\"shrink-0\">{command.label}</span>\n                  {command.description ? (\n                    <span className=\"min-w-0 truncate text-xs text-muted-foreground\">\n                      {command.description}\n                    </span>\n                  ) : null}\n                  <span className=\"ml-auto shrink-0 font-mono text-xs text-muted-foreground/70\">\n                    /{command.value}\n                  </span>\n                </motion.button>\n              );\n            })}\n                </AnimatePresence>\n              </div>\n            </ClipResizeFrame>\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n      <textarea\n        ref={textareaRef}\n        value={currentValue}\n        disabled={disabled}\n        placeholder={placeholder ?? t(\"placeholder\")}\n        aria-label={ariaLabel ?? t(\"label\")}\n        rows={minRows}\n        {...textareaProps}\n        aria-autocomplete={commands.length ? \"list\" : undefined}\n        aria-controls={slashOpen ? listId : undefined}\n        aria-activedescendant={activeCommand ? optionId(activeCommand.value) : undefined}\n        onChange={(event) => {\n          setValue(event.target.value);\n          setCaret(event.target.selectionStart);\n        }}\n        onSelect={(event) => setCaret(event.currentTarget.selectionStart)}\n        onKeyDown={handleKeyDown}\n        className=\"scrollbar-hide block w-full resize-none overflow-y-auto bg-transparent px-2 pt-1.5 text-sm leading-6 text-foreground outline-none placeholder:text-muted-foreground/55\"\n      />\n\n      <div className=\"mt-1 flex min-h-8 items-center gap-1\">\n        {actions.length ? (\n          // The library menu: arrow keys and typeahead, a highlight that\n          // glides between rows, and no animation when the keyboard opens it.\n          <DropdownMenu open={actionsOpen} onOpenChange={setActionsOpen}>\n            <Tooltip content={t(\"addToPrompt\")} side=\"top\">\n              <AddButton\n                open={actionsOpen}\n                reduce={reduce}\n                disabled={disabled || loading}\n                aria-label={t(\"addToPrompt\")}\n              />\n            </Tooltip>\n            <DropdownMenuContent side=\"top\" align=\"start\" sideOffset={8} className=\"w-72\">\n              {actions.map((action) => (\n                <DropdownMenuItem\n                  key={action.value}\n                  disabled={action.disabled}\n                  onSelect={() => onAction?.(action.value)}\n                  textValue={typeof action.label === \"string\" ? action.label : undefined}\n                  className=\"items-start\"\n                >\n                  {action.icon ? (\n                    <span aria-hidden=\"true\" className=\"mt-0.5 flex shrink-0\">\n                      {action.icon}\n                    </span>\n                  ) : null}\n                  {/* One line each: a menu row is read at a glance. */}\n                  <span className=\"min-w-0 flex-1\">\n                    <span className=\"block truncate\">{action.label}</span>\n                    {action.description ? (\n                      <span className=\"block truncate text-xs leading-4 text-muted-foreground\">\n                        {action.description}\n                      </span>\n                    ) : null}\n                  </span>\n                </DropdownMenuItem>\n              ))}\n            </DropdownMenuContent>\n          </DropdownMenu>\n        ) : null}\n        {leadingAction}\n        {models.length ? (\n          // The same menu as the plus: a model is a pick from a short list,\n          // with the check at the end of the chosen row.\n          <DropdownMenu open={modelsOpen} onOpenChange={setModelsOpen}>\n            <DropdownMenuTrigger disabled={disabled || loading}>\n              <button\n                type=\"button\"\n                disabled={disabled || loading}\n                className=\"inline-flex h-8 min-w-0 max-w-52 items-center gap-1.5 rounded-full px-3 text-xs text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none data-[state=open]:bg-foreground/[0.06] data-[state=open]:text-foreground\"\n              >\n                {currentModel?.icon ? (\n                  <span aria-hidden=\"true\" className=\"flex size-4 shrink-0 items-center justify-center [&_svg]:size-3.5\">\n                    {currentModel.icon}\n                  </span>\n                ) : null}\n                <span className=\"truncate\">{currentModel?.label ?? t(\"chooseModel\")}</span>\n                <motion.span\n                  aria-hidden=\"true\"\n                  animate={{ rotate: modelsOpen ? 180 : 0 }}\n                  transition={reduce ? { duration: 0 } : SPRING_SWAP}\n                  className=\"flex shrink-0\"\n                >\n                  <ChevronDown className=\"size-3.5\" />\n                </motion.span>\n              </button>\n            </DropdownMenuTrigger>\n            <DropdownMenuContent side=\"top\" align=\"start\" sideOffset={8} className=\"w-56\">\n              <DropdownMenuRadioGroup value={currentModelValue ?? \"\"} onValueChange={setModel}>\n                {models.map((option) => (\n                  <DropdownMenuRadioItem\n                    key={option.value}\n                    value={option.value}\n                    disabled={option.disabled}\n                    closeOnSelect\n                    textValue={typeof option.label === \"string\" ? option.label : undefined}\n                  >\n                    {option.icon ? (\n                      <span aria-hidden=\"true\" className=\"flex shrink-0\">\n                        {option.icon}\n                      </span>\n                    ) : null}\n                    <span className=\"min-w-0 truncate\">{option.label}</span>\n                  </DropdownMenuRadioItem>\n                ))}\n              </DropdownMenuRadioGroup>\n            </DropdownMenuContent>\n          </DropdownMenu>\n        ) : null}\n\n        <span className=\"relative ml-auto flex\">\n          <Tooltip content={loading ? t(\"stop\") : t(\"send\")} side=\"top\">\n          <Button\n            type={loading ? \"button\" : \"submit\"}\n            size=\"icon\"\n            disabled={loading ? !onStop : !canSubmit}\n            aria-label={loading ? t(\"stop\") : t(\"send\")}\n            onClick={loading ? onStop : undefined}\n            className={cn(\n              \"size-8 rounded-full\",\n              // Nothing to send: a quiet gray chip, not a dimmed primary. It\n              // lights up the moment there is a prompt.\n              !loading && !canSubmit && \"bg-foreground/[0.06] text-muted-foreground disabled:opacity-100\",\n            )}\n          >\n            <AnimatePresence initial={false} mode=\"popLayout\">\n              <motion.span\n                key={loading ? \"stop\" : \"send\"}\n                // A little blur melts the arrow into the square, so the swap\n                // reads as one icon changing rather than two crossing.\n                initial={reduce ? { opacity: 1 } : { opacity: 0, y: 3, scale: 0.8, filter: \"blur(2px)\" }}\n                animate={{ opacity: 1, y: 0, scale: 1, filter: \"blur(0px)\" }}\n                exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3, scale: 0.8, filter: \"blur(2px)\" }}\n                transition={reduce ? { duration: 0 } : SPRING_SWAP}\n                className=\"grid place-items-center\"\n              >\n                {loading ? (\n                  <Square className=\"size-3 fill-current\" />\n                ) : (\n                  <ArrowUp className=\"size-4\" />\n                )}\n              </motion.span>\n            </AnimatePresence>\n          </Button>\n          </Tooltip>\n          {/* While the agent works, a thin arc circles the stop button. */}\n          <AnimatePresence>\n            {loading ? (\n              <motion.svg\n                key=\"working\"\n                aria-hidden=\"true\"\n                viewBox=\"0 0 40 40\"\n                initial={{ opacity: 0, scale: reduce ? 1 : 0.9 }}\n                animate={{ opacity: 1, scale: 1, rotate: reduce ? 0 : 360 }}\n                exit={{ opacity: 0, transition: { duration: 0.15, ease: EASE_OUT } }}\n                transition={{\n                  opacity: { duration: 0.2, ease: EASE_OUT },\n                  scale: { duration: 0.2, ease: EASE_OUT },\n                  rotate: { duration: 1, ease: \"linear\", repeat: Number.POSITIVE_INFINITY },\n                }}\n                className=\"pointer-events-none absolute -inset-1 size-10 text-primary\"\n              >\n                <circle cx=\"20\" cy=\"20\" r=\"19\" fill=\"none\" stroke=\"currentColor\" strokeOpacity={0.15} strokeWidth=\"1.5\" />\n                <circle\n                  cx=\"20\"\n                  cy=\"20\"\n                  r=\"19\"\n                  fill=\"none\"\n                  stroke=\"currentColor\"\n                  strokeWidth=\"1.5\"\n                  strokeLinecap=\"round\"\n                  strokeDasharray=\"30 90\"\n                />\n              </motion.svg>\n            ) : null}\n          </AnimatePresence>\n        </span>\n      </div>\n    </form>\n  );\n}\n\n/**\n * The plus that opens the add menu. Its own component so the tooltip around it\n * and the menu trigger inside both reach the button: the plus turns into a\n * cross while the menu is open.\n */\nfunction AddButton({\n  open,\n  reduce,\n  ...props\n}: ComponentProps<typeof Button> & { open: boolean; reduce: boolean }) {\n  return (\n    <DropdownMenuTrigger disabled={props.disabled}>\n      <Button\n        type=\"button\"\n        variant=\"ghost\"\n        size=\"icon\"\n        {...props}\n        className=\"size-8 rounded-full data-[state=open]:bg-foreground/[0.06] data-[state=open]:text-foreground\"\n      >\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: open ? 45 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n          className=\"flex\"\n        >\n          <Plus className=\"size-4\" />\n        </motion.span>\n      </Button>\n    </DropdownMenuTrigger>\n  );\n}\n"},{"path":"components/agents/streaming-response.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport {\n  Check,\n  ChevronDown,\n  Copy,\n  RotateCcw,\n  ThumbsDown,\n  ThumbsUp,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { type ReactNode, useCallback, useId, useState } from \"react\";\nimport { AgentDisclosure } from \"@/components/agents/agent-disclosure\";\nimport {\n  type CitationItem,\n  CitationList,\n  CitationStack,\n} from \"@/components/agents/citations\";\nimport { IconSwap as ActionIcon } from \"@/components/agents/icon-swap\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from \"@/lib/ease\";\nimport { useCopy } from \"@/lib/hooks/use-copy\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport type StreamingResponseStatus = \"streaming\" | \"complete\" | \"error\";\nexport type StreamingResponseFeedback = \"up\" | \"down\" | null;\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const streamingResponseMessages = {\n  copy: \"Copy response\",\n  copied: \"Copied\",\n  retry: \"Retry response\",\n  helpful: \"Helpful\",\n  notHelpful: \"Not helpful\",\n  source: \"{count} source\",\n  sources: \"{count} sources\",\n};\n\nexport type StreamingResponseMessages = typeof streamingResponseMessages;\n\nexport interface StreamingResponseProps {\n  /** Rendered response content. Pass plain text or the output of a Markdown renderer. */\n  children: ReactNode;\n  /** Stream state; actions appear once it leaves \"streaming\". Default: \"streaming\" */\n  status?: StreamingResponseStatus;\n  /** Plain-text value copied by the built-in copy action. */\n  copyText?: string;\n  /** Overrides the built-in clipboard action. */\n  onCopy?: () => void | Promise<void>;\n  /** Called when the retry action is pressed. The action shows only when set. */\n  onRetry?: () => void;\n  /** Optional sources shown as a compact footer disclosure after streaming. */\n  sources?: CitationItem[];\n  /** Whether the sources list is expanded, for controlled use. */\n  sourcesOpen?: boolean;\n  /** Whether the sources list starts expanded when uncontrolled. Default: false */\n  defaultSourcesOpen?: boolean;\n  /** Called with the next state when the sources list expands or collapses. */\n  onSourcesOpenChange?: (open: boolean) => void;\n  /** Prefix for source row ids that `Citation` markers link to. Generated when omitted. */\n  sourceIdPrefix?: string;\n  /** The thumbs up or down rating, for controlled use. */\n  feedback?: StreamingResponseFeedback;\n  /** The initial rating when uncontrolled. Default: null */\n  defaultFeedback?: StreamingResponseFeedback;\n  /** Called with the new rating, or `null` when it is toggled off. */\n  onFeedbackChange?: (feedback: StreamingResponseFeedback) => void;\n  /** Set false when a surrounding conversation log announces streamed text. */\n  announce?: boolean;\n  /** Hides the built-in completion actions without changing response status. */\n  showActions?: boolean;\n  /** Override any built-in string. `{count}` fills `source` (one) and `sources` (many). */\n  labels?: Partial<StreamingResponseMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes merged onto the wrapper around the response content. */\n  contentClassName?: string;\n  /** Classes merged onto the row of completion actions. */\n  actionsClassName?: string;\n}\n\nfunction ResponseAction({\n  label,\n  active,\n  onClick,\n  children,\n}: {\n  label: string;\n  /** Set for toggle actions; exposed as `aria-pressed`. */\n  active?: boolean;\n  onClick: () => void;\n  children: ReactNode;\n}) {\n  const reduce = useReducedMotion() ?? false;\n\n  return (\n    <Tooltip content={label} side=\"top\">\n      <motion.button\n        type=\"button\"\n        aria-label={label}\n        aria-pressed={active}\n        onClick={onClick}\n        whileTap={reduce ? undefined : { scale: 0.95 }}\n        transition={SPRING_PRESS}\n        className={cn(\n          // A foreground tint, not bg-muted: muted is the bubble colour, so a\n          // muted hover would vanish inside a soft bubble.\n          \"grid size-7 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n          active && \"bg-foreground/[0.06] text-foreground\",\n        )}\n      >\n        {children}\n      </motion.button>\n    </Tooltip>\n  );\n}\n\nexport function StreamingResponse({\n  children,\n  status = \"streaming\",\n  copyText,\n  onCopy,\n  onRetry,\n  sources = [],\n  sourcesOpen,\n  defaultSourcesOpen = false,\n  onSourcesOpenChange,\n  sourceIdPrefix,\n  feedback,\n  defaultFeedback = null,\n  onFeedbackChange,\n  announce = true,\n  showActions = true,\n  labels,\n  className,\n  contentClassName,\n  actionsClassName,\n}: StreamingResponseProps) {\n  const t = useMessages(\"streamingResponse\", streamingResponseMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const { copied, copy: handleCopy } = useCopy({ text: copyText, onCopy });\n  const [internalFeedback, setInternalFeedback] =\n    useState<StreamingResponseFeedback>(defaultFeedback);\n  const [internalSourcesOpen, setInternalSourcesOpen] =\n    useState(defaultSourcesOpen);\n  const currentFeedback = feedback ?? internalFeedback;\n  const currentSourcesOpen = sourcesOpen ?? internalSourcesOpen;\n  const streaming = status === \"streaming\";\n  const complete = status === \"complete\";\n  const canCopy = Boolean(copyText || onCopy);\n  const hasSources = sources.length > 0;\n  const shouldShowActions =\n    showActions && !streaming && (canCopy || onRetry || complete || hasSources);\n  const sourcesContentId = `${baseId}-sources`;\n  const resolvedSourcePrefix =\n    sourceIdPrefix ?? `response-source-${baseId.replace(/:/g, \"\")}`;\n\n  const setFeedback = (next: Exclude<StreamingResponseFeedback, null>) => {\n    const value = currentFeedback === next ? null : next;\n    if (feedback === undefined) setInternalFeedback(value);\n    onFeedbackChange?.(value);\n  };\n\n  const setSourcesOpen = useCallback(\n    (next: boolean) => {\n      if (sourcesOpen === undefined) setInternalSourcesOpen(next);\n      onSourcesOpenChange?.(next);\n    },\n    [onSourcesOpenChange, sourcesOpen],\n  );\n\n  return (\n    <div\n      data-state={status}\n      aria-busy={streaming}\n      className={cn(\"w-full\", className)}\n    >\n      <div\n        aria-live={announce ? \"polite\" : \"off\"}\n        className={cn(\n          \"text-sm leading-6 text-foreground/90 [&_a]:font-medium [&_a]:underline [&_a]:underline-offset-4 [&_code]:rounded [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.9em] [&_ol]:my-3 [&_ol]:list-decimal [&_ol]:space-y-1 [&_ol]:pl-5 [&_p+p]:mt-3 [&_pre]:my-3 [&_pre]:overflow-x-auto [&_pre]:rounded-xl [&_pre]:border [&_pre]:border-border [&_pre]:bg-muted/45 [&_pre]:p-3 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_ul]:my-3 [&_ul]:list-disc [&_ul]:space-y-1 [&_ul]:pl-5\",\n          contentClassName,\n        )}\n      >\n        {children}\n      </div>\n\n      <AnimatePresence initial={false}>\n        {shouldShowActions ? (\n          <motion.div\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 4 }}\n            animate={{ opacity: 1, y: 0 }}\n            exit={{ opacity: 0 }}\n            transition={{ duration: reduce ? 0.12 : 0.22, ease: EASE_OUT }}\n            className=\"mt-3\"\n          >\n            <div className={cn(\"flex items-center gap-0.5\", actionsClassName)}>\n              {canCopy ? (\n                <ResponseAction\n                  label={copied ? t(\"copied\") : t(\"copy\")}\n                  onClick={handleCopy}\n                >\n                  <ActionIcon id={copied ? \"copied\" : \"copy\"}>\n                    {copied ? (\n                      <Check className=\"size-3.5\" />\n                    ) : (\n                      <Copy className=\"size-3.5\" />\n                    )}\n                  </ActionIcon>\n                </ResponseAction>\n              ) : null}\n              {onRetry ? (\n                <ResponseAction label={t(\"retry\")} onClick={onRetry}>\n                  <RotateCcw className=\"size-3.5\" />\n                </ResponseAction>\n              ) : null}\n              {complete ? (\n                <>\n                  <ResponseAction\n                    label={t(\"helpful\")}\n                    active={currentFeedback === \"up\"}\n                    onClick={() => setFeedback(\"up\")}\n                  >\n                    {/* A chosen rating fills in, so the choice reads at a glance. */}\n                    <ActionIcon id={currentFeedback === \"up\" ? \"up-on\" : \"up\"}>\n                      <ThumbsUp\n                        className={cn(\"size-3.5\", currentFeedback === \"up\" && \"fill-current\")}\n                      />\n                    </ActionIcon>\n                  </ResponseAction>\n                  <ResponseAction\n                    label={t(\"notHelpful\")}\n                    active={currentFeedback === \"down\"}\n                    onClick={() => setFeedback(\"down\")}\n                  >\n                    <ActionIcon id={currentFeedback === \"down\" ? \"down-on\" : \"down\"}>\n                      <ThumbsDown\n                        className={cn(\"size-3.5\", currentFeedback === \"down\" && \"fill-current\")}\n                      />\n                    </ActionIcon>\n                  </ResponseAction>\n                </>\n              ) : null}\n              {hasSources ? (\n                <button\n                  type=\"button\"\n                  aria-expanded={currentSourcesOpen}\n                  aria-controls={sourcesContentId}\n                  onClick={() => setSourcesOpen(!currentSourcesOpen)}\n                  className=\"group ml-1 inline-flex min-h-7 items-center gap-2 rounded-full px-1.5 text-xs text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n                >\n                  <CitationStack citations={sources} />\n                  <span className=\"tabular-nums\">\n                    {t(sources.length === 1 ? \"source\" : \"sources\", {\n                      count: sources.length,\n                    })}\n                  </span>\n                  <motion.span\n                    aria-hidden=\"true\"\n                    animate={{ rotate: currentSourcesOpen ? 180 : 0 }}\n                    transition={reduce ? { duration: 0 } : SPRING_SWAP}\n                    className=\"text-muted-foreground/50 group-hover:text-muted-foreground\"\n                  >\n                    <ChevronDown className=\"size-3\" />\n                  </motion.span>\n                </button>\n              ) : null}\n            </div>\n\n            {hasSources ? (\n              <AgentDisclosure\n                id={sourcesContentId}\n                open={currentSourcesOpen}\n              >\n                <CitationList\n                  citations={sources}\n                  idPrefix={resolvedSourcePrefix}\n                  className=\"mt-2 rounded-2xl border border-border p-2\"\n                />\n              </AgentDisclosure>\n            ) : null}\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n    </div>\n  );\n}\n"},{"path":"components/agents/todo-list.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport { ChevronDown, ListTodo } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { type ReactNode, useId, useLayoutEffect, useRef } from \"react\";\nimport { ClipResizeFrame } from \"@/components/agents/clip-resize-frame\";\nimport { ActionSwapRollText } from \"@/components/motion/action-swap-roll\";\nimport {\n  EASE_OUT,\n  SPRING_LAYOUT,\n  SPRING_SWAP,\n} from \"@/lib/ease\";\nimport { useStatusOpen } from \"@/lib/hooks/use-status-open\";\nimport { formatNumber, useLocale, useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport type TodoItemStatus =\n  | \"pending\"\n  | \"in-progress\"\n  | \"completed\"\n  | \"cancelled\";\n\nexport interface TodoItem {\n  /** Unique key for the row. */\n  id: string;\n  /** Task text; struck through when completed. */\n  title: ReactNode;\n  /** Task state; sets the icon and text tone. Default: \"pending\" */\n  status?: TodoItemStatus;\n  /** Ring fill from 0 to 100 while in progress; unset spins a partial ring. */\n  progress?: number;\n  /** Muted text at the end of the row, such as a time or count. */\n  detail?: ReactNode;\n}\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const todoListMessages = {\n  title: \"To-dos\",\n  label: \"Agent task list\",\n  progress: \"{completed} of {total} tasks completed\",\n  empty: \"No tasks yet\",\n  pending: \"Pending\",\n  inProgress: \"In progress\",\n  completed: \"Completed\",\n  cancelled: \"Cancelled\",\n};\n\nexport type TodoListMessages = typeof todoListMessages;\n\nconst STATUS_MESSAGE = {\n  pending: \"pending\",\n  \"in-progress\": \"inProgress\",\n  completed: \"completed\",\n  cancelled: \"cancelled\",\n} as const satisfies Record<TodoItemStatus, keyof TodoListMessages>;\n\nexport interface TodoListProps {\n  /** The tasks, each with a status. */\n  items: TodoItem[];\n  /** Header text. Default: \"To-dos\" */\n  title?: ReactNode;\n  /** Whether the list is expanded, for controlled use. */\n  open?: boolean;\n  /** Whether the list starts expanded when uncontrolled. Default: true */\n  defaultOpen?: boolean;\n  /** Called with the new state when the list expands or collapses. */\n  onOpenChange?: (open: boolean) => void;\n  /** Collapses the list once every task is completed. Default: true */\n  collapseOnComplete?: boolean;\n  /** Height in px before the task list scrolls. Default: 248 */\n  maxHeight?: number;\n  /** Override any built-in string. `{completed}` and `{total}` fill `progress`. */\n  labels?: Partial<TodoListMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nfunction TodoHeaderIcon({ complete }: { complete: boolean }) {\n  const reduce = useReducedMotion() ?? false;\n\n  return (\n    <span\n      aria-hidden=\"true\"\n      className=\"relative grid size-6 shrink-0 place-items-center\"\n    >\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        {complete ? (\n          <motion.svg\n            key=\"complete\"\n            viewBox=\"0 0 24 24\"\n            initial={reduce ? { opacity: 1 } : { opacity: 0, scale: 0.72 }}\n            animate={{ opacity: 1, scale: 1 }}\n            exit={{ opacity: 0 }}\n            transition={reduce ? { duration: 0 } : SPRING_SWAP}\n            className=\"absolute size-5.5 overflow-visible text-emerald-500\"\n          >\n            <circle cx=\"12\" cy=\"12\" r=\"9\" fill=\"currentColor\" />\n            <motion.path\n              d=\"M7.5 12.25 10.5 15.25 16.75 8.75\"\n              fill=\"none\"\n              stroke=\"white\"\n              strokeWidth=\"2.25\"\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              initial={reduce ? { pathLength: 1 } : { pathLength: 0 }}\n              animate={{ pathLength: 1 }}\n              transition={\n                reduce ? { duration: 0 } : { duration: 0.24, ease: EASE_OUT }\n              }\n            />\n          </motion.svg>\n        ) : (\n          <motion.span\n            key=\"todo\"\n            initial={reduce ? { opacity: 1 } : { opacity: 0, scale: 0.8 }}\n            animate={{ opacity: 1, scale: 1 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.72 }}\n            transition={reduce ? { duration: 0 } : SPRING_SWAP}\n            className=\"absolute grid place-items-center text-muted-foreground\"\n          >\n            <ListTodo className=\"size-4\" />\n          </motion.span>\n        )}\n      </AnimatePresence>\n    </span>\n  );\n}\n\nfunction TodoStatusIcon({\n  status,\n  progress,\n}: {\n  status: TodoItemStatus;\n  progress?: number;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  const normalizedProgress =\n    progress === undefined ? 0.68 : Math.min(100, Math.max(0, progress)) / 100;\n\n  return (\n    <motion.svg\n      aria-hidden=\"true\"\n      viewBox=\"0 0 24 24\"\n      initial={false}\n      className={cn(\n        \"mx-0.5 size-5 shrink-0 overflow-visible text-muted-foreground\",\n        status === \"in-progress\" && \"text-foreground\",\n        status === \"cancelled\" && \"text-rose-600 dark:text-rose-400\",\n      )}\n    >\n      <motion.circle\n        cx=\"12\"\n        cy=\"12\"\n        r=\"9\"\n        fill=\"currentColor\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeDasharray={status === \"pending\" ? \"2 3\" : undefined}\n        strokeLinecap=\"round\"\n        initial={false}\n        animate={{ fillOpacity: status === \"completed\" ? 0.06 : 0 }}\n        transition={reduce ? { duration: 0 } : { duration: 0.18, ease: EASE_OUT }}\n        className={cn(status === \"in-progress\" && \"opacity-20\")}\n      />\n      <motion.circle\n        cx=\"12\"\n        cy=\"12\"\n        r=\"9\"\n        pathLength=\"1\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap=\"round\"\n        initial={false}\n        animate={{\n          pathLength: status === \"in-progress\" ? normalizedProgress : 0,\n          opacity: status === \"in-progress\" ? 1 : 0,\n          rotate:\n            status === \"in-progress\" && progress === undefined && !reduce\n              ? 360\n              : -90,\n        }}\n        transition={\n          status === \"in-progress\" && progress === undefined && !reduce\n            ? { rotate: { duration: 1.1, repeat: Infinity, ease: \"linear\" } }\n            : reduce\n              ? { duration: 0 }\n              : SPRING_LAYOUT\n        }\n        style={{ transformOrigin: \"12px 12px\" }}\n      />\n      <motion.path\n        d=\"M7.5 12.25 10.5 15.25 16.75 8.75\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        initial={false}\n        animate={{\n          pathLength: status === \"completed\" ? 1 : 0,\n          opacity: status === \"completed\" ? 1 : 0,\n        }}\n        transition={reduce ? { duration: 0 } : { duration: 0.24, ease: EASE_OUT }}\n      />\n      <motion.path\n        d=\"M8.5 8.5 15.5 15.5M15.5 8.5 8.5 15.5\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth=\"2\"\n        strokeLinecap=\"round\"\n        initial={false}\n        animate={{\n          pathLength: status === \"cancelled\" ? 1 : 0,\n          opacity: status === \"cancelled\" ? 1 : 0,\n        }}\n        transition={reduce ? { duration: 0 } : { duration: 0.2, ease: EASE_OUT }}\n      />\n    </motion.svg>\n  );\n}\n\nexport function TodoList({\n  items,\n  title,\n  open,\n  defaultOpen = true,\n  onOpenChange,\n  collapseOnComplete = true,\n  maxHeight = 248,\n  labels,\n  className,\n}: TodoListProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"todoList\", todoListMessages, labels);\n  const { locale } = useLocale();\n  const baseId = useId();\n  const triggerId = `${baseId}-trigger`;\n  const contentId = `${baseId}-content`;\n  const viewportRef = useRef<HTMLDivElement>(null);\n  const completed = items.filter((item) => item.status === \"completed\").length;\n  const allComplete = items.length > 0 && completed === items.length;\n  const itemCount = items.length;\n  // Reopens when finished work gets a new item; folds once everything is\n  // done, if asked to, including a list that mounts already complete.\n  const [currentOpen, setOpen] = useStatusOpen({\n    status: allComplete,\n    initialStatus: false,\n    open,\n    defaultOpen,\n    onOpenChange,\n    decide: (wasComplete, isComplete) => {\n      if (wasComplete && !isComplete) return true;\n      if (!wasComplete && isComplete && collapseOnComplete) return false;\n      return undefined;\n    },\n  });\n\n  useLayoutEffect(() => {\n    const viewport = viewportRef.current;\n    if (!viewport || itemCount === 0) return;\n\n    const frame = requestAnimationFrame(() => {\n      if (viewport.scrollHeight <= viewport.clientHeight) return;\n      if (typeof viewport.scrollTo === \"function\") {\n        viewport.scrollTo({\n          top: viewport.scrollHeight,\n          behavior: reduce ? \"auto\" : \"smooth\",\n        });\n      } else {\n        viewport.scrollTop = viewport.scrollHeight;\n      }\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [itemCount, reduce]);\n\n  return (\n    // The card's bottom edge glides as the list folds or opens, instead of\n    // the old fold that snapped the edge up once it finished.\n    <ClipResizeFrame\n      role=\"region\"\n      aria-label={t(\"label\")}\n      className={cn(\"w-full\", className)}\n    >\n      <button\n        id={triggerId}\n        type=\"button\"\n        aria-expanded={currentOpen}\n        aria-controls={contentId}\n        onClick={() => setOpen(!currentOpen)}\n        className=\"group flex h-11 w-full items-center gap-2.5 rounded-2xl px-3.5 text-start outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n      >\n        <TodoHeaderIcon complete={allComplete} />\n        <h3 className=\"min-w-0 flex-1 truncate text-sm font-medium text-foreground/90\">\n          {title ?? t(\"title\")}\n        </h3>\n        <span\n          className={cn(\n            \"shrink-0 text-xs font-medium tabular-nums text-muted-foreground\",\n            allComplete && \"text-emerald-600 dark:text-emerald-400\",\n          )}\n        >\n          <span className=\"sr-only\">\n            {t(\"progress\", { completed, total: items.length })}\n          </span>\n          <span aria-hidden=\"true\" className=\"inline-flex\">\n            <ActionSwapRollText value={String(completed)}>\n              {formatNumber(completed, locale)}\n            </ActionSwapRollText>\n            <span>/</span>\n            <span>{formatNumber(items.length, locale)}</span>\n          </span>\n        </span>\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: currentOpen ? 180 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n          className=\"text-muted-foreground/50 transition-colors group-hover:text-muted-foreground\"\n        >\n          <ChevronDown className=\"size-3.5\" />\n        </motion.span>\n      </button>\n\n      {/* The list leaves the layout at once when folding (popLayout) and\n          fades under the rising edge; opening, it fades in as the edge drops. */}\n      <AnimatePresence initial={false} mode=\"popLayout\">\n      {currentOpen ? (\n      <motion.div\n        key=\"list\"\n        id={contentId}\n        role=\"region\"\n        aria-labelledby={triggerId}\n        initial={{ opacity: 0 }}\n        animate={{ opacity: 1, transition: { duration: 0.2, ease: EASE_OUT } }}\n        exit={{ opacity: 0, transition: { duration: 0.14, ease: EASE_OUT } }}\n        className=\"w-full\"\n      >\n        <div\n          ref={viewportRef}\n          className=\"scrollbar-hide overflow-y-auto px-2 pb-2\"\n          style={{ maxHeight }}\n        >\n          {items.length ? (\n            <ol aria-live=\"polite\" className=\"space-y-0\">\n            <AnimatePresence initial={false} mode=\"popLayout\">\n              {items.map((item) => {\n                const status = item.status ?? \"pending\";\n                return (\n                  <motion.li\n                    layout=\"position\"\n                    key={item.id}\n                    initial={reduce ? { opacity: 1 } : { opacity: 0, y: 6 }}\n                    animate={{ opacity: 1, y: 0 }}\n                    exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3 }}\n                    transition={\n                      reduce\n                        ? { duration: 0 }\n                        : {\n                            opacity: { duration: 0.18, ease: EASE_OUT },\n                            y: SPRING_LAYOUT,\n                            layout: SPRING_LAYOUT,\n                          }\n                    }\n                    className=\"flex min-h-9 items-center gap-2.5 rounded-xl px-1.5 py-1\"\n                  >\n                    <TodoStatusIcon status={status} progress={item.progress} />\n                    <span className=\"sr-only\">{t(STATUS_MESSAGE[status])}: </span>\n                    <span\n                      className={cn(\n                        \"min-w-0 flex-1 truncate text-sm leading-5\",\n                        status === \"pending\" && \"text-muted-foreground/65\",\n                        status === \"in-progress\" && \"text-foreground\",\n                        status === \"completed\" && \"text-muted-foreground/60\",\n                        status === \"cancelled\" && \"text-muted-foreground/55\",\n                      )}\n                    >\n                      <span className=\"relative inline-block max-w-full\">\n                        {item.title}\n                        <motion.span\n                          aria-hidden=\"true\"\n                          initial={false}\n                          animate={{\n                            scaleX: status === \"completed\" ? 1 : 0,\n                            opacity: status === \"completed\" ? 1 : 0,\n                          }}\n                          transition={\n                            reduce\n                              ? { duration: 0 }\n                              : { duration: 0.28, ease: EASE_OUT, delay: 0.06 }\n                          }\n                          className=\"absolute inset-x-0 top-1/2 h-px origin-left bg-current rtl:origin-right\"\n                        />\n                      </span>\n                    </span>\n                    {item.detail ? (\n                      <span className=\"shrink-0 text-sm text-muted-foreground/55\">\n                        {item.detail}\n                      </span>\n                    ) : null}\n                  </motion.li>\n                );\n              })}\n            </AnimatePresence>\n            </ol>\n          ) : (\n            <p className=\"px-1.5 py-2 text-sm text-muted-foreground\">\n              {t(\"empty\")}\n            </p>\n          )}\n        </div>\n      </motion.div>\n      ) : null}\n      </AnimatePresence>\n    </ClipResizeFrame>\n  );\n}\n"},{"path":"components/agents/tool-approval.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport {\n  Check,\n  ChevronDown,\n  CircleAlert,\n  LoaderCircle,\n  ShieldCheck,\n  X,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { type ReactNode, useId } from \"react\";\nimport {\n  AgentCode,\n  type AgentCodeLanguage,\n} from \"@/components/agents/agent-code\";\nimport { AgentDisclosure } from \"@/components/agents/agent-disclosure\";\nimport { IconSwap } from \"@/components/agents/icon-swap\";\nimport { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from \"@/lib/ease\";\nimport { useStatusOpen } from \"@/lib/hooks/use-status-open\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ToolApprovalStatus =\n  | \"pending\"\n  | \"approving\"\n  | \"approved\"\n  | \"denied\"\n  | \"running\"\n  | \"complete\"\n  | \"error\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const toolApprovalMessages = {\n  title: \"Allow this tool to run?\",\n  viewDetails: \"View details\",\n  allowOnce: \"Allow once\",\n  alwaysAllow: \"Always allow\",\n  deny: \"Deny\",\n  pending: \"Approval required\",\n  approving: \"Approving\",\n  approved: \"Approved\",\n  denied: \"Denied\",\n  running: \"Running\",\n  complete: \"Completed\",\n  error: \"Failed\",\n};\n\nexport type ToolApprovalMessages = typeof toolApprovalMessages;\n\nexport interface ToolApprovalParameter {\n  /** Unique key for the row. */\n  id: string;\n  /** Parameter name, shown muted in the left column of the details. */\n  label: ReactNode;\n  /** Parameter value, shown in monospace in the right column. */\n  value: ReactNode;\n}\n\nexport interface ToolApprovalCodeProps {\n  /** Source text to show, wrapped rather than scrolled. */\n  code: string;\n  /** Language used for syntax highlighting. Default: \"bash\" */\n  language?: AgentCodeLanguage;\n  /** Classes merged onto the code block. */\n  className?: string;\n}\n\nexport interface ToolApprovalProps {\n  /** Tool name shown in monospace under the title. */\n  tool: ReactNode;\n  /** Heading for the request. Default: \"Allow this tool to run?\" */\n  title?: ReactNode;\n  /** Short explanation of what the tool will do. */\n  description?: ReactNode;\n  /** Arguments listed in the expandable details panel. */\n  parameters?: ToolApprovalParameter[];\n  /** Request state, which sets the icon, badge and action buttons. Default: \"pending\" */\n  status?: ToolApprovalStatus;\n  /** Whether the details panel is expanded, for controlled use. */\n  open?: boolean;\n  /** Whether the details panel starts expanded when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new state when the details panel opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /** Called when the \"Allow once\" button is pressed. */\n  onApprove?: () => void;\n  /** Called when \"Always allow\" is pressed. The button shows only when set. */\n  onAlwaysAllow?: () => void;\n  /** Called when the \"Deny\" button is pressed. */\n  onDeny?: () => void;\n  /** Override any built-in string. */\n  labels?: Partial<ToolApprovalMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nfunction getStatusBadgeClass(status: ToolApprovalStatus) {\n  if (status === \"pending\") {\n    return \"border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400\";\n  }\n  if (status === \"approving\" || status === \"running\") {\n    return \"border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400\";\n  }\n  if (status === \"approved\" || status === \"complete\") {\n    return \"border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400\";\n  }\n  return \"border-rose-500/30 bg-rose-500/10 text-rose-600 dark:text-rose-400\";\n}\n\nexport function ToolApprovalCode({\n  code,\n  language = \"bash\",\n  className,\n}: ToolApprovalCodeProps) {\n  return (\n    <AgentCode\n      code={code}\n      language={language}\n      className={cn(\n        // Parameter values sit in a narrow grid column with nowhere to scroll\n        // on touch, so they wrap instead of clipping (as ToolResultOutput does).\n        \"whitespace-pre-wrap break-words rounded-lg border border-border/50 bg-muted/30 px-2.5 py-2\",\n        className,\n      )}\n    />\n  );\n}\n\nexport function ToolApproval({\n  tool,\n  title,\n  description,\n  parameters = [],\n  status = \"pending\",\n  open,\n  defaultOpen = false,\n  onOpenChange,\n  onApprove,\n  onAlwaysAllow,\n  onDeny,\n  labels,\n  className,\n}: ToolApprovalProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"toolApproval\", toolApprovalMessages, labels);\n  const baseId = useId();\n  const detailsId = `${baseId}-details`;\n  // The details fold once a decision is made.\n  const [currentOpen, setOpen] = useStatusOpen({\n    status,\n    open,\n    defaultOpen,\n    onOpenChange,\n    decide: (previous, next) =>\n      previous === \"pending\" && next !== \"pending\" ? false : undefined,\n  });\n  const busy = status === \"approving\" || status === \"running\";\n  const pending = status === \"pending\";\n  const error = status === \"error\";\n\n  return (\n    <div\n      data-state={status}\n      aria-busy={busy}\n      className={cn(\n        \"w-full overflow-hidden rounded-2xl border border-border/60 bg-background text-sm\",\n        className,\n      )}\n    >\n      <div className=\"flex items-start gap-3 p-4\">\n        <span\n          aria-hidden=\"true\"\n          className={cn(\n            \"mt-0.5 grid size-8 shrink-0 place-items-center rounded-full border border-border/60 bg-background text-muted-foreground\",\n            error && \"text-destructive\",\n          )}\n        >\n          {/* The icon tells the story of the request, so each change morphs:\n              shield, then spinner, then check or cross. */}\n          <IconSwap id={busy ? \"busy\" : status}>\n              {busy ? (\n                <LoaderCircle className={cn(\"size-4\", !reduce && \"animate-spin\")} />\n              ) : error ? (\n                <CircleAlert className=\"size-4\" />\n              ) : status === \"denied\" ? (\n                <X className=\"size-4\" />\n              ) : status === \"approved\" || status === \"complete\" ? (\n                <Check className=\"size-4\" />\n              ) : (\n                <ShieldCheck className=\"size-4\" />\n              )}\n          </IconSwap>\n        </span>\n\n        <div className=\"min-w-0 flex-1\">\n          <div className=\"flex min-w-0 items-start justify-between gap-3\">\n            <div className=\"min-w-0\">\n              <div className=\"font-medium text-foreground\">{title ?? t(\"title\")}</div>\n              <div className=\"mt-0.5 truncate font-mono text-xs text-muted-foreground\">\n                {tool}\n              </div>\n            </div>\n            <span\n              className={cn(\n                \"relative shrink-0 overflow-hidden rounded-full border px-2 py-0.5 text-[11px] font-medium transition-colors\",\n                getStatusBadgeClass(status),\n              )}\n            >\n              {/* The label rolls up as the status moves on. */}\n              <AnimatePresence mode=\"popLayout\" initial={false}>\n                <motion.span\n                  key={status}\n                  initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6 }}\n                  animate={{ opacity: 1, y: 0 }}\n                  exit={reduce ? { opacity: 0 } : { opacity: 0, y: -6 }}\n                  transition={{ duration: reduce ? 0.12 : 0.18, ease: EASE_OUT }}\n                  className=\"block\"\n                >\n                  {t(status)}\n                </motion.span>\n              </AnimatePresence>\n            </span>\n          </div>\n          {description ? (\n            <p className=\"mt-2 leading-5 text-muted-foreground\">{description}</p>\n          ) : null}\n\n          {parameters.length ? (\n            <button\n              type=\"button\"\n              aria-expanded={currentOpen}\n              aria-controls={detailsId}\n              onClick={() => setOpen(!currentOpen)}\n              className=\"mt-2 inline-flex items-center gap-1 rounded-full text-xs font-medium text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n            >\n              {t(\"viewDetails\")}\n              <motion.span\n                aria-hidden=\"true\"\n                animate={{ rotate: currentOpen ? 180 : 0 }}\n                transition={reduce ? { duration: 0 } : SPRING_SWAP}\n              >\n                <ChevronDown className=\"size-3.5\" />\n              </motion.span>\n            </button>\n          ) : null}\n        </div>\n      </div>\n\n      <AgentDisclosure\n        id={detailsId}\n        open={currentOpen}\n      >\n        <dl className=\"mx-4 mb-4 grid gap-2 rounded-xl border border-border/50 bg-background/70 p-3\">\n          {parameters.map((parameter) => (\n            <div\n              key={parameter.id}\n              className=\"grid grid-cols-[minmax(0,7rem)_minmax(0,1fr)] items-center gap-3 text-xs\"\n            >\n              <dt className=\"text-muted-foreground\">{parameter.label}</dt>\n              <dd className=\"min-w-0 break-words font-mono text-foreground/85\">\n                {parameter.value}\n              </dd>\n            </div>\n          ))}\n        </dl>\n      </AgentDisclosure>\n\n      <AnimatePresence initial={false}>\n        {pending ? (\n          <motion.div\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 4 }}\n            animate={{ opacity: 1, y: 0 }}\n            exit={{ opacity: 0 }}\n            transition={{ duration: reduce ? 0.12 : 0.22, ease: EASE_OUT }}\n            className=\"flex flex-wrap items-center gap-2 border-t border-border/60 px-4 py-3\"\n          >\n            <motion.button\n              type=\"button\"\n              onClick={onApprove}\n              whileTap={reduce ? undefined : { scale: 0.97 }}\n              transition={SPRING_PRESS}\n              className=\"rounded-full bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2\"\n            >\n              {t(\"allowOnce\")}\n            </motion.button>\n            {onAlwaysAllow ? (\n              <motion.button\n                type=\"button\"\n                onClick={onAlwaysAllow}\n                whileTap={reduce ? undefined : { scale: 0.97 }}\n                transition={SPRING_PRESS}\n                className=\"rounded-full border border-border/60 bg-background px-3 py-1.5 text-xs font-medium text-foreground outline-none transition-colors hover:bg-foreground/[0.06] focus-visible:ring-2 focus-visible:ring-ring\"\n              >\n                {t(\"alwaysAllow\")}\n              </motion.button>\n            ) : null}\n            <motion.button\n              type=\"button\"\n              onClick={onDeny}\n              whileTap={reduce ? undefined : { scale: 0.97 }}\n              transition={SPRING_PRESS}\n              className=\"rounded-full px-3 py-1.5 text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n            >\n              {t(\"deny\")}\n            </motion.button>\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n    </div>\n  );\n}\n"},{"path":"components/agents/tool-result.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/chat-app\n\nimport {\n  Ban,\n  Braces,\n  Check,\n  ChevronDown,\n  CircleCheck,\n  CircleX,\n  Copy,\n  LoaderCircle,\n  RotateCcw,\n  SquareTerminal,\n  Wrench,\n} from \"lucide-react\";\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { type ReactNode, useId, useLayoutEffect, useRef } from \"react\";\nimport {\n  AgentCode,\n  type AgentCodeLanguage,\n} from \"@/components/agents/agent-code\";\nimport { AgentDisclosure } from \"@/components/agents/agent-disclosure\";\nimport { IconSwap } from \"@/components/agents/icon-swap\";\nimport { ActionSwapRollText } from \"@/components/motion/action-swap-roll\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { SPRING_PRESS, SPRING_SWAP } from \"@/lib/ease\";\nimport { useCopy } from \"@/lib/hooks/use-copy\";\nimport { useStatusOpen } from \"@/lib/hooks/use-status-open\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ToolResultStatus = \"running\" | \"success\" | \"error\" | \"cancelled\";\nexport type ToolResultKind = \"terminal\" | \"request\" | \"custom\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const toolResultMessages = {\n  running: \"Running\",\n  success: \"Completed\",\n  error: \"Failed\",\n  cancelled: \"Cancelled\",\n  copy: \"Copy result\",\n  copied: \"Copied\",\n  retry: \"Run again\",\n};\n\nexport type ToolResultMessages = typeof toolResultMessages;\n\nexport interface ToolResultProps {\n  /** Tool name, shown in small monospace after the title. */\n  tool: ReactNode;\n  /** Heading in the header row, rolls to the new text when it changes. */\n  title: ReactNode;\n  children: ReactNode;\n  /** Run state, sets the status badge and auto open or fold. Default: \"running\" */\n  status?: ToolResultStatus;\n  /** Picks the header icon when no `icon` is given. Default: \"custom\" */\n  kind?: ToolResultKind;\n  /** Short muted detail after the title, e.g. a duration or count. */\n  meta?: ReactNode;\n  /** Replaces the icon chosen by `kind`. */\n  icon?: ReactNode;\n  /** Whether the output panel is open, for controlled use. */\n  open?: boolean;\n  /** Whether the output panel starts open when uncontrolled. Default: true */\n  defaultOpen?: boolean;\n  /** Called with the new open state when the panel opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /** Folds the panel when the status leaves \"running\". Default: true */\n  collapseOnComplete?: boolean;\n  /** Maximum height of the scrolling output area, in px. Default: 220 */\n  maxHeight?: number;\n  /** Text the copy button writes to the clipboard. Shows the copy button. */\n  copyText?: string;\n  /** Runs instead of the clipboard write when copy is pressed. Shows the copy button. */\n  onCopy?: () => void | Promise<void>;\n  /** Called when the retry button is pressed. Shows the retry button. */\n  onRetry?: () => void;\n  /** Override any built-in string. */\n  labels?: Partial<ToolResultMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes merged onto the padded box around the output. */\n  contentClassName?: string;\n}\n\nexport interface ToolResultOutputProps {\n  children: string;\n  /** Syntax highlighting language for the output. Default: \"bash\" */\n  language?: AgentCodeLanguage;\n  /** Classes merged onto the code element. */\n  className?: string;\n}\n\nfunction getSwapKey(value: ReactNode, fallback: string) {\n  return typeof value === \"string\" || typeof value === \"number\"\n    ? String(value)\n    : fallback;\n}\n\nfunction getStatusClass(status: ToolResultStatus) {\n  if (status === \"running\") {\n    return \"text-blue-600 dark:text-blue-400\";\n  }\n  if (status === \"success\") {\n    return \"text-emerald-600 dark:text-emerald-400\";\n  }\n  if (status === \"error\") {\n    return \"text-rose-600 dark:text-rose-400\";\n  }\n  return \"text-muted-foreground\";\n}\n\nfunction KindIcon({ kind }: { kind: ToolResultKind }) {\n  if (kind === \"terminal\") return <SquareTerminal className=\"size-4\" />;\n  if (kind === \"request\") return <Braces className=\"size-4\" />;\n  return <Wrench className=\"size-4\" />;\n}\n\nfunction StatusIcon({\n  status,\n  reduce,\n}: {\n  status: ToolResultStatus;\n  reduce: boolean;\n}) {\n  if (status === \"running\") {\n    return <LoaderCircle className={cn(\"size-3\", !reduce && \"animate-spin\")} />;\n  }\n  if (status === \"success\") return <CircleCheck className=\"size-3\" />;\n  if (status === \"error\") return <CircleX className=\"size-3\" />;\n  return <Ban className=\"size-3\" />;\n}\n\nfunction ToolResultAction({\n  label,\n  onClick,\n  children,\n}: {\n  label: string;\n  onClick: () => void;\n  children: ReactNode;\n}) {\n  const reduce = useReducedMotion() ?? false;\n\n  return (\n    <Tooltip content={label} side=\"top\">\n      <motion.button\n        type=\"button\"\n        aria-label={label}\n        onClick={onClick}\n        whileTap={reduce ? undefined : { scale: 0.95 }}\n        transition={SPRING_PRESS}\n        // A foreground tint: the output panel is already muted, so a muted\n        // hover would not show.\n        className=\"grid size-7 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n      >\n        {children}\n      </motion.button>\n    </Tooltip>\n  );\n}\n\nexport function ToolResultOutput({\n  children,\n  language = \"bash\",\n  className,\n}: ToolResultOutputProps) {\n  return (\n    <AgentCode\n      code={children}\n      language={language}\n      className={cn(\n        \"whitespace-pre-wrap break-words text-foreground/80\",\n        className,\n      )}\n    />\n  );\n}\n\nexport function ToolResult({\n  tool,\n  title,\n  children,\n  status = \"running\",\n  kind = \"custom\",\n  meta,\n  icon,\n  open,\n  defaultOpen = true,\n  onOpenChange,\n  collapseOnComplete = true,\n  maxHeight = 220,\n  copyText,\n  onCopy,\n  onRetry,\n  labels,\n  className,\n  contentClassName,\n}: ToolResultProps) {\n  const t = useMessages(\"toolResult\", toolResultMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const triggerId = `${baseId}-trigger`;\n  const contentId = `${baseId}-content`;\n  const viewportRef = useRef<HTMLDivElement>(null);\n  const { copied, copy: handleCopy } = useCopy({ text: copyText, onCopy });\n  // Opens when the tool starts running; folds when it stops, if asked to.\n  const [currentOpen, setOpen] = useStatusOpen({\n    status,\n    open,\n    defaultOpen,\n    onOpenChange,\n    decide: (previous, next) => {\n      if (previous !== \"running\" && next === \"running\") return true;\n      if (previous === \"running\" && next !== \"running\" && collapseOnComplete) return false;\n      return undefined;\n    },\n  });\n  const running = status === \"running\";\n  const canCopy = Boolean(copyText || onCopy);\n  const titleKey = getSwapKey(title, status);\n  const metaKey = getSwapKey(meta, `${status}-meta`);\n  const toolKey = getSwapKey(tool, `${status}-tool`);\n  const statusLabel = t(status);\n\n  useLayoutEffect(() => {\n    const viewport = viewportRef.current;\n    if (!viewport || !currentOpen || !running) return;\n\n    const frame = requestAnimationFrame(() => {\n      if (typeof viewport.scrollTo === \"function\") {\n        viewport.scrollTo({\n          top: viewport.scrollHeight,\n          behavior: reduce ? \"auto\" : \"smooth\",\n        });\n      } else {\n        viewport.scrollTop = viewport.scrollHeight;\n      }\n    });\n    return () => cancelAnimationFrame(frame);\n  });\n\n  return (\n    <div\n      data-state={status}\n      aria-busy={running}\n      className={cn(\"w-full text-sm\", className)}\n    >\n      <button\n        id={triggerId}\n        type=\"button\"\n        aria-expanded={currentOpen}\n        aria-controls={contentId}\n        onClick={() => setOpen(!currentOpen)}\n        className=\"group flex min-h-9 w-full items-center gap-2 rounded-full py-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\"\n      >\n        <span\n          aria-hidden=\"true\"\n          className=\"grid size-4 shrink-0 place-items-center text-muted-foreground\"\n        >\n          {icon ?? <KindIcon kind={kind} />}\n        </span>\n        <span className=\"flex min-w-0 flex-1 items-baseline gap-2\">\n          <span className=\"min-w-0 truncate font-medium text-foreground/90\">\n            <ActionSwapRollText value={titleKey}>\n              {title}\n            </ActionSwapRollText>\n          </span>\n          {meta ? (\n            <span className=\"shrink-0 text-xs text-muted-foreground/60\">\n              <ActionSwapRollText value={metaKey}>\n                {meta}\n              </ActionSwapRollText>\n            </span>\n          ) : null}\n          <span className=\"min-w-0 truncate font-mono text-[11px] text-muted-foreground/55\">\n            <ActionSwapRollText value={toolKey}>\n              {tool}\n            </ActionSwapRollText>\n          </span>\n        </span>\n        <span\n          className={cn(\n            \"inline-flex shrink-0 items-center gap-1 text-[11px] font-medium\",\n            getStatusClass(status),\n          )}\n        >\n          <IconSwap id={status}>\n            <StatusIcon status={status} reduce={reduce} />\n          </IconSwap>\n          <ActionSwapRollText value={status}>{statusLabel}</ActionSwapRollText>\n        </span>\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: currentOpen ? 180 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n          className=\"shrink-0 text-muted-foreground/50 transition-colors group-hover:text-muted-foreground\"\n        >\n          <ChevronDown className=\"size-3.5\" />\n        </motion.span>\n      </button>\n\n      <AgentDisclosure\n        id={contentId}\n        role=\"region\"\n        aria-labelledby={triggerId}\n        open={currentOpen}\n      >\n        <div className=\"pl-6 pt-1.5\">\n          <div className=\"overflow-hidden rounded-xl bg-muted/80\">\n          <div\n            ref={viewportRef}\n            role=\"log\"\n            aria-live=\"polite\"\n            className=\"scrollbar-hide overflow-y-auto\"\n            style={{ maxHeight }}\n          >\n            <div className={cn(\"p-3\", contentClassName)}>{children}</div>\n          </div>\n\n            {canCopy || onRetry ? (\n              <div className=\"flex items-center gap-0.5 px-2 pb-1.5\">\n              {canCopy ? (\n                <ToolResultAction\n                  label={copied ? t(\"copied\") : t(\"copy\")}\n                  onClick={handleCopy}\n                >\n                  <IconSwap id={copied ? \"copied\" : \"copy\"}>\n                    {copied ? (\n                      <Check className=\"size-3.5\" />\n                    ) : (\n                      <Copy className=\"size-3.5\" />\n                    )}\n                  </IconSwap>\n                </ToolResultAction>\n              ) : null}\n              {onRetry ? (\n                <ToolResultAction label={t(\"retry\")} onClick={onRetry}>\n                  <RotateCcw className=\"size-3.5\" />\n                </ToolResultAction>\n              ) : null}\n              </div>\n            ) : null}\n          </div>\n        </div>\n      </AgentDisclosure>\n    </div>\n  );\n}\n"},{"path":"components/motion/animated-sidebar.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  type HTMLMotionProps,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  type ButtonHTMLAttributes,\n  type CSSProperties,\n  forwardRef,\n  type HTMLAttributes,\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n} from \"react\";\nimport { SharedLayoutBg } from \"@/components/motion/shared-layout-bg\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  AnimatedSidebarContext,\n  AnimatedSidebarPanelContext,\n  type AnimatedSidebarMessages,\n  animatedSidebarMessages,\n  type SidebarCollapsible,\n  type SidebarSide,\n  type SidebarVariant,\n  useAnimatedSidebar,\n  useAnimatedSidebarPanel,\n} from \"./animated-sidebar/context\";\nimport { MobileSidebar } from \"./animated-sidebar/mobile-sidebar\";\nimport {\n  PANEL_TRANSITION,\n  REDUCED_TRANSITION,\n  SIDEBAR_MORPH_TRANSITION,\n  SUBMENU_ITEM_VARIANTS,\n  SUBMENU_VARIANTS,\n} from \"./animated-sidebar/motion\";\nimport { useIsMobile } from \"./animated-sidebar/use-is-mobile\";\n\nexport {\n  AnimatedSidebarMenuSubButton,\n  type AnimatedSidebarMenuSubButtonProps,\n} from \"./animated-sidebar/menu-sub-button\";\nexport {\n  AnimatedSidebarMenuButton,\n  type AnimatedSidebarMenuButtonProps,\n} from \"./animated-sidebar/menu-button\";\nexport {\n  type AnimatedSidebarMessages,\n  animatedSidebarMessages,\n  useAnimatedSidebar,\n} from \"./animated-sidebar/context\";\n\nconst SIDEBAR_KEYBOARD_SHORTCUT = \"b\";\n\ntype SidebarProviderStyle = CSSProperties & {\n  \"--sidebar-width\"?: string;\n  \"--sidebar-width-icon\"?: string;\n  \"--sidebar-width-mobile\"?: string;\n};\n\nexport interface AnimatedSidebarProviderProps\n  extends HTMLAttributes<HTMLDivElement> {\n  /** Whether the desktop sidebar is expanded, for controlled use. */\n  open?: boolean;\n  /** Whether the desktop sidebar starts expanded when uncontrolled. Default: true */\n  defaultOpen?: boolean;\n  /** Called with the next state when the desktop sidebar expands or collapses. */\n  onOpenChange?: (open: boolean) => void;\n  /** Whether the mobile drawer is open, for controlled use. */\n  openMobile?: boolean;\n  /** Whether the mobile drawer starts open when uncontrolled. Default: false */\n  defaultOpenMobile?: boolean;\n  /** Called with the next state when the mobile drawer opens or closes. */\n  onOpenMobileChange?: (open: boolean) => void;\n  /** Inline styles; set `--sidebar-width`, `--sidebar-width-icon` or `--sidebar-width-mobile` here. */\n  style?: SidebarProviderStyle;\n  /** Override any built-in string. */\n  labels?: Partial<AnimatedSidebarMessages>;\n}\n\nexport function AnimatedSidebarProvider({\n  children,\n  open,\n  defaultOpen = true,\n  onOpenChange,\n  openMobile,\n  defaultOpenMobile = false,\n  onOpenMobileChange,\n  className,\n  style,\n  labels,\n  ...props\n}: AnimatedSidebarProviderProps) {\n  const t = useMessages(\"animatedSidebar\", animatedSidebarMessages, labels);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const [internalOpenMobile, setInternalOpenMobile] =\n    useState(defaultOpenMobile);\n  const isMobile = useIsMobile();\n  const reduce = useReducedMotion() ?? false;\n  const generatedId = useId();\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  const desktopOpen = open ?? internalOpen;\n  const mobileOpen = openMobile ?? internalOpenMobile;\n\n  const setOpen = useCallback(\n    (nextOpen: boolean) => {\n      if (open === undefined) setInternalOpen(nextOpen);\n      onOpenChange?.(nextOpen);\n    },\n    [onOpenChange, open],\n  );\n\n  const setOpenMobile = useCallback(\n    (nextOpen: boolean) => {\n      if (openMobile === undefined) setInternalOpenMobile(nextOpen);\n      onOpenMobileChange?.(nextOpen);\n    },\n    [onOpenMobileChange, openMobile],\n  );\n\n  const toggleSidebar = useCallback(() => {\n    if (isMobile) setOpenMobile(!mobileOpen);\n    else setOpen(!desktopOpen);\n  }, [desktopOpen, isMobile, mobileOpen, setOpen, setOpenMobile]);\n\n  useEffect(() => {\n    const handleShortcut = (event: KeyboardEvent) => {\n      if (\n        event.key.toLowerCase() === SIDEBAR_KEYBOARD_SHORTCUT &&\n        (event.metaKey || event.ctrlKey)\n      ) {\n        event.preventDefault();\n        toggleSidebar();\n      }\n    };\n\n    window.addEventListener(\"keydown\", handleShortcut);\n    return () => window.removeEventListener(\"keydown\", handleShortcut);\n  }, [toggleSidebar]);\n\n  return (\n    <AnimatedSidebarContext.Provider\n      value={{\n        isMobile,\n        layoutId: `${generatedId}-active`,\n        open: desktopOpen,\n        openMobile: mobileOpen,\n        reduce,\n        setOpen,\n        setOpenMobile,\n        state: desktopOpen ? \"expanded\" : \"collapsed\",\n        toggleSidebar,\n        triggerRef,\n        t,\n      }}\n    >\n      <div\n        {...props}\n        data-slot=\"sidebar-wrapper\"\n        data-state={desktopOpen ? \"expanded\" : \"collapsed\"}\n        style={{\n          \"--sidebar-width\": \"16rem\",\n          \"--sidebar-width-icon\": \"4.25rem\",\n          \"--sidebar-width-mobile\": \"18rem\",\n          ...style,\n        }}\n        className={cn(\n          \"group/sidebar-wrapper flex min-h-svh w-full min-w-0\",\n          className,\n        )}\n      >\n        {children}\n      </div>\n    </AnimatedSidebarContext.Provider>\n  );\n}\n\nexport interface AnimatedSidebarProps\n  extends Omit<HTMLMotionProps<\"aside\">, \"children\"> {\n  children?: ReactNode;\n  /** Which edge of the layout the sidebar sits on. Default: \"left\" */\n  side?: SidebarSide;\n  /** Panel style: bordered edge, floating card, or inset card. Default: \"sidebar\" */\n  variant?: SidebarVariant;\n  /** How it collapses: to an icon rail, fully off canvas, or never. Default: \"icon\" */\n  collapsible?: SidebarCollapsible;\n  /** Accessible name for the sidebar landmark. Default: \"Sidebar\" */\n  ariaLabel?: string;\n  /** Classes merged onto the inner panel that holds the content. */\n  panelClassName?: string;\n}\n\nexport const AnimatedSidebar = forwardRef<HTMLElement, AnimatedSidebarProps>(\n  function AnimatedSidebar(\n    {\n      side = \"left\",\n      variant = \"sidebar\",\n      collapsible = \"icon\",\n      ariaLabel: ariaLabelProp,\n      children,\n      className,\n      panelClassName,\n      style,\n      ...props\n    },\n    forwardedRef,\n  ) {\n    const context = useAnimatedSidebar();\n    const ariaLabel = ariaLabelProp ?? context.t(\"label\");\n    const collapsed = collapsible !== \"none\" && !context.open;\n    const offcanvas = collapsed && collapsible === \"offcanvas\";\n    const width = offcanvas\n      ? \"0px\"\n      : collapsed\n        ? \"var(--sidebar-width-icon)\"\n        : \"var(--sidebar-width)\";\n\n    if (context.isMobile) {\n      return (\n        <MobileSidebar\n          ariaLabel={ariaLabel}\n          className={className}\n          side={side}\n        >\n          {children}\n        </MobileSidebar>\n      );\n    }\n\n    return (\n      <motion.aside\n        {...props}\n        ref={forwardedRef}\n        initial={false}\n        aria-label={ariaLabel}\n        data-slot=\"sidebar\"\n        data-state={collapsed ? \"collapsed\" : \"expanded\"}\n        data-collapsible={collapsible}\n        data-variant={variant}\n        data-side={side}\n        animate={{ width }}\n        transition={\n          context.reduce ? { duration: 0 } : SIDEBAR_MORPH_TRANSITION\n        }\n        style={style}\n        className={cn(\n          \"group/sidebar relative hidden h-auto shrink-0 md:block will-change-[width]\",\n          \"peer\",\n          side === \"right\" && \"order-last\",\n          className,\n        )}\n      >\n        <motion.div\n          initial={false}\n          animate={{\n            opacity: offcanvas ? 0 : 1,\n            x: offcanvas ? (side === \"left\" ? \"-100%\" : \"100%\") : \"0%\",\n          }}\n          transition={\n            context.reduce ? REDUCED_TRANSITION : PANEL_TRANSITION\n          }\n          className={cn(\n            \"sticky top-0 flex h-svh w-full flex-col overflow-hidden bg-background\",\n            collapsible === \"offcanvas\" && \"w-[var(--sidebar-width)]\",\n            variant === \"sidebar\" &&\n              (side === \"left\" ? \"border-border border-r\" : \"border-border border-l\"),\n            variant === \"floating\" &&\n              \"m-2 h-[calc(100svh-1rem)] rounded-2xl border border-border shadow-sm\",\n            variant === \"inset\" && \"m-2 h-[calc(100svh-1rem)] rounded-2xl\",\n            panelClassName,\n          )}\n        >\n          <AnimatedSidebarPanelContext.Provider\n            value={{ collapsed, collapsible, side }}\n          >\n            {children}\n          </AnimatedSidebarPanelContext.Provider>\n        </motion.div>\n      </motion.aside>\n    );\n  },\n);\n\nexport interface AnimatedSidebarTriggerProps\n  extends ButtonHTMLAttributes<HTMLButtonElement> {}\n\nexport const AnimatedSidebarTrigger = forwardRef<\n  HTMLButtonElement,\n  AnimatedSidebarTriggerProps\n>(function AnimatedSidebarTrigger(\n  { className, onClick, type = \"button\", ...props },\n  forwardedRef,\n) {\n  const context = useAnimatedSidebar();\n  const expanded = context.isMobile ? context.openMobile : context.open;\n\n  return (\n    <button\n      {...props}\n      ref={(node) => {\n        context.triggerRef.current = node;\n        if (typeof forwardedRef === \"function\") forwardedRef(node);\n        else if (forwardedRef) forwardedRef.current = node;\n      }}\n      type={type}\n      aria-label={props[\"aria-label\"] ?? context.t(\"toggle\")}\n      aria-expanded={expanded}\n      data-slot=\"sidebar-trigger\"\n      data-state={expanded ? \"expanded\" : \"collapsed\"}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) context.toggleSidebar();\n      }}\n      className={cn(\n        \"inline-flex size-10 shrink-0 items-center justify-center rounded-full outline-none\",\n        \"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n        className,\n      )}\n    />\n  );\n});\n\nexport interface AnimatedSidebarCloseProps\n  extends ButtonHTMLAttributes<HTMLButtonElement> {}\n\nexport const AnimatedSidebarClose = forwardRef<\n  HTMLButtonElement,\n  AnimatedSidebarCloseProps\n>(function AnimatedSidebarClose(\n  { className, onClick, type = \"button\", ...props },\n  forwardedRef,\n) {\n  const context = useAnimatedSidebar();\n\n  return (\n    <button\n      {...props}\n      ref={forwardedRef}\n      type={type}\n      aria-label={props[\"aria-label\"] ?? context.t(\"close\")}\n      onClick={(event) => {\n        onClick?.(event);\n        if (event.defaultPrevented) return;\n        if (context.isMobile) context.setOpenMobile(false);\n        else context.setOpen(false);\n      }}\n      className={cn(\n        \"inline-flex size-10 shrink-0 items-center justify-center rounded-full outline-none\",\n        \"focus-visible:ring-2 focus-visible:ring-ring\",\n        className,\n      )}\n    />\n  );\n});\n\nexport interface AnimatedSidebarRailProps\n  extends ButtonHTMLAttributes<HTMLButtonElement> {}\n\nexport const AnimatedSidebarRail = forwardRef<\n  HTMLButtonElement,\n  AnimatedSidebarRailProps\n>(function AnimatedSidebarRail(\n  { className, onClick, type = \"button\", ...props },\n  forwardedRef,\n) {\n  const context = useAnimatedSidebar();\n  const panel = useAnimatedSidebarPanel();\n\n  return (\n    <button\n      {...props}\n      ref={forwardedRef}\n      type={type}\n      data-side={panel.side}\n      aria-label={props[\"aria-label\"] ?? context.t(\"toggle\")}\n      title={context.t(\"toggle\")}\n      tabIndex={-1}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) context.toggleSidebar();\n      }}\n      className={cn(\n        \"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 outline-none md:block\",\n        \"after:absolute after:inset-y-0 after:left-1/2 after:w-px after:bg-transparent after:transition-colors hover:after:bg-border\",\n        \"data-[side=right]:right-0 data-[side=right]:translate-x-1/2 data-[side=left]:left-full\",\n        className,\n      )}\n    />\n  );\n});\n\nexport interface AnimatedSidebarInsetProps\n  extends HTMLMotionProps<\"main\"> {}\n\nexport const AnimatedSidebarInset = forwardRef<\n  HTMLElement,\n  AnimatedSidebarInsetProps\n>(function AnimatedSidebarInset({ className, ...props }, forwardedRef) {\n  return (\n    <motion.main\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-inset\"\n      className={cn(\n        \"relative flex min-h-svh min-w-0 flex-1 flex-col bg-background\",\n        \"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-2xl md:peer-data-[variant=inset]:shadow-sm\",\n        className,\n      )}\n    />\n  );\n});\n\nexport const AnimatedSidebarHeader = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarHeader({ className, ...props }, forwardedRef) {\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-header\"\n      className={cn(\"flex shrink-0 flex-col gap-2 p-3\", className)}\n    />\n  );\n});\n\nexport const AnimatedSidebarContent = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarContent({ className, ...props }, forwardedRef) {\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-content\"\n      className={cn(\n        \"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto overflow-x-hidden overscroll-contain px-2 py-2\",\n        className,\n      )}\n    />\n  );\n});\n\nexport const AnimatedSidebarFooter = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarFooter({ className, ...props }, forwardedRef) {\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-footer\"\n      className={cn(\n        \"flex shrink-0 flex-col gap-2 border-border border-t p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]\",\n        className,\n      )}\n    />\n  );\n});\n\nexport const AnimatedSidebarGroup = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarGroup({ className, ...props }, forwardedRef) {\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-group\"\n      className={cn(\"flex w-full min-w-0 flex-col px-1 py-1.5\", className)}\n    />\n  );\n});\n\nexport const AnimatedSidebarGroupLabel = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarGroupLabel(\n  { children, className, ...props },\n  forwardedRef,\n) {\n  const { collapsed } = useAnimatedSidebarPanel();\n\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      aria-hidden={collapsed}\n      data-slot=\"sidebar-group-label\"\n      className={cn(\n        \"mb-1 h-7 overflow-hidden px-2 text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground transition-opacity\",\n        collapsed ? \"opacity-0\" : \"opacity-100\",\n        className,\n      )}\n    >\n      {children}\n    </div>\n  );\n});\n\nexport const AnimatedSidebarGroupContent = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarGroupContent(\n  { className, ...props },\n  forwardedRef,\n) {\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-group-content\"\n      className={cn(\"w-full min-w-0\", className)}\n    />\n  );\n});\n\nexport const AnimatedSidebarMenu = forwardRef<\n  HTMLUListElement,\n  HTMLAttributes<HTMLUListElement>\n>(function AnimatedSidebarMenu(\n  { children, className, ...props },\n  forwardedRef,\n) {\n  return (\n    <SharedLayoutBg\n      {...props}\n      ref={forwardedRef as React.Ref<HTMLElement>}\n      as=\"ul\"\n      inset={0}\n      pillClassName=\"rounded-full bg-muted/70\"\n      pillContainerClassName=\"inset-y-auto top-0 h-9\"\n      data-slot=\"sidebar-menu\"\n      className={cn(\"flex w-full min-w-0 list-none flex-col gap-0.5\", className)}\n    >\n      {children}\n    </SharedLayoutBg>\n  );\n});\n\nexport const AnimatedSidebarMenuItem = forwardRef<\n  HTMLLIElement,\n  HTMLMotionProps<\"li\">\n>(function AnimatedSidebarMenuItem({ className, ...props }, forwardedRef) {\n  return (\n    <motion.li\n      {...props}\n      ref={forwardedRef}\n      layout=\"position\"\n      transition={SPRING_LAYOUT}\n      data-slot=\"sidebar-menu-item\"\n      className={cn(\"relative\", className)}\n    />\n  );\n});\n\nexport interface AnimatedSidebarMenuSubProps\n  extends Omit<HTMLMotionProps<\"ul\">, \"children\"> {\n  /** Shows the submenu. It stays hidden while the sidebar is collapsed. */\n  open: boolean;\n  children?: ReactNode;\n}\n\nexport const AnimatedSidebarMenuSub = forwardRef<\n  HTMLUListElement,\n  AnimatedSidebarMenuSubProps\n>(function AnimatedSidebarMenuSub(\n  { open, children, className, ...props },\n  forwardedRef,\n) {\n  const context = useAnimatedSidebar();\n  const panel = useAnimatedSidebarPanel();\n\n  return (\n    <AnimatePresence initial={false} mode=\"popLayout\">\n      {open && !panel.collapsed ? (\n        <motion.ul\n          {...props}\n          ref={forwardedRef}\n          key=\"sidebar-submenu\"\n          variants={context.reduce ? undefined : SUBMENU_VARIANTS}\n          initial={context.reduce ? false : \"closed\"}\n          animate={context.reduce ? { opacity: 1 } : \"open\"}\n          exit={context.reduce ? { opacity: 0 } : \"closed\"}\n          transition={context.reduce ? { duration: 0.12 } : undefined}\n          data-slot=\"sidebar-menu-sub\"\n          className={cn(\n            \"relative mt-1 ml-5 flex min-w-0 flex-col gap-0.5 border-border border-l pl-3\",\n            className,\n          )}\n        >\n          {children}\n        </motion.ul>\n      ) : null}\n    </AnimatePresence>\n  );\n});\n\nexport const AnimatedSidebarMenuSubItem = forwardRef<\n  HTMLLIElement,\n  HTMLMotionProps<\"li\">\n>(function AnimatedSidebarMenuSubItem(\n  { className, ...props },\n  forwardedRef,\n) {\n  return (\n    <motion.li\n      {...props}\n      ref={forwardedRef}\n      variants={SUBMENU_ITEM_VARIANTS}\n      data-slot=\"sidebar-menu-sub-item\"\n      className={cn(\"relative min-w-0\", className)}\n    />\n  );\n});\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"components/agents/agent-activity/activity-row.tsx","type":"util","content":"import {\n  Brain,\n  Check,\n  Circle,\n  FileText,\n  Globe2,\n  ImageIcon,\n  MessageSquare,\n  PencilLine,\n  Search,\n  SquareTerminal,\n  Wrench,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { IconSwap } from \"@/components/agents/icon-swap\";\nimport { EASE_OUT, SPRING_LAYOUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport type { AgentActivityTranslate } from \"./messages\";\nimport type {\n  AgentActivityItem,\n  AgentActivitySearch,\n  AgentActivityStep,\n  AgentActivityText,\n  AgentActivityTool,\n  AgentActivityTrace,\n  AgentSearchResult,\n} from \"./types\";\n\nfunction StepRow({ item }: { item: AgentActivityStep }) {\n  const state = item.status ?? \"complete\";\n\n  return (\n    <div className=\"flex min-h-7 items-start gap-2.5 rounded-md px-1.5 py-1\">\n      {/* The marker morphs as the step moves on: a finished step's dot\n          blurs into its check rather than snapping. */}\n      <span\n        aria-hidden=\"true\"\n        className=\"relative mt-0.5 grid size-4 shrink-0 place-items-center text-muted-foreground/70\"\n      >\n        <IconSwap id={state}>\n            {state === \"complete\" ? (\n              <Check className=\"size-4\" strokeWidth={1.8} />\n            ) : state === \"active\" ? (\n              <span className=\"relative grid size-3 place-items-center\">\n                <motion.span\n                  className=\"absolute inset-0 rounded-full bg-foreground/10\"\n                  animate={{ opacity: [0.35, 0.8, 0.35] }}\n                  transition={{ duration: 1.5, ease: \"easeInOut\", repeat: Number.POSITIVE_INFINITY }}\n                />\n                <span className=\"size-1.5 rounded-full bg-foreground/60\" />\n              </span>\n            ) : (\n              <Circle className=\"size-3\" strokeWidth={1.5} />\n            )}\n        </IconSwap>\n      </span>\n      <span\n        className={cn(\n          \"min-w-0 flex-1 leading-5\",\n          state === \"pending\" ? \"text-muted-foreground/55\" : \"text-foreground/90\",\n        )}\n      >\n        {item.label}\n      </span>\n      {item.meta ? (\n        <span className=\"shrink-0 leading-5 text-muted-foreground/55\">\n          {item.meta}\n        </span>\n      ) : null}\n    </div>\n  );\n}\n\nfunction TextRow({ item }: { item: AgentActivityText }) {\n  return (\n    <div className=\"rounded-md px-1.5 py-1 leading-5 text-muted-foreground\">\n      {item.content}\n    </div>\n  );\n}\n\nfunction SearchResultRow({\n  result,\n}: {\n  result: AgentSearchResult;\n}) {\n  const content = (\n    <>\n      <span\n        aria-hidden=\"true\"\n        className=\"grid size-5 shrink-0 place-items-center text-muted-foreground\"\n      >\n        {result.icon ?? <Globe2 className=\"size-3\" strokeWidth={2} />}\n      </span>\n      <span className=\"min-w-0 truncate font-medium text-foreground/90\">\n        {result.title}\n      </span>\n      {result.domain ? (\n        <span className=\"min-w-0 truncate text-muted-foreground/55\">\n          {result.domain}\n        </span>\n      ) : null}\n    </>\n  );\n  const className = cn(\n    \"flex min-h-7 items-center gap-2 rounded-md px-1.5 py-1 text-left outline-none transition-colors\",\n    result.url && \"hover:bg-foreground/[0.04] focus-visible:ring-2 focus-visible:ring-ring\",\n  );\n\n  return result.url ? (\n    <a href={result.url} className={className}>\n      {content}\n    </a>\n  ) : (\n    <div className={className}>{content}</div>\n  );\n}\n\nfunction SearchRow({\n  item,\n  t,\n}: {\n  item: AgentActivitySearch;\n  t: AgentActivityTranslate;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  const enter = reduce ? { opacity: 1 } : { opacity: 0, y: 6 };\n  const visible = { opacity: 1, y: 0 };\n  const exit = reduce ? { opacity: 0 } : { opacity: 0, y: -3 };\n  const transition = reduce\n    ? { duration: 0 }\n    : {\n        opacity: { duration: 0.18, ease: EASE_OUT },\n        y: SPRING_LAYOUT,\n        layout: SPRING_LAYOUT,\n      };\n\n  return (\n    <div className=\"space-y-0.5\">\n      <div className=\"flex min-h-7 items-center gap-2.5 rounded-md px-1.5 py-1 text-muted-foreground\">\n        <Search aria-hidden=\"true\" className=\"size-4 shrink-0\" strokeWidth={1.7} />\n        <span className=\"min-w-0 truncate\">{item.query}</span>\n      </div>\n      {item.results?.length ? (\n        <div className=\"space-y-0.5 pl-4\">\n          <AnimatePresence initial mode=\"popLayout\">\n            {item.results.map((result) => (\n              <motion.div\n                layout=\"position\"\n                key={result.id}\n                initial={enter}\n                animate={visible}\n                exit={exit}\n                transition={transition}\n              >\n                <SearchResultRow result={result} />\n              </motion.div>\n            ))}\n          </AnimatePresence>\n        </div>\n      ) : null}\n      <AnimatePresence initial>\n        {item.moreCount ? (\n          <motion.div\n            key=\"more-results\"\n            initial={enter}\n            animate={visible}\n            exit={exit}\n            transition={transition}\n            className=\"px-1.5 py-1 pl-8 text-muted-foreground/55\"\n          >\n            {t(\"moreResults\", { count: item.moreCount })}\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nfunction ActionIcon({ action }: { action: string }) {\n  if (action === \"read\") return <FileText className=\"size-4\" />;\n  if (action === \"edit\" || action === \"write\") {\n    return <PencilLine className=\"size-4\" />;\n  }\n  if (action === \"run\") return <SquareTerminal className=\"size-4\" />;\n  return <Wrench className=\"size-4\" />;\n}\n\nconst KNOWN_ACTIONS = [\"read\", \"edit\", \"write\", \"run\"] as const;\n\nfunction ToolRow({\n  item,\n  t,\n}: {\n  item: AgentActivityTool;\n  t: AgentActivityTranslate;\n}) {\n  const known = KNOWN_ACTIONS.find((action) => action === item.action);\n  const action = known\n    ? t(known)\n    : item.action.charAt(0).toUpperCase() + item.action.slice(1);\n\n  return (\n    <div className=\"flex min-h-8 min-w-0 items-center gap-2.5 rounded-md px-1.5 py-0.5 leading-5\">\n      <span\n        aria-hidden=\"true\"\n        className=\"grid size-4 shrink-0 place-items-center text-muted-foreground/70\"\n      >\n        <ActionIcon action={item.action} />\n      </span>\n      <span className=\"shrink-0 font-medium text-foreground/90\">{action}</span>\n      <span className=\"min-w-0 flex-1 truncate rounded-full bg-muted/80 px-2.5 py-1 font-mono text-xs text-muted-foreground/70\">\n        {item.target}\n      </span>\n      {typeof item.additions === \"number\" || typeof item.deletions === \"number\" ? (\n        <span className=\"flex shrink-0 items-center gap-2 font-mono tabular-nums\">\n          {typeof item.additions === \"number\" ? (\n            <span className=\"text-emerald-500\">+{item.additions}</span>\n          ) : null}\n          {typeof item.deletions === \"number\" ? (\n            <span className=\"text-rose-500\">−{item.deletions}</span>\n          ) : null}\n        </span>\n      ) : null}\n    </div>\n  );\n}\n\nfunction TraceIcon({ kind }: { kind: AgentActivityTrace[\"kind\"] }) {\n  if (kind === \"thinking\") return <Brain className=\"size-4\" />;\n  if (kind === \"message\") return <MessageSquare className=\"size-4\" />;\n  if (kind === \"write\") return <PencilLine className=\"size-4\" />;\n  if (kind === \"run\") return <SquareTerminal className=\"size-4\" />;\n  if (kind === \"read\") return <ImageIcon className=\"size-4\" />;\n  return <Wrench className=\"size-4\" />;\n}\n\nfunction TraceRow({ item }: { item: AgentActivityTrace }) {\n  return (\n    <div className=\"grid min-h-8 grid-cols-[1rem_auto_minmax(0,1fr)] items-center gap-2.5 rounded-md px-1.5 py-0.5\">\n      <span\n        aria-hidden=\"true\"\n        className=\"grid size-4 place-items-center text-muted-foreground/70\"\n      >\n        {item.icon ?? <TraceIcon kind={item.kind} />}\n      </span>\n      <span className=\"font-medium text-foreground/90\">{item.label}</span>\n      {item.detail ? (\n        <span className=\"min-w-0 truncate rounded-full bg-muted/80 px-2.5 py-1 font-mono text-xs text-muted-foreground/70\">\n          {item.detail}\n        </span>\n      ) : (\n        <span />\n      )}\n    </div>\n  );\n}\n\nexport function ActivityRow({\n  item,\n  t,\n}: {\n  item: AgentActivityItem;\n  t: AgentActivityTranslate;\n}) {\n  if (item.type === \"text\") return <TextRow item={item} />;\n  if (item.type === \"search\") return <SearchRow item={item} t={t} />;\n  if (item.type === \"tool\") return <ToolRow item={item} t={t} />;\n  if (item.type === \"trace\") return <TraceRow item={item} />;\n  return <StepRow item={item} />;\n}\n"},{"path":"components/agents/agent-activity/messages.ts","type":"util","content":"/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const agentActivityMessages = {\n  thinking: \"Thinking…\",\n  searching: \"Searching the web…\",\n  runningTools: \"Running tools…\",\n  workingTrace: \"Working through the run…\",\n  workingMixed: \"Working through it…\",\n  thoughtFor: \"Thought for {duration}\",\n  seconds: \"{seconds}s\",\n  minutes: \"{minutes}m\",\n  minutesSeconds: \"{minutes}m {seconds}s\",\n  searched: \"Searched the web\",\n  ranToolsOne: \"Ran {count} tool\",\n  ranToolsOther: \"Ran {count} tools\",\n  traceSummary: \"{toolCalls}, {messages}\",\n  toolCallsOne: \"{count} tool call\",\n  toolCallsOther: \"{count} tool calls\",\n  messagesOne: \"{count} message\",\n  messagesOther: \"{count} messages\",\n  completedStepsOne: \"Completed {count} step\",\n  completedStepsOther: \"Completed {count} steps\",\n  moreResults: \"+{count} more\",\n  read: \"Read\",\n  edit: \"Edit\",\n  write: \"Write\",\n  run: \"Run\",\n};\n\nexport type AgentActivityMessages = typeof agentActivityMessages;\n\nexport type AgentActivityTranslate = (\n  key: keyof AgentActivityMessages,\n  values?: Record<string, string | number>,\n) => string;\n"},{"path":"components/agents/agent-activity/types.ts","type":"util","content":"import type { ReactNode } from \"react\";\nimport type { AgentActivityMessages } from \"./messages\";\n\nexport type AgentActivityStatus = \"working\" | \"complete\";\nexport type AgentStepStatus = \"pending\" | \"active\" | \"complete\";\n\nexport interface AgentActivityStep {\n  id: string;\n  type: \"step\";\n  label: ReactNode;\n  status?: AgentStepStatus;\n  meta?: ReactNode;\n}\n\nexport interface AgentActivityText {\n  id: string;\n  type: \"text\";\n  content: ReactNode;\n}\n\nexport interface AgentSearchResult {\n  id: string;\n  title: ReactNode;\n  domain?: ReactNode;\n  url?: string;\n  icon?: ReactNode;\n}\n\nexport interface AgentActivitySearch {\n  id: string;\n  type: \"search\";\n  query: ReactNode;\n  results?: AgentSearchResult[];\n  moreCount?: number;\n}\n\nexport interface AgentActivityTool {\n  id: string;\n  type: \"tool\";\n  action: \"read\" | \"edit\" | \"run\" | (string & {});\n  target: ReactNode;\n  additions?: number;\n  deletions?: number;\n}\n\nexport type AgentTraceKind =\n  | \"thinking\"\n  | \"message\"\n  | \"write\"\n  | \"run\"\n  | \"read\"\n  | (string & {});\n\nexport interface AgentActivityTrace {\n  id: string;\n  type: \"trace\";\n  kind: AgentTraceKind;\n  label: ReactNode;\n  detail?: ReactNode;\n  icon?: ReactNode;\n}\n\nexport type AgentActivityItem =\n  | AgentActivityStep\n  | AgentActivityText\n  | AgentActivitySearch\n  | AgentActivityTool\n  | AgentActivityTrace;\n\nexport type AgentActivityContentType = AgentActivityItem[\"type\"] | \"mixed\";\n\nexport interface AgentActivityProps {\n  /** Chronological activity entries. Append or update items as events stream. */\n  items: AgentActivityItem[];\n  /** Expected activity kind before the first streamed item arrives. */\n  contentType?: AgentActivityContentType;\n  /** Current run phase. Active runs always stay expanded. */\n  status?: AgentActivityStatus;\n  /** Elapsed run time, in seconds. Used by the step-only summary. */\n  duration?: number;\n  /** Controlled expanded state used after the run completes. */\n  open?: boolean;\n  /** Initial expanded state used after the run completes. */\n  defaultOpen?: boolean;\n  /** Called when the completed activity disclosure changes state. */\n  onOpenChange?: (open: boolean) => void;\n  /** Collapse the disclosure when status changes from working to complete. */\n  collapseOnComplete?: boolean;\n  /** Optional label shown while the run is active. */\n  activeLabel?: ReactNode;\n  /** Optional completed summary. Derived from the item types by default. */\n  summary?: ReactNode;\n  /** Optional renderer for the contents of the active status row. */\n  renderWorkingStatus?: (context: {\n    label: ReactNode;\n    duration: number;\n  }) => ReactNode;\n  /** Optional renderer for the contents before the built-in disclosure chevron. */\n  renderCompletedStatus?: (context: {\n    summary: ReactNode;\n    duration: number;\n  }) => ReactNode;\n  /** Maximum visible activity height before the stream begins gliding. */\n  maxHeight?: number;\n  /** Override any built-in string. Pick `One`/`Other` keys by count; `{count}`, `{duration}`, `{seconds}` and `{minutes}` fill the matching messages. */\n  labels?: Partial<AgentActivityMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes merged onto the list of activity items. */\n  contentClassName?: string;\n}\n"},{"path":"components/agents/agent-disclosure.tsx","type":"util","content":"\"use client\";\n\nimport { motion, type HTMLMotionProps, useReducedMotion } from \"motion/react\";\nimport { type CSSProperties, useState } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface AgentDisclosureProps\n  extends Omit<HTMLMotionProps<\"div\">, \"animate\" | \"initial\"> {\n  open: boolean;\n  openHeight?: CSSProperties[\"height\"];\n}\n\n/**\n * Shared reveal for collapsible agent content: a clip, fade and short drop,\n * never an animated height. The box takes its height as soon as it opens and\n * gives it up only once the closing reveal has played, so the exit is seen\n * and mirrors the entrance.\n */\nexport function AgentDisclosure({\n  open,\n  openHeight = \"auto\",\n  className,\n  style,\n  transition,\n  onAnimationComplete,\n  ...props\n}: AgentDisclosureProps) {\n  const reduce = useReducedMotion() ?? false;\n  const [collapsed, setCollapsed] = useState(!open);\n  if (open && collapsed) setCollapsed(false);\n\n  return (\n    <motion.div\n      {...props}\n      aria-hidden={!open}\n      inert={!open}\n      initial={false}\n      animate={\n        reduce\n          ? { opacity: open ? 1 : 0 }\n          : {\n              opacity: open ? 1 : 0,\n              clipPath: open ? \"inset(0 0 0% 0)\" : \"inset(0 0 100% 0)\",\n              y: open ? 0 : -4,\n            }\n      }\n      transition={\n        transition ?? {\n          duration: reduce ? 0 : open ? 0.22 : 0.14,\n          ease: EASE_OUT,\n        }\n      }\n      onAnimationComplete={(definition) => {\n        if (!open) setCollapsed(true);\n        onAnimationComplete?.(definition);\n      }}\n      className={cn(\"overflow-hidden\", className)}\n      style={{\n        ...style,\n        height: collapsed ? 0 : openHeight,\n        pointerEvents: open ? undefined : \"none\",\n        transformOrigin: \"top\",\n      }}\n    />\n  );\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps - label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances - modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides - pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/hooks/use-status-open.ts","type":"util","content":"\"use client\";\n\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport { useControllable } from \"@/lib/hooks/use-controllable\";\n\n/**\n * Open state for a disclosure that opens or closes itself when a status\n * changes: a tool result that opens while it runs, a todo list that folds\n * when the work completes. Controlled through `open`, or uncontrolled from\n * `defaultOpen`.\n *\n * `decide(previous, next)` runs in the render that first sees a new status\n * and returns `true` to open, `false` to close, or `undefined` to leave it.\n * An uncontrolled panel flips in that same render, so it never shows one\n * commit in the old state. Telling the consumer through `onOpenChange` is a\n * side effect, so it waits for the commit.\n */\nexport function useStatusOpen<Status>({\n  status,\n  initialStatus = status,\n  decide,\n  open,\n  defaultOpen,\n  onOpenChange,\n}: {\n  status: Status;\n  /**\n   * The status to treat as already seen at mount. Defaults to `status`, so\n   * mounting is not a change; pass another value to let the first render\n   * count as one.\n   */\n  initialStatus?: Status;\n  decide: (previous: Status, next: Status) => boolean | undefined;\n  open?: boolean;\n  defaultOpen: boolean;\n  onOpenChange?: (open: boolean) => void;\n}) {\n  const [currentOpen, setOpen, setInternal] = useControllable(open, defaultOpen, onOpenChange);\n  const [seenStatus, setSeenStatus] = useState(initialStatus);\n  const [request, setRequest] = useState<{ open: boolean; from: boolean } | null>(null);\n\n  if (status !== seenStatus) {\n    setSeenStatus(status);\n    const wanted = decide(seenStatus, status);\n    if (wanted !== undefined) {\n      if (open === undefined) setInternal(wanted);\n      setRequest({ open: wanted, from: currentOpen });\n    }\n  }\n\n  const notify = useRef(onOpenChange);\n  useLayoutEffect(() => {\n    notify.current = onOpenChange;\n  });\n  useEffect(() => {\n    if (request && request.open !== request.from) notify.current?.(request.open);\n  }, [request]);\n\n  return [currentOpen, setOpen] as const;\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"components/agents/ai-sidebar/messages.ts","type":"util","content":"export const aiSidebarMessages = {\n  label: \"Resources\",\n  rename: \"Rename\",\n  renameItem: \"Rename {item}\",\n  actions: \"Actions for {item}\",\n  moveUp: \"Move up\",\n  moveDown: \"Move down\",\n  moveInto: \"Move into {target}\",\n  moveOut: \"Move out\",\n  moveToTop: \"Move to top level\",\n  movePending: \"Wait for the current move to finish.\",\n  movedBefore: \"Moved {item} before {target}.\",\n  movedInside: \"Moved {item} inside {target}.\",\n  movedAfter: \"Moved {item} after {target}.\",\n  movedToTop: \"Moved {item} to the top level.\",\n  moveFailed: \"Move failed. {item} was restored.\",\n  renameFailed: \"Rename failed. {item} was restored.\",\n  unnamedItem: \"item\",\n};\n\nexport type AISidebarMessages = typeof aiSidebarMessages;\n\nexport type Translate = (\n  key: keyof AISidebarMessages,\n  values?: Record<string, string | number>,\n) => string;\n"},{"path":"components/agents/ai-sidebar/resource-row.tsx","type":"util","content":"\"use client\";\n\nimport {\n  ArrowDown,\n  ArrowUp,\n  Bookmark,\n  FileText,\n  Folder,\n  FolderInput,\n  FolderOpen,\n  MoreHorizontal,\n  Pencil,\n  Undo2,\n} from \"lucide-react\";\nimport { motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type DragEvent,\n  type KeyboardEvent,\n  type ReactNode,\n  useEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport {\n  MorphPopover,\n  MorphPopoverContent,\n  MorphPopoverTrigger,\n} from \"@/components/motion/popover-morph\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { useTouchCapable } from \"@/lib/hooks/use-touch-capable\";\nimport { cn } from \"@/lib/utils\";\nimport { MarqueeLabel } from \"./marquee-label\";\nimport type { Translate } from \"./messages\";\nimport { ResourceMenuAction } from \"./resource-menu-action\";\nimport { canContain } from \"./tree\";\nimport type {\n  AISidebarProps,\n  DropTarget,\n  FlatResource,\n  SidebarResource,\n  SidebarResourceMoveCommands,\n} from \"./types\";\n\nfunction defaultIcon(item: SidebarResource, expanded: boolean) {\n  const Icon =\n    item.kind === \"folder\" || item.kind === \"project\"\n      ? expanded\n        ? FolderOpen\n        : Folder\n      : item.kind === \"bookmark\"\n          ? Bookmark\n          : FileText;\n  return <Icon className=\"size-4\" />;\n}\n\ninterface ResourceRowProps {\n  row: FlatResource;\n  active: boolean;\n  expanded: boolean;\n  focused: boolean;\n  draggingId: string | null;\n  dropTarget: DropTarget | null;\n  menuOpen: boolean;\n  moves: SidebarResourceMoveCommands;\n  renaming: boolean;\n  onDragEnd: () => void;\n  onDragOver: (event: DragEvent<HTMLDivElement>, row: FlatResource) => void;\n  onDragStart: (event: DragEvent<HTMLDivElement>, id: string) => void;\n  onDrop: (event: DragEvent<HTMLDivElement>) => void;\n  onFocus: () => void;\n  onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void;\n  onMenuOpenChange: (open: boolean) => void;\n  onRenameCancel: () => void;\n  onRenameCommit: (label: string) => void;\n  onRenameStart: () => void;\n  onSelect: () => void;\n  onToggle: () => void;\n  renderIcon?: (item: SidebarResource) => ReactNode;\n  renderMenu?: AISidebarProps[\"renderMenu\"];\n  setRef: (node: HTMLDivElement | null) => void;\n  t: Translate;\n}\n\nexport function ResourceRow({\n  row,\n  active,\n  expanded,\n  focused,\n  draggingId,\n  dropTarget,\n  menuOpen,\n  moves,\n  renaming,\n  onDragEnd,\n  onDragOver,\n  onDragStart,\n  onDrop,\n  onFocus,\n  onKeyDown,\n  onMenuOpenChange,\n  onRenameCancel,\n  onRenameCommit,\n  onRenameStart,\n  onSelect,\n  onToggle,\n  renderIcon,\n  renderMenu,\n  setRef,\n  t,\n}: ResourceRowProps) {\n  const reduce = useReducedMotion() ?? false;\n  const canTouch = useTouchCapable();\n  const [hovered, setHovered] = useState(false);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const skipRenameBlurRef = useRef(false);\n  const draggedRef = useRef(false);\n  const [draft, setDraft] = useState(row.item.label);\n  const acceptsChildren = canContain(row.item);\n  const isDragging = draggingId === row.item.id;\n  const dropPosition = dropTarget?.id === row.item.id ? dropTarget.position : null;\n\n  useEffect(() => {\n    if (!renaming) return;\n    skipRenameBlurRef.current = false;\n    setDraft(row.item.label);\n    requestAnimationFrame(() => {\n      inputRef.current?.focus();\n      inputRef.current?.select();\n    });\n  }, [renaming, row.item.label]);\n\n  const runFromMenu = (action: () => void) => () => {\n    onMenuOpenChange(false);\n    action();\n  };\n\n  const menu = renderMenu?.(row.item, {\n    close: () => onMenuOpenChange(false),\n    rename: () => {\n      onMenuOpenChange(false);\n      onRenameStart();\n    },\n    moves,\n  }) ?? (\n    <>\n      <ResourceMenuAction icon={Pencil} onSelect={runFromMenu(onRenameStart)}>\n        {t(\"rename\")}\n      </ResourceMenuAction>\n      {moves.up || moves.down || moves.into || moves.out ? (\n        <div aria-hidden=\"true\" className=\"my-1 h-px bg-border\" />\n      ) : null}\n      {moves.up ? (\n        <ResourceMenuAction icon={ArrowUp} onSelect={runFromMenu(moves.up)}>\n          {t(\"moveUp\")}\n        </ResourceMenuAction>\n      ) : null}\n      {moves.down ? (\n        <ResourceMenuAction icon={ArrowDown} onSelect={runFromMenu(moves.down)}>\n          {t(\"moveDown\")}\n        </ResourceMenuAction>\n      ) : null}\n      {moves.into ? (\n        <ResourceMenuAction\n          icon={FolderInput}\n          onSelect={runFromMenu(moves.into.run)}\n        >\n          {t(\"moveInto\", { target: moves.into.label })}\n        </ResourceMenuAction>\n      ) : null}\n      {moves.out ? (\n        <ResourceMenuAction icon={Undo2} onSelect={runFromMenu(moves.out)}>\n          {t(\"moveOut\")}\n        </ResourceMenuAction>\n      ) : null}\n    </>\n  );\n\n  return (\n    <motion.div\n      ref={setRef}\n      layout=\"position\"\n      transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n      role=\"treeitem\"\n      aria-level={row.depth + 1}\n      aria-selected={acceptsChildren ? undefined : active}\n      aria-expanded={acceptsChildren ? expanded : undefined}\n      aria-disabled={row.item.disabled || undefined}\n      tabIndex={focused ? 0 : -1}\n      draggable={!row.item.disabled && !renaming}\n      data-menu-open={menuOpen || undefined}\n      data-drop={dropPosition ?? undefined}\n      data-dragging={isDragging || undefined}\n      onFocus={onFocus}\n      onKeyDown={onKeyDown}\n      onClick={(event) => {\n        if (\n          event.defaultPrevented ||\n          draggedRef.current ||\n          renaming ||\n          row.item.disabled\n        )\n          return;\n        if (acceptsChildren) onToggle();\n        else onSelect();\n      }}\n      onDoubleClick={(event) => {\n        if (acceptsChildren || row.item.disabled) return;\n        event.preventDefault();\n        onRenameStart();\n      }}\n      onMouseEnter={() => setHovered(true)}\n      onMouseLeave={() => setHovered(false)}\n      onDragStartCapture={(event) => {\n        draggedRef.current = true;\n        onDragStart(event, row.item.id);\n      }}\n      onDragEndCapture={() => {\n        onDragEnd();\n        requestAnimationFrame(() => {\n          draggedRef.current = false;\n        });\n      }}\n      onDragOver={(event) => onDragOver(event, row)}\n      onDrop={onDrop}\n      className={cn(\n        \"group/resource relative flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 rounded-xl pr-3 text-sm outline-none\",\n        \"text-muted-foreground transition-colors hover:bg-muted hover:text-foreground\",\n        \"focus-visible:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset\",\n        \"data-[menu-open=true]:bg-muted data-[menu-open=true]:text-foreground\",\n        \"data-[dragging=true]:opacity-40\",\n        \"data-[drop=inside]:bg-muted data-[drop=inside]:ring-1 data-[drop=inside]:ring-primary/45\",\n        \"data-[drop=before]:before:absolute data-[drop=before]:before:-top-0.5 data-[drop=before]:before:right-2 data-[drop=before]:before:left-2 data-[drop=before]:before:h-0.5 data-[drop=before]:before:rounded-full data-[drop=before]:before:bg-primary\",\n        \"data-[drop=after]:after:absolute data-[drop=after]:after:-bottom-0.5 data-[drop=after]:after:right-2 data-[drop=after]:after:left-2 data-[drop=after]:after:h-0.5 data-[drop=after]:after:rounded-full data-[drop=after]:after:bg-primary\",\n        !acceptsChildren && active && \"bg-muted text-foreground\",\n        row.item.disabled && \"cursor-not-allowed opacity-45\",\n      )}\n      style={{ paddingLeft: `${12 + row.depth * 16}px` }}\n    >\n      <span aria-hidden=\"true\" className=\"grid size-5 shrink-0 place-items-center\">\n        {renderIcon?.(row.item) ?? defaultIcon(row.item, expanded)}\n      </span>\n\n      {renaming ? (\n        <input\n          ref={inputRef}\n          value={draft}\n          aria-label={t(\"renameItem\", { item: row.item.label })}\n          onChange={(event) => setDraft(event.target.value)}\n          draggable={false}\n          onClick={(event) => event.stopPropagation()}\n          onDoubleClick={(event) => event.stopPropagation()}\n          onBlur={() => {\n            if (!skipRenameBlurRef.current) onRenameCommit(draft);\n          }}\n          onKeyDown={(event) => {\n            event.stopPropagation();\n            if (event.key === \"Enter\") {\n              skipRenameBlurRef.current = true;\n              onRenameCommit(draft);\n            }\n            if (event.key === \"Escape\") {\n              skipRenameBlurRef.current = true;\n              onRenameCancel();\n            }\n          }}\n          className=\"mx-1 h-7 min-w-0 flex-1 rounded-full border border-border bg-background px-3 text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n        />\n      ) : (\n        <MarqueeLabel active={hovered || menuOpen}>{row.item.label}</MarqueeLabel>\n      )}\n\n      {!renaming && !row.item.disabled ? (\n        <MorphPopover\n          open={menuOpen}\n          onOpenChange={onMenuOpenChange}\n        >\n          <Tooltip content={menuOpen ? null : t(\"actions\", { item: row.item.label })} side=\"top\">\n            <ActionsTrigger\n              aria-label={t(\"actions\", { item: row.item.label })}\n              className={cn(\n                // A finger never hovers, and this menu is the only path to\n                // rename and move without a drag - keep it on screen there.\n                canTouch ? \"opacity-100\" : \"opacity-0\",\n              )}\n            />\n          </Tooltip>\n          <MorphPopoverContent\n            side=\"bottom\"\n            align=\"end\"\n            sideOffset={8}\n            className=\"w-40 p-2\"\n          >\n            <div data-sidebar-resource-menu={row.item.id}>{menu}</div>\n          </MorphPopoverContent>\n        </MorphPopover>\n      ) : null}\n    </motion.div>\n  );\n}\n\n/**\n * The row's \"…\" button. Its own component so the tooltip around it and the\n * popover trigger inside both reach the button.\n */\nfunction ActionsTrigger({ className, ...props }: ComponentProps<\"button\">) {\n  return (\n    <MorphPopoverTrigger>\n      <button\n        type=\"button\"\n        draggable={false}\n        tabIndex={-1}\n        {...props}\n        onClick={(event) => {\n          props.onClick?.(event);\n          event.stopPropagation();\n        }}\n        className={cn(\n          \"grid size-7 shrink-0 place-items-center rounded-full outline-none transition-opacity hover:bg-foreground/5 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring group-hover/resource:opacity-100 group-data-[menu-open=true]/resource:opacity-100\",\n          className,\n        )}\n      >\n        <MoreHorizontal aria-hidden=\"true\" className=\"size-4\" />\n      </button>\n    </MorphPopoverTrigger>\n  );\n}\n"},{"path":"components/agents/ai-sidebar/tree.ts","type":"util","content":"import type {\n  FlatResource,\n  SidebarResource,\n  SidebarResourceDropPosition,\n  SidebarResourceMove,\n} from \"./types\";\n\nexport function canContain(item: SidebarResource) {\n  return item.kind === \"folder\" || item.kind === \"project\";\n}\n\nexport function flattenResources(\n  items: SidebarResource[],\n  expanded: Set<string>,\n  depth = 0,\n  parentId: string | null = null,\n): FlatResource[] {\n  return items.flatMap((item) => {\n    const row = { item, depth, parentId };\n    if (!item.children?.length || !expanded.has(item.id)) return [row];\n    return [\n      row,\n      ...flattenResources(item.children, expanded, depth + 1, item.id),\n    ];\n  });\n}\n\nexport function findResource(\n  items: SidebarResource[],\n  id: string,\n): SidebarResource | undefined {\n  for (const item of items) {\n    if (item.id === id) return item;\n    const child = item.children ? findResource(item.children, id) : undefined;\n    if (child) return child;\n  }\n}\n\nexport function containsResource(item: SidebarResource, id: string): boolean {\n  return (\n    item.id === id ||\n    item.children?.some((child) => containsResource(child, id)) === true\n  );\n}\n\nfunction removeResource(\n  items: SidebarResource[],\n  id: string,\n): { items: SidebarResource[]; removed?: SidebarResource } {\n  let removed: SidebarResource | undefined;\n  const next: SidebarResource[] = [];\n\n  for (const item of items) {\n    if (item.id === id) {\n      removed = item;\n      continue;\n    }\n\n    if (item.children?.length) {\n      const childResult = removeResource(item.children, id);\n      if (childResult.removed) {\n        removed = childResult.removed;\n        next.push({ ...item, children: childResult.items });\n        continue;\n      }\n    }\n\n    next.push(item);\n  }\n\n  return { items: next, removed };\n}\n\nfunction insertResource(\n  items: SidebarResource[],\n  resource: SidebarResource,\n  targetId: string | null,\n  position: SidebarResourceDropPosition,\n): SidebarResource[] {\n  if (targetId === null) return [...items, resource];\n\n  const next: SidebarResource[] = [];\n  for (const item of items) {\n    if (item.id === targetId) {\n      if (position === \"before\") next.push(resource, item);\n      else if (position === \"after\") next.push(item, resource);\n      else next.push({ ...item, children: [...(item.children ?? []), resource] });\n      continue;\n    }\n\n    if (item.children?.length) {\n      next.push({\n        ...item,\n        children: insertResource(item.children, resource, targetId, position),\n      });\n    } else {\n      next.push(item);\n    }\n  }\n  return next;\n}\n\nexport function moveResource(\n  items: SidebarResource[],\n  move: SidebarResourceMove,\n): SidebarResource[] | null {\n  const source = findResource(items, move.itemId);\n  if (!source || source.disabled) return null;\n  if (move.targetId && containsResource(source, move.targetId)) return null;\n\n  const target = move.targetId ? findResource(items, move.targetId) : undefined;\n  if (\n    move.position === \"inside\" &&\n    (!target || target.disabled || !canContain(target))\n  )\n    return null;\n\n  const removed = removeResource(items, move.itemId);\n  if (!removed.removed) return null;\n  return insertResource(\n    removed.items,\n    removed.removed,\n    move.targetId,\n    move.position,\n  );\n}\n\nexport function renameResource(\n  items: SidebarResource[],\n  id: string,\n  label: string,\n): SidebarResource[] {\n  return items.map((item) => ({\n    ...item,\n    label: item.id === id ? label : item.label,\n    children: item.children\n      ? renameResource(item.children, id, label)\n      : undefined,\n  }));\n}\n"},{"path":"components/agents/ai-sidebar/types.ts","type":"util","content":"import type { ReactNode } from \"react\";\nimport type { AISidebarMessages } from \"./messages\";\n\nexport type SidebarResourceKind =\n  | \"folder\"\n  | \"project\"\n  | \"file\"\n  | \"bookmark\";\n\nexport interface SidebarResource {\n  /** Unique key for the row, used for selection, expansion and moves. */\n  id: string;\n  /** Name shown in the row and edited on rename. */\n  label: string;\n  /** Picks the row icon; folders and projects can hold children. */\n  kind: SidebarResourceKind;\n  /** Nested rows shown when a folder or project is expanded. */\n  children?: SidebarResource[];\n  /** Dims the row and blocks selecting, renaming, dragging and dropping into it. */\n  disabled?: boolean;\n}\n\nexport type SidebarResourceDropPosition = \"before\" | \"inside\" | \"after\";\n\nexport interface SidebarResourceMove {\n  /** Id of the row being moved. */\n  itemId: string;\n  /** Id of the row it lands next to or inside, or null for the end of the root. */\n  targetId: string | null;\n  /** Where the row lands relative to the target. */\n  position: SidebarResourceDropPosition;\n}\n\n/**\n * The moves this row can make right now, the same four the keyboard offers on\n * `Alt+Shift+Arrow`. A pointer drag is the fast path for them; a finger has no\n * drag to give, so the row menu carries them too. Absent keys are moves this\n * row cannot make from where it sits.\n */\nexport interface SidebarResourceMoveCommands {\n  /** Moves the row above the row before it. */\n  up?: () => void;\n  /** Moves the row below the row after it. */\n  down?: () => void;\n  /** Moves the row into the folder or project above it, named by `label`. */\n  into?: { label: string; run: () => void };\n  /** Moves the row out of its parent, just after it. */\n  out?: () => void;\n}\n\nexport interface SidebarResourceMenuControls {\n  /** Closes the row menu. */\n  close: () => void;\n  /** Closes the menu and starts renaming the row in place. */\n  rename: () => void;\n  /** The moves this row can make right now. */\n  moves: SidebarResourceMoveCommands;\n}\n\nexport interface AISidebarProps {\n  /** The resource tree, for controlled use. */\n  items?: SidebarResource[];\n  /** The initial resource tree when uncontrolled. */\n  defaultItems?: SidebarResource[];\n  /** Called with the new tree after a move, rename or rollback. */\n  onItemsChange?: (items: SidebarResource[]) => void;\n  /** Reject the promise to roll the optimistic move back. */\n  onMove?: (move: SidebarResourceMove) => void | Promise<void>;\n  /** Called with the error and the move when `onMove` rejects. */\n  onMoveError?: (error: unknown, move: SidebarResourceMove) => void;\n  /** Called with the item and trimmed new label. Reject to roll it back. */\n  onRename?: (item: SidebarResource, label: string) => void | Promise<void>;\n  /** Id of the selected row, for controlled use. */\n  activeId?: string | null;\n  /** Id of the initially selected row when uncontrolled. Default: null */\n  defaultActiveId?: string | null;\n  /** Called with the row's id when a row is selected. */\n  onActiveChange?: (id: string) => void;\n  /** Ids of folders and projects that start expanded. */\n  defaultExpandedIds?: string[];\n  /** Renders a row's icon in place of the built-in kind icon. */\n  renderIcon?: (item: SidebarResource) => ReactNode;\n  /** Renders a row's actions menu, with controls to close, rename and move. */\n  renderMenu?: (\n    item: SidebarResource,\n    controls: SidebarResourceMenuControls,\n  ) => ReactNode;\n  /** Accessible name for the tree. Default: \"Resources\" */\n  ariaLabel?: string;\n  /** Classes merged onto the tree element. */\n  className?: string;\n  /** Override any built-in string. */\n  labels?: Partial<AISidebarMessages>;\n}\n\nexport interface FlatResource {\n  item: SidebarResource;\n  depth: number;\n  parentId: string | null;\n}\n\nexport interface DropTarget {\n  id: string | null;\n  position: SidebarResourceDropPosition;\n}\n"},{"path":"components/agents/approval-card/messages.ts","type":"util","content":"/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const approvalCardMessages = {\n  title: \"Approval required\",\n  approve: \"Approve\",\n  submit: \"Submit response\",\n  requestChanges: \"Request changes\",\n  reject: \"Reject\",\n  dismiss: \"Dismiss\",\n  previousQuestion: \"Previous question\",\n  nextQuestion: \"Next question\",\n  customPlaceholder: \"Add another response…\",\n  questionProgress: \"Question {current} of {total}\",\n  stepCount: \"{current}/{total}\",\n  inputRequired: \"Input required\",\n  submitting: \"Submitting\",\n  approved: \"Approved\",\n  rejected: \"Rejected\",\n  changesRequested: \"Changes requested\",\n  answered: \"Response submitted\",\n};\n\nexport type ApprovalCardMessages = typeof approvalCardMessages;\n"},{"path":"components/agents/approval-card/types.ts","type":"util","content":"import type { ReactNode } from \"react\";\nimport type { ApprovalCardMessages } from \"./messages\";\n\nexport type ApprovalCardStatus =\n  | \"pending\"\n  | \"submitting\"\n  | \"approved\"\n  | \"rejected\"\n  | \"changes-requested\"\n  | \"answered\";\n\nexport interface ApprovalCardOption {\n  /** Value stored in the answer's `selected` list when picked. */\n  value: string;\n  /** Text shown next to the radio or checkbox. */\n  label: string;\n  /** Plain supporting text rendered under the label. */\n  description?: string;\n  /** Stops the option from being picked. */\n  disabled?: boolean;\n}\n\nexport interface ApprovalCardQuestion {\n  /** Unique key; the question's answer is stored under it. */\n  id: string;\n  /** Question text, shown as the card heading on its step. */\n  title: ReactNode;\n  /** Supporting text under the question. */\n  description?: ReactNode;\n  /** Choices shown as radios, or checkboxes when `multiple` is set. */\n  options?: ApprovalCardOption[];\n  /** Allows picking more than 1 option, shown as checkboxes. */\n  multiple?: boolean;\n  /** Set to false to stay on the step after a single choice is picked. */\n  autoAdvance?: boolean;\n  /** Adds a text field for a free-form answer. */\n  allowCustom?: boolean;\n  /** Placeholder of the free-form field. Default: \"Add another response…\" */\n  customPlaceholder?: string;\n}\n\nexport interface ApprovalCardAnswer {\n  selected: string[];\n  custom?: string;\n}\n\nexport type ApprovalCardAnswers = Record<string, ApprovalCardAnswer>;\n\nexport interface ApprovalCardProps {\n  /** Heading of the card. A question's own title replaces it. Default: \"Approval required\" */\n  title?: ReactNode;\n  /** Supporting text under the title when there are no questions. */\n  description?: ReactNode;\n  children?: ReactNode;\n  /** Questions asked one step at a time. Replaces approve and reject buttons. */\n  questions?: ApprovalCardQuestion[];\n  /** Current state, which sets the badge, icon and whether the form shows. Default: \"pending\" */\n  status?: ApprovalCardStatus;\n  /** Answers keyed by question id, for controlled use. */\n  answers?: ApprovalCardAnswers;\n  /** The initial answers when uncontrolled. */\n  defaultAnswers?: ApprovalCardAnswers;\n  /** Called with all answers whenever one changes. */\n  onAnswersChange?: (answers: ApprovalCardAnswers) => void;\n  /** Index of the shown question, for controlled use. */\n  step?: number;\n  /** The initial question index when uncontrolled. Default: 0 */\n  defaultStep?: number;\n  /** Called with the new question index when the step changes. */\n  onStepChange?: (step: number) => void;\n  /** Called with all answers when the last question is submitted. */\n  onSubmit?: (answers: ApprovalCardAnswers) => void;\n  /** Called when the approve button is pressed. */\n  onApprove?: () => void;\n  /** Called when the reject button is pressed. The button shows only when set. */\n  onReject?: () => void;\n  /** Called when the request changes button is pressed. The button shows only when set. */\n  onRequestChanges?: () => void;\n  /** Called when the close button is pressed. The button shows only when set. */\n  onDismiss?: () => void;\n  /** Text of the approve button. Default: \"Approve\" */\n  approveLabel?: ReactNode;\n  /** Text of the last question's submit button. Default: \"Submit response\" */\n  submitLabel?: ReactNode;\n  /** Shown in place of the form once the card is settled. Defaults to the status label. */\n  result?: ReactNode;\n  /** Override any built-in string. */\n  labels?: Partial<ApprovalCardMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n"},{"path":"components/agents/clip-resize-frame.tsx","type":"util","content":"\"use client\";\n\nimport {\n  type AnimationPlaybackControls,\n  animate,\n  type HTMLMotionProps,\n  motion,\n  useMotionValue,\n  useReducedMotion,\n  useTransform,\n} from \"motion/react\";\nimport { type CSSProperties, type ReactNode, useLayoutEffect, useRef } from \"react\";\nimport { EASE_OUT, SPRING_MORPH } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\n// The bottom edge glides to the new size; a little quicker when shrinking,\n// since the content inside has already gone.\nconst GROW = { duration: 0.3, ease: EASE_OUT } as const;\nconst SHRINK = { duration: 0.24, ease: EASE_OUT } as const;\n\nexport interface ClipResizeFrameProps extends Omit<HTMLMotionProps<\"div\">, \"children\" | \"style\"> {\n  style?: CSSProperties;\n  /**\n   * Which size follows the content. \"y\": the bottom edge glides as the height\n   * changes. \"x\": both ends glide in or out from the centre as the width\n   * changes, on a morph spring, for pills and chips. Default: \"y\"\n   */\n  axis?: \"x\" | \"y\";\n  /**\n   * With axis \"y\", which edge moves. \"top\" is for a panel anchored at its\n   * bottom, such as a list opening above an input: its top edge glides and its\n   * content stays against the bottom. Default: \"bottom\"\n   */\n  edge?: \"top\" | \"bottom\";\n  /** Outer corner radius in px. The surface inside uses one less. */\n  radius?: number;\n  /** Classes for the content box (padding goes here). */\n  contentClassName?: string;\n  children: ReactNode;\n}\n\n/**\n * A bordered card whose bottom edge glides when its content grows or shrinks,\n * without animating height. The layout changes at once; a clip on the card\n * hides the difference and slides it away. The border is the 1px gap between\n * two clipped layers (the frame in the border colour, the surface inside it),\n * so the bottom line travels with the edge instead of being clipped off.\n */\nexport function ClipResizeFrame({\n  axis = \"y\",\n  edge = \"bottom\",\n  radius = 16,\n  className,\n  contentClassName,\n  style,\n  children,\n  ...props\n}: ClipResizeFrameProps) {\n  const reduce = useReducedMotion() ?? false;\n  const horizontal = axis === \"x\";\n  const fromTop = !horizontal && edge === \"top\";\n  const surfaceRef = useRef<HTMLDivElement>(null);\n  const contentRef = useRef<HTMLDivElement>(null);\n  // How much of the surface (px) is hidden right now: at the moving edge, or\n  // split evenly between the two ends.\n  const gap = useMotionValue(0);\n  const clip = (value: number, round: number) =>\n    horizontal\n      ? `inset(0 ${value / 2}px 0 ${value / 2}px round ${round}px)`\n      : fromTop\n        ? `inset(${value}px 0 0 0 round ${round}px)`\n        : `inset(0 0 ${value}px 0 round ${round}px)`;\n  const frameClip = useTransform(gap, (value) =>\n    Math.abs(value) > 0.5 ? clip(value, radius) : \"none\",\n  );\n  const surfaceClip = useTransform(gap, (value) =>\n    Math.abs(value) > 0.5 ? clip(value, radius - 1) : \"none\",\n  );\n\n  useLayoutEffect(() => {\n    const surface = surfaceRef.current;\n    const content = contentRef.current;\n    if (!surface || !content || typeof ResizeObserver === \"undefined\") return;\n\n    const measure = () => (horizontal ? content.offsetWidth : content.offsetHeight);\n    const side = horizontal ? \"width\" : \"height\";\n    let last = measure();\n    // While shrinking, the surface keeps its old size so the edge has\n    // somewhere to glide from; null when the surface sizes to its content.\n    let held: number | null = null;\n    let controls: AnimationPlaybackControls | undefined;\n\n    const release = () => {\n      held = null;\n      surface.style[side] = \"\";\n      gap.set(0);\n    };\n\n    // Runs after layout and before paint, so the held size lands in the\n    // same frame as the content change: the edge never jumps.\n    const observer = new ResizeObserver(() => {\n      const next = measure();\n      if (next === last) return;\n      const visible = (held ?? last) - gap.get();\n      last = next;\n      controls?.stop();\n\n      if (reduce) {\n        release();\n        return;\n      }\n\n      const from = Math.max(next, visible);\n      held = from > next ? from : null;\n      surface.style[side] = held === null ? \"\" : `${held}px`;\n      gap.set(from - visible);\n      controls = animate(gap, from - next, {\n        ...(horizontal ? SPRING_MORPH : next < visible ? SHRINK : GROW),\n        // The edge has reached the content: hand the size back to layout.\n        onComplete: () => {\n          if (held !== null) release();\n        },\n      });\n    });\n    observer.observe(content);\n    return () => {\n      observer.disconnect();\n      controls?.stop();\n    };\n  }, [gap, reduce, horizontal]);\n\n  return (\n    <motion.div\n      {...props}\n      style={{ ...style, borderRadius: radius, clipPath: frameClip }}\n      className={cn(\"bg-border p-px\", horizontal && \"w-fit\", className)}\n    >\n      <motion.div\n        ref={surfaceRef}\n        style={{ borderRadius: radius - 1, clipPath: surfaceClip }}\n        // Held wider than its content while shrinking, the surface keeps the\n        // content centred, so the two ends close in on it evenly.\n        // Held taller than its content, a top-edge surface keeps the content\n        // against its anchored bottom.\n        className={cn(\n          \"overflow-hidden bg-background\",\n          horizontal && \"flex justify-center\",\n          fromTop && \"flex flex-col justify-end\",\n        )}\n      >\n        <div ref={contentRef} className={cn(horizontal && \"w-max shrink-0\", contentClassName)}>\n          {children}\n        </div>\n      </motion.div>\n    </motion.div>\n  );\n}\n"},{"path":"components/agents/icon-swap.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport type { ReactNode } from \"react\";\nimport { SPRING_SWAP } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface IconSwapProps {\n  /** Changes whenever the icon should change (copy → copied, running → done). */\n  id: string;\n  children: ReactNode;\n  className?: string;\n}\n\n/**\n * Crossfades one status icon into the next with a little scale and a 2px\n * blur, so the change reads as one icon morphing rather than two crossing.\n * Reduced motion keeps the fade and drops the scale.\n */\nexport function IconSwap({ id, children, className }: IconSwapProps) {\n  const reduce = useReducedMotion() ?? false;\n  return (\n    <AnimatePresence mode=\"popLayout\" initial={false}>\n      <motion.span\n        key={id}\n        initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: \"blur(2px)\" }}\n        animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n        exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: \"blur(2px)\" }}\n        transition={reduce ? { duration: 0.12 } : SPRING_SWAP}\n        className={cn(\"grid place-items-center\", className)}\n      >\n        {children}\n      </motion.span>\n    </AnimatePresence>\n  );\n}\n"},{"path":"components/motion/action-swap-roll.tsx","type":"util","content":"\"use client\";\n\nimport {\n  ActionSwapButton,\n  ActionSwapIcon,\n  ActionSwapText,\n  type ActionSwapButtonProps,\n  type ActionSwapIconProps,\n  type ActionSwapTextProps,\n} from \"./action-swap\";\n\nexport type {\n  ActionSwapButtonSize,\n  ActionSwapButtonVariant,\n  ActionSwapItem,\n} from \"./action-swap\";\n\nexport type ActionSwapRollButtonProps = Omit<ActionSwapButtonProps, \"animation\">;\nexport type ActionSwapRollTextProps = Omit<ActionSwapTextProps, \"animation\">;\nexport type ActionSwapRollIconProps = Omit<ActionSwapIconProps, \"animation\">;\n\nexport function ActionSwapRollButton(props: ActionSwapRollButtonProps) {\n  return <ActionSwapButton {...props} animation=\"roll\" />;\n}\n\nexport function ActionSwapRollText(props: ActionSwapRollTextProps) {\n  return <ActionSwapText {...props} animation=\"roll\" />;\n}\n\nexport function ActionSwapRollIcon(props: ActionSwapRollIconProps) {\n  return <ActionSwapIcon {...props} animation=\"roll\" />;\n}\n"},{"path":"components/motion/button/index.tsx","type":"util","content":"export type {\n  ButtonLinkProps,\n  ButtonProps,\n  ButtonSize,\n  ButtonVariant,\n} from \"./base\";\nexport { Button, ButtonLink } from \"./base\";\nexport type { MagneticButtonProps } from \"./magnetic\";\nexport { MagneticButton } from \"./magnetic\";\nexport type { MetallicButtonProps } from \"./metallic\";\nexport { MetallicButton } from \"./metallic\";\nexport type {\n  ButtonState,\n  StatefulButtonMessages,\n  StatefulButtonProps,\n} from \"./stateful\";\nexport { StatefulButton, statefulButtonMessages } from \"./stateful\";\n"},{"path":"components/motion/checkbox.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { useId } from \"react\";\nimport { EASE_OUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const checkboxMessages = {\n  checked: \"Selected\",\n  indeterminate: \"Partially selected\",\n};\n\nexport type CheckboxMessages = typeof checkboxMessages;\n\nconst CHECK_PATH = \"M5 13l4 4L19 7\";\nconst INDETERMINATE_PATH = \"M6 12h12\";\n\nexport interface CheckboxProps {\n  /** Whether the box is checked. */\n  checked: boolean;\n  /** Called with the new state when the box is toggled. */\n  onCheckedChange: (checked: boolean) => void;\n  /** Blocks toggling and dims the control. */\n  disabled?: boolean;\n  /** Shows a dash for a partly selected group. Announced as mixed. */\n  indeterminate?: boolean;\n  /** Visible text beside the box, also its accessible name. */\n  label?: string;\n  /** Supporting text under the label, announced as the description rather than the name. */\n  description?: string;\n  /** Classes merged onto the root label element. */\n  className?: string;\n  /** Id for the checkbox button. Generated when omitted. */\n  id?: string;\n  /** Accessible name when there is no visible label. */\n  \"aria-label\"?: string;\n  /** Associates an external message (e.g. a form error) with the control. */\n  \"aria-describedby\"?: string;\n  /** Override any built-in string. */\n  labels?: Partial<CheckboxMessages>;\n}\n\nexport function Checkbox({\n  checked,\n  onCheckedChange,\n  disabled,\n  indeterminate,\n  label,\n  description,\n  className,\n  id: idProp,\n  \"aria-label\": ariaLabel,\n  \"aria-describedby\": ariaDescribedBy,\n  labels,\n}: CheckboxProps) {\n  const t = useMessages(\"checkbox\", checkboxMessages, labels);\n  const autoId = useId();\n  const id = idProp ?? autoId;\n  const reduce = useReducedMotion();\n  const showMark = checked || indeterminate;\n  const path = indeterminate ? INDETERMINATE_PATH : CHECK_PATH;\n  const descriptionId = description ? `${id}-description` : undefined;\n  // The wrapping <label> would fold the description into the name, so name from the label text alone.\n  const labelId = description && label && !ariaLabel ? `${id}-label` : undefined;\n  const describedBy =\n    [ariaDescribedBy, descriptionId].filter(Boolean).join(\" \") || undefined;\n\n  return (\n    <label\n      htmlFor={id}\n      className={cn(\n        \"inline-flex gap-3\",\n        description ? \"items-start\" : \"items-center\",\n        disabled ? \"cursor-not-allowed\" : \"cursor-pointer\",\n        className,\n      )}\n    >\n      <motion.button\n        id={id}\n        type=\"button\"\n        role=\"checkbox\"\n        aria-checked={indeterminate ? \"mixed\" : checked}\n        aria-label={ariaLabel}\n        aria-labelledby={labelId}\n        aria-describedby={describedBy}\n        disabled={disabled}\n        onClick={() => !disabled && onCheckedChange(!checked)}\n        whileTap={reduce || disabled ? undefined : { scale: 0.92 }}\n        transition={SPRING_PRESS}\n        data-state={\n          checked ? \"checked\" : indeterminate ? \"indeterminate\" : \"unchecked\"\n        }\n        className={cn(\n          \"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-md border-2 outline-none transition-colors duration-200\",\n          \"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n          \"disabled:cursor-not-allowed disabled:opacity-60\",\n          showMark\n            ? \"border-primary bg-primary text-primary-foreground\"\n            : \"border-muted-foreground/50 bg-background hover:border-muted-foreground\",\n        )}\n      >\n        <AnimatePresence initial={false}>\n          {showMark ? (\n            <motion.svg\n              key={indeterminate ? \"indeterminate\" : \"checked\"}\n              width=\"12\"\n              height=\"12\"\n              viewBox=\"0 0 24 24\"\n              fill=\"none\"\n              stroke=\"currentColor\"\n              strokeWidth={3}\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              initial={reduce ? { opacity: 1 } : { opacity: 0, scale: 0.5 }}\n              animate={reduce ? { opacity: 1 } : { opacity: 1, scale: 1 }}\n              exit={\n                reduce\n                  ? { opacity: 0 }\n                  : { opacity: 0, scale: 0.5, filter: \"blur(4px)\" }\n              }\n              transition={\n                reduce ? { duration: 0 } : { duration: 0.16, ease: EASE_OUT }\n              }\n              aria-hidden\n            >\n              <title>{t(indeterminate ? \"indeterminate\" : \"checked\")}</title>\n              <motion.path\n                d={path}\n                initial={reduce ? { pathLength: 1 } : { pathLength: 0 }}\n                animate={{ pathLength: 1 }}\n                transition={\n                  reduce\n                    ? { duration: 0 }\n                    : {\n                        duration: indeterminate ? 0.2 : 0.3,\n                        ease: EASE_OUT,\n                        delay: 0.04,\n                      }\n                }\n              />\n            </motion.svg>\n          ) : null}\n        </AnimatePresence>\n      </motion.button>\n      {label || description ? (\n        <span className={cn(\"flex min-w-0 flex-col gap-0.5 select-none\", disabled && \"opacity-60\")}>\n          {label ? (\n            <span\n              id={labelId}\n              // Geist sits low in a 20px line; a 16px line lifts the text onto the control.\n              className={cn(\"text-sm text-foreground\", description && \"leading-4\")}\n            >\n              {label}\n            </span>\n          ) : null}\n          {description ? (\n            <span id={descriptionId} className=\"text-xs text-muted-foreground\">\n              {description}\n            </span>\n          ) : null}\n        </span>\n      ) : null}\n    </label>\n  );\n}\n"},{"path":"components/motion/input.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  forwardRef,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n  type InputHTMLAttributes,\n  type ReactNode,\n} from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport type InputClassNames = {\n  /** Classes for the outer wrapper. */\n  root?: string;\n  /** Classes for the label above the field. */\n  label?: string;\n  /** Classes for the bordered box around the input and icons. */\n  field?: string;\n  /** Classes for the input element. */\n  input?: string;\n  /** Classes for the wrapper of the icon before the text. */\n  leftIcon?: string;\n  /** Classes for the wrapper of the icon after the text. */\n  rightIcon?: string;\n  /** Classes for the check mark shown while `success` is set. */\n  successIcon?: string;\n  /** Classes for the error message under the field. */\n  errorMessage?: string;\n};\n\nexport interface InputProps extends Omit<\n  InputHTMLAttributes<HTMLInputElement>,\n  \"value\" | \"defaultValue\" | \"onChange\"\n> {\n  /** Text shown above the field and tied to it as its label. */\n  label?: string;\n  /** The field text, for controlled use. */\n  value?: string;\n  /** The initial field text when uncontrolled. */\n  defaultValue?: string;\n  /** Called with the new text on every edit. */\n  onChange?: (value: string) => void;\n  /** Truthy error triggers a shake, red border and (if a string) a message. */\n  error?: string | boolean;\n  /** Reserve one message line so validation does not shift nearby content. */\n  reserveErrorLine?: boolean;\n  /** Shows a green check in place of `rightIcon`. */\n  success?: boolean;\n  /** Icon inside the field, before the text. */\n  leftIcon?: ReactNode;\n  /** Icon inside the field, after the text. Hidden while `success` is set. */\n  rightIcon?: ReactNode;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes for the root, label, field, input, icons and error message. */\n  classNames?: InputClassNames;\n}\n\nexport const Input = forwardRef<HTMLInputElement, InputProps>(function Input(\n  {\n    label,\n    value: valueProp,\n    defaultValue,\n    onChange,\n    onFocus,\n    onBlur,\n    error,\n    reserveErrorLine = false,\n    success,\n    leftIcon,\n    rightIcon,\n    className,\n    classNames,\n    disabled,\n    id: idProp,\n    type,\n    ...rest\n  },\n  ref,\n) {\n  const reactId = useId();\n  const id = idProp ?? reactId;\n  const reduce = useReducedMotion();\n\n  const controlled = valueProp !== undefined;\n  const [internal, setInternal] = useState(defaultValue ?? \"\");\n  const value = controlled ? (valueProp ?? \"\") : internal;\n\n  const [focused, setFocused] = useState(false);\n\n  const fieldRef = useRef<HTMLDivElement>(null);\n\n  const hasError = Boolean(error);\n  const errorMessage = typeof error === \"string\" ? error : null;\n\n  // Right edge shows the success check, otherwise the caller's right icon.\n  const rightSlot = success ? null : rightIcon;\n\n  // Shake the field when an error appears.\n  useEffect(() => {\n    if (!fieldRef.current || reduce || !hasError) return;\n    animate(\n      fieldRef.current,\n      { x: [0, -6, 6, -4, 4, -2, 0] },\n      { duration: 0.45 },\n    );\n  }, [hasError, reduce]);\n\n  const handleChange = (next: string) => {\n    if (!controlled) setInternal(next);\n    onChange?.(next);\n  };\n\n  return (\n    <div\n      className={cn(\"flex flex-col gap-1.5\", className, classNames?.root)}\n    >\n      {label ? (\n        <label\n          htmlFor={id}\n          className={cn(\n            \"px-1 text-sm font-medium text-foreground\",\n            classNames?.label,\n          )}\n        >\n          {label}\n        </label>\n      ) : null}\n\n      <div\n        ref={fieldRef}\n        data-state={\n          hasError\n            ? \"error\"\n            : success\n              ? \"success\"\n              : focused\n                ? \"focused\"\n                : \"idle\"\n        }\n        className={cn(\n          \"relative h-11 overflow-hidden rounded-full border transition-colors duration-200\",\n          \"border-border\",\n          focused && !hasError && \"border-foreground/40 ring-2 ring-ring/40\",\n          hasError && \"border-destructive ring-2 ring-destructive/25\",\n          disabled && \"opacity-60\",\n          classNames?.field,\n        )}\n      >\n        {leftIcon ? (\n          <span\n            className={cn(\n              \"pointer-events-none absolute left-3 top-1/2 flex -translate-y-1/2 items-center text-muted-foreground [&_svg]:h-4 [&_svg]:w-4\",\n              classNames?.leftIcon,\n            )}\n          >\n            {leftIcon}\n          </span>\n        ) : null}\n\n        <input\n          ref={ref}\n          id={id}\n          type={type}\n          value={value}\n          disabled={disabled}\n          aria-invalid={hasError || undefined}\n          aria-describedby={errorMessage ? `${id}-error` : undefined}\n          {...rest}\n          onChange={(e) => handleChange(e.target.value)}\n          onFocus={(event) => {\n            setFocused(true);\n            onFocus?.(event);\n          }}\n          onBlur={(event) => {\n            setFocused(false);\n            onBlur?.(event);\n          }}\n          className={cn(\n            \"peer h-full w-full bg-transparent text-base leading-6 text-foreground caret-foreground outline-none\",\n            \"placeholder:text-muted-foreground/60\",\n            leftIcon ? \"pl-10\" : \"pl-3.5\",\n            rightSlot || success ? \"pr-10\" : \"pr-3.5\",\n            disabled && \"cursor-not-allowed\",\n            classNames?.input,\n          )}\n        />\n\n        {success ? (\n          <motion.svg\n            viewBox=\"0 0 24 24\"\n            fill=\"none\"\n            className={cn(\n              \"absolute right-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-(--color-success)\",\n              classNames?.successIcon,\n            )}\n          >\n            <motion.path\n              d=\"M5 12.5l4.5 4.5L19 7.5\"\n              stroke=\"currentColor\"\n              strokeWidth={2.5}\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              initial={reduce ? { pathLength: 1 } : { pathLength: 0 }}\n              animate={{ pathLength: 1 }}\n              transition={{ duration: 0.35, ease: EASE_OUT }}\n            />\n          </motion.svg>\n        ) : rightSlot ? (\n          <span\n            className={cn(\n              \"absolute right-0 top-0 flex h-full items-center text-muted-foreground [&_button]:grid [&_button]:size-11 [&_button]:place-items-center [&_svg]:h-4 [&_svg]:w-4\",\n              classNames?.rightIcon,\n            )}\n          >\n            {rightSlot}\n          </span>\n        ) : null}\n      </div>\n\n      <div className={reserveErrorLine ? \"min-h-4\" : \"contents\"}>\n        <AnimatePresence initial={false}>\n          {errorMessage ? (\n            <motion.p\n              id={`${id}-error`}\n              role=\"alert\"\n              initial={\n                reduce\n                  ? { opacity: 0 }\n                  : { opacity: 0, y: -4, filter: \"blur(4px)\" }\n              }\n              animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n              exit={\n                reduce\n                  ? { opacity: 0 }\n                  : { opacity: 0, y: -4, filter: \"blur(4px)\" }\n              }\n              transition={{ duration: 0.2 }}\n              className={cn(\n                \"px-1 text-xs text-destructive\",\n                classNames?.errorMessage,\n              )}\n            >\n              {errorMessage}\n            </motion.p>\n          ) : null}\n        </AnimatePresence>\n      </div>\n    </div>\n  );\n});\n"},{"path":"components/motion/radio.tsx","type":"util","content":"\"use client\";\n\nimport { motion, MotionConfig, useReducedMotion } from \"motion/react\";\nimport {\n  createContext,\n  type KeyboardEvent,\n  useCallback,\n  useContext,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useState,\n  type ReactNode,\n} from \"react\";\nimport { SPRING_LAYOUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\ntype RadioCtx = {\n  value: string;\n  setValue: (value: string) => void;\n  layoutId: string;\n  /**\n   * The one option Tab reaches: the selected option, or the first enabled one\n   * when nothing enabled is selected. `null` until the options have\n   * registered, when every enabled option stays reachable.\n   */\n  tabStop: string | null;\n  register: (value: string, disabled: boolean) => void;\n  unregister: (value: string) => void;\n};\n\nconst RadioCtx = createContext<RadioCtx | null>(null);\n\nfunction useRadioGroup() {\n  const ctx = useContext(RadioCtx);\n  if (!ctx) {\n    throw new Error(\"RadioGroupItem must be used inside <RadioGroup>\");\n  }\n  return ctx;\n}\n\nexport interface RadioGroupProps {\n  /** The selected value, for controlled use. */\n  value?: string;\n  /** The initial value when uncontrolled. Default: \"\" */\n  defaultValue?: string;\n  /** Called with the item's value when the selection changes. */\n  onValueChange?: (value: string) => void;\n  children: ReactNode;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Stacks items in a column or wraps them in a row. Default: \"vertical\" */\n  orientation?: \"vertical\" | \"horizontal\";\n  /** Accessible name for the group when no visible label names it. */\n  \"aria-label\"?: string;\n  /** Id of a visible element that names the group. */\n  \"aria-labelledby\"?: string;\n}\n\nexport function RadioGroup({\n  value,\n  defaultValue = \"\",\n  onValueChange,\n  children,\n  className,\n  orientation = \"vertical\",\n  \"aria-label\": ariaLabel,\n  \"aria-labelledby\": ariaLabelledBy,\n}: RadioGroupProps) {\n  const [internal, setInternal] = useState(defaultValue);\n  const layoutId = useId();\n  const reduce = useReducedMotion();\n  const controlled = value !== undefined;\n  const current = controlled ? value : internal;\n  const setValue = useCallback(\n    (next: string) => {\n      if (!controlled) setInternal(next);\n      onValueChange?.(next);\n    },\n    [controlled, onValueChange],\n  );\n  const [options, setOptions] = useState<Map<string, boolean>>(new Map());\n  const register = useCallback((option: string, disabled: boolean) => {\n    setOptions((map) =>\n      map.get(option) === disabled ? map : new Map(map).set(option, disabled),\n    );\n  }, []);\n  const unregister = useCallback((option: string) => {\n    setOptions((map) => {\n      if (!map.has(option)) return map;\n      const next = new Map(map);\n      next.delete(option);\n      return next;\n    });\n  }, []);\n  // Resolved during render so the group has exactly one tab stop in the same\n  // commit that changes the selection or the options.\n  let tabStop: string | null = null;\n  if (options.size > 0) {\n    const enabled = Array.from(options).filter(([, disabled]) => !disabled);\n    tabStop = enabled.some(([option]) => option === current)\n      ? current\n      : (enabled[0]?.[0] ?? \"\");\n  }\n  const contextValue = useMemo(\n    () => ({ value: current, setValue, layoutId, tabStop, register, unregister }),\n    [current, layoutId, setValue, tabStop, register, unregister],\n  );\n\n  return (\n    <MotionConfig transition={reduce ? { duration: 0 } : SPRING_LAYOUT}>\n      <RadioCtx.Provider value={contextValue}>\n        <div\n          role=\"radiogroup\"\n          aria-label={ariaLabel}\n          aria-labelledby={ariaLabelledBy}\n          className={cn(\n            \"flex gap-3\",\n            orientation === \"vertical\" ? \"flex-col\" : \"flex-row flex-wrap\",\n            className,\n          )}\n        >\n          {children}\n        </div>\n      </RadioCtx.Provider>\n    </MotionConfig>\n  );\n}\n\nexport interface RadioGroupItemProps {\n  /** The value the group takes when this item is picked. */\n  value: string;\n  /** Text shown beside the radio, used as its name. */\n  label?: string;\n  /** Supporting text under the label, announced as the description rather than the name. */\n  description?: string;\n  /** Dims the item and stops it from being picked. */\n  disabled?: boolean;\n  /** Classes merged onto the item's label element. */\n  className?: string;\n  /** Id for the radio button. Default: a generated id */\n  id?: string;\n}\n\nexport function RadioGroupItem({\n  value,\n  label,\n  description,\n  disabled,\n  className,\n  id: idProp,\n}: RadioGroupItemProps) {\n  const {\n    value: groupValue,\n    setValue,\n    layoutId,\n    tabStop,\n    register,\n    unregister,\n  } = useRadioGroup();\n  const autoId = useId();\n  const id = idProp ?? autoId;\n  const reduce = useReducedMotion();\n  const selected = groupValue === value;\n  const descriptionId = description ? `${id}-description` : undefined;\n  // The wrapping <label> would fold the description into the name, so name from the label text alone.\n  const labelId = description && label ? `${id}-label` : undefined;\n\n  useLayoutEffect(() => {\n    register(value, Boolean(disabled));\n  }, [register, value, disabled]);\n  useLayoutEffect(() => () => unregister(value), [unregister, value]);\n\n  const reachable =\n    !disabled && (tabStop === null ? true : tabStop === value);\n\n  // Arrow keys move to the next enabled option in the group, wrapping at the\n  // ends, and select it as focus arrives, like native radio buttons.\n  const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {\n    const step =\n      event.key === \"ArrowDown\" || event.key === \"ArrowRight\"\n        ? 1\n        : event.key === \"ArrowUp\" || event.key === \"ArrowLeft\"\n          ? -1\n          : 0;\n    if (!step) return;\n    const group = event.currentTarget.closest('[role=\"radiogroup\"]');\n    const radios = Array.from(\n      group?.querySelectorAll<HTMLButtonElement>('[role=\"radio\"]') ?? [],\n    ).filter(\n      (radio) =>\n        !radio.disabled &&\n        radio.closest('[role=\"radiogroup\"]') === group,\n    );\n    const at = radios.indexOf(event.currentTarget);\n    if (at < 0 || radios.length < 2) return;\n    event.preventDefault();\n    const next = radios[(at + step + radios.length) % radios.length];\n    next.focus();\n    next.click();\n  };\n\n  return (\n    <label\n      htmlFor={id}\n      className={cn(\n        \"inline-flex gap-3\",\n        description ? \"items-start\" : \"items-center\",\n        disabled ? \"cursor-not-allowed\" : \"cursor-pointer\",\n        className,\n      )}\n    >\n      <motion.button\n        id={id}\n        type=\"button\"\n        role=\"radio\"\n        aria-checked={selected}\n        aria-labelledby={labelId}\n        aria-describedby={descriptionId}\n        disabled={disabled}\n        tabIndex={reachable ? 0 : -1}\n        onClick={() => !disabled && setValue(value)}\n        onKeyDown={onKeyDown}\n        whileTap={reduce || disabled ? undefined : { scale: 0.92 }}\n        transition={SPRING_PRESS}\n        data-state={selected ? \"checked\" : \"unchecked\"}\n        className={cn(\n          \"relative inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 outline-none transition-colors duration-200\",\n          \"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n          \"disabled:cursor-not-allowed disabled:opacity-60\",\n          selected\n            ? \"border-primary\"\n            : \"border-muted-foreground/50 hover:border-muted-foreground\",\n        )}\n      >\n        {selected ? (\n          <motion.span\n            layoutId={layoutId}\n            className=\"absolute inset-1 rounded-full bg-primary\"\n            transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n          />\n        ) : null}\n      </motion.button>\n      {label || description ? (\n        <span className={cn(\"flex min-w-0 flex-col gap-0.5 select-none\", disabled && \"opacity-60\")}>\n          {label ? (\n            <span\n              id={labelId}\n              // Geist sits low in a 20px line; a 16px line lifts the text onto the control.\n              className={cn(\"text-sm text-foreground\", description && \"leading-4\")}\n            >\n              {label}\n            </span>\n          ) : null}\n          {description ? (\n            <span id={descriptionId} className=\"text-xs text-muted-foreground\">\n              {description}\n            </span>\n          ) : null}\n        </span>\n      ) : null}\n    </label>\n  );\n}\n"},{"path":"components/motion/tooltip.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type PointerEvent as ReactPointerEvent,\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { TooltipSurface } from \"@/components/motion/tooltip-surface\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useHoverGesture } from \"@/lib/hooks/use-hover-gesture\";\nimport { useTapGesture } from \"@/lib/hooks/use-tap-gesture\";\nimport { assignRef } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\nimport { focusFromKeyboard, graceArea, inBox, inPolygon, watchModality } from \"./tooltip/grace\";\nimport { TooltipArrow, TooltipPositioner } from \"./tooltip/positioner\";\nimport {\n  type TooltipAlign,\n  type TooltipAnchor,\n  type TooltipPoint,\n  type TooltipSide,\n  useTooltipPointer,\n} from \"./tooltip/use-position\";\n\nexport type { TooltipAlign, TooltipSide };\n\n/* -------------------------------------------------------------------------- */\n/* Provider                                                                   */\n/* -------------------------------------------------------------------------- */\n\ninterface TooltipTiming {\n  /** Delay before a hover opens a tooltip (ms). */\n  delay: number;\n  /** Delay before a tooltip closes once the pointer has left it (ms). */\n  closeDelay: number;\n  /** After one tooltip closes, others open instantly for this long (ms). */\n  skipDelay: number;\n}\n\nconst TimingContext = createContext<TooltipTiming>({ delay: 120, closeDelay: 0, skipDelay: 300 });\n\nexport interface TooltipProviderProps extends Partial<TooltipTiming> {\n  children: ReactNode;\n}\n\n/** Shared timing for every tooltip inside it. Optional: tooltips work without one. */\nexport function TooltipProvider({ children, ...timing }: TooltipProviderProps) {\n  const parent = useContext(TimingContext);\n  const { delay = parent.delay, closeDelay = parent.closeDelay, skipDelay = parent.skipDelay } =\n    timing;\n  const value = useMemo(() => ({ delay, closeDelay, skipDelay }), [delay, closeDelay, skipDelay]);\n  return <TimingContext.Provider value={value}>{children}</TimingContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Root                                                                       */\n/* -------------------------------------------------------------------------- */\n\n// Moving along a toolbar should feel instant after the first label, and only\n// one label may show at a time: a keyboard-focused control and a hovered one\n// would otherwise both claim the screen.\nlet lastClosedAt = 0;\nlet current: { close: () => void } | null = null;\n\nfunction isEmpty(content: ReactNode) {\n  return content == null || content === false || content === \"\";\n}\n\ninterface TooltipContextValue {\n  open: boolean;\n  /** Show and hide without animating (keyboard focus, a warm toolbar, a replaced label). */\n  instant: boolean;\n  contentId: string;\n  labelId: string;\n  asLabel: boolean;\n  empty: boolean;\n  followCursor: boolean;\n  anchor: TooltipAnchor | null;\n  /** True when a TooltipTrigger owns the anchor; false for an external `anchorRef`. */\n  triggered: boolean;\n  floatingRef: RefObject<HTMLSpanElement | null>;\n  pointer: ReturnType<typeof useTooltipPointer>;\n  setTrigger: (element: TooltipAnchor | null) => void;\n  setEmpty: (empty: boolean) => void;\n  close: () => void;\n  onContentEnter: () => void;\n  onContentLeave: (event: ReactPointerEvent) => void;\n}\n\nconst TooltipContext = createContext<TooltipContextValue | null>(null);\n\nfunction useTooltipContext(part: string) {\n  const context = useContext(TooltipContext);\n  if (!context) throw new Error(`${part} must be used inside <Tooltip>`);\n  return context;\n}\n\nexport interface TooltipRootProps {\n  children?: ReactNode;\n  /** Whether the tooltip is shown, for controlled use. */\n  open?: boolean;\n  /** Whether the tooltip starts shown when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new state when the tooltip shows or hides. */\n  onOpenChange?: (open: boolean) => void;\n  /** Delay before showing on hover (ms). Keyboard focus shows immediately. */\n  delay?: number;\n  /** Delay before hiding once the pointer has left (ms). */\n  closeDelay?: number;\n  /** Never show, e.g. while the label it carries is already visible. */\n  disabled?: boolean;\n  /**\n   * Use the tooltip as the trigger's accessible name rather than its\n   * description. For icon-only controls whose only label is the tooltip.\n   */\n  asLabel?: boolean;\n  /** Follow real pointer coordinates; keyboard focus still uses the anchor. */\n  followCursor?: boolean;\n  /** Existing anchor for controlled integrations such as chart cells. */\n  anchorRef?: RefObject<TooltipAnchor | null>;\n  /** Id of the tooltip surface, for anchors that reference it themselves. */\n  id?: string;\n}\n\nfunction TooltipRoot({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  delay: delayProp,\n  closeDelay: closeDelayProp,\n  disabled = false,\n  asLabel = false,\n  followCursor = false,\n  anchorRef,\n  id,\n  initialEmpty = false,\n}: TooltipRootProps & { initialEmpty?: boolean }) {\n  const timing = useContext(TimingContext);\n  const delay = delayProp ?? timing.delay;\n  const closeDelay = closeDelayProp ?? timing.closeDelay;\n  const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);\n  const open = controlledOpen ?? uncontrolledOpen;\n  // Keyboard focus and a warm toolbar show the label at once; animating\n  // something seen this often only makes it feel slow.\n  const [instant, setInstant] = useState(false);\n  const [empty, setEmpty] = useState(initialEmpty);\n  const [trigger, setTrigger] = useState<TooltipAnchor | null>(null);\n  const [external, setExternal] = useState<TooltipAnchor | null>(null);\n  const anchor = anchorRef ? external : trigger;\n  const generatedId = useId();\n  const contentId = id ?? `${generatedId}-content`;\n  const labelId = `${generatedId}-label`;\n  const floatingRef = useRef<HTMLSpanElement | null>(null);\n  const anchorObject = useRef<TooltipAnchor | null>(null);\n  const pointer = useTooltipPointer(anchor, followCursor);\n\n  // An external ref can attach after this component renders; read it once it has.\n  useLayoutEffect(() => {\n    if (!anchorRef) return;\n    const element = anchorRef.current ?? null;\n    if (element !== external) setExternal(element);\n  });\n\n  // Everything the event listeners read, current without re-binding them.\n  const latest = useRef({ open, delay, closeDelay, disabled, empty, onOpenChange, controlled: false });\n  useLayoutEffect(() => {\n    anchorObject.current = anchor;\n    latest.current = {\n      open,\n      delay,\n      closeDelay,\n      disabled,\n      empty,\n      onOpenChange,\n      controlled: controlledOpen !== undefined,\n    };\n  });\n\n  const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const grace = useRef<(() => void) | null>(null);\n  const self = useRef<{ close: () => void }>({ close: () => {} });\n\n  const clearTimers = useCallback(() => {\n    if (openTimer.current) clearTimeout(openTimer.current);\n    if (closeTimer.current) clearTimeout(closeTimer.current);\n    openTimer.current = null;\n    closeTimer.current = null;\n  }, []);\n\n  const stopGrace = useCallback(() => {\n    grace.current?.();\n    grace.current = null;\n  }, []);\n\n  // Only a real change reaches the consumer: a pointer leaving a closed\n  // tooltip is not news.\n  const commit = useCallback((next: boolean) => {\n    if (latest.current.open === next) return;\n    if (!latest.current.controlled) setUncontrolledOpen(next);\n    latest.current.onOpenChange?.(next);\n  }, []);\n\n  const openNow = useCallback(\n    (now = false) => {\n      clearTimers();\n      stopGrace();\n      if (latest.current.disabled || latest.current.empty) return;\n      // The label being replaced leaves at once, so two never show together.\n      if (current && current !== self.current) current.close();\n      current = self.current;\n      setInstant(now);\n      commit(true);\n    },\n    [clearTimers, stopGrace, commit],\n  );\n\n  const finish = useCallback(\n    (now: boolean) => {\n      clearTimers();\n      stopGrace();\n      if (latest.current.open) lastClosedAt = Date.now();\n      if (current === self.current) current = null;\n      if (latest.current.open) setInstant(now);\n      commit(false);\n    },\n    [clearTimers, stopGrace, commit],\n  );\n  // Also a listener (window blur, outside press), so it takes no arguments.\n  const close = useCallback(() => finish(false), [finish]);\n  useLayoutEffect(() => {\n    self.current.close = () => finish(true);\n  }, [finish]);\n\n  const requestOpen = useCallback(() => {\n    clearTimers();\n    if (latest.current.open || latest.current.disabled || latest.current.empty) return;\n    // Warm: another label is still showing (the pointer is crossing to this\n    // one), or one closed a moment ago. Either way, skip the delay and the fade.\n    const warm =\n      (current !== null && current !== self.current) ||\n      Date.now() - lastClosedAt < timing.skipDelay;\n    if (warm) openNow(true);\n    else if (latest.current.delay <= 0) openNow();\n    else openTimer.current = setTimeout(() => openNow(), latest.current.delay);\n  }, [clearTimers, openNow, timing.skipDelay]);\n\n  const requestClose = useCallback(() => {\n    clearTimers();\n    if (latest.current.closeDelay > 0) {\n      closeTimer.current = setTimeout(close, latest.current.closeDelay);\n    } else close();\n  }, [clearTimers, close]);\n\n  // Hold the label open while the pointer crosses from one box toward the other.\n  const startGrace = useCallback(\n    (exit: TooltipPoint, from: Element, to: Element | null) => {\n      stopGrace();\n      if (!to) return requestClose();\n      const target = to.getBoundingClientRect();\n      const origin = from.getBoundingClientRect();\n      const corridor = graceArea(exit, target);\n      const onMove = (event: PointerEvent) => {\n        const point = { x: event.clientX, y: event.clientY };\n        if (inBox(point, target) || inBox(point, origin)) return;\n        if (!inPolygon(point, corridor)) requestClose();\n      };\n      document.addEventListener(\"pointermove\", onMove);\n      grace.current = () => document.removeEventListener(\"pointermove\", onMove);\n    },\n    [stopGrace, requestClose],\n  );\n\n  const hover = useHoverGesture();\n  const tap = useTapGesture<boolean>();\n\n  // Listeners go on the trigger itself rather than on cloned props, so a\n  // component that owns its own handlers keeps them, and no wrapper element\n  // sits between the control and its layout.\n  useEffect(() => {\n    if (anchorRef || !trigger) return;\n    watchModality();\n    // A mouse press dismisses the label and keeps it away until the pointer\n    // leaves; hovering a control you just clicked should not bring it back.\n    let suppressed = false;\n    // Focus that came from the keyboard holds the label open on its own.\n    let keyboardFocus = false;\n\n    const onEnter = (event: PointerEvent) => {\n      if (!hover.enter(event)) return;\n      stopGrace();\n      if (closeTimer.current) clearTimeout(closeTimer.current);\n      if (!suppressed) requestOpen();\n    };\n    const onLeave = (event: PointerEvent) => {\n      if (!hover.leave(event)) return;\n      suppressed = false;\n      if (keyboardFocus) return;\n      if (openTimer.current) {\n        clearTimers();\n        return;\n      }\n      if (latest.current.open && !followCursor) {\n        startGrace({ x: event.clientX, y: event.clientY }, trigger, floatingRef.current);\n      } else requestClose();\n    };\n    const onDown = (event: PointerEvent) => {\n      tap.start(event, latest.current.open);\n      if (event.pointerType === \"mouse\") {\n        suppressed = true;\n        close();\n      }\n    };\n    // A finger never hovers, and Safari does not focus a button on tap either,\n    // so the label is only reachable if the tap itself toggles it. The click\n    // carries no pointerType; the pointerdown before it says whether it was a\n    // tap, and keyboard activation has none at all.\n    const onClick = () => {\n      const gesture = tap.take();\n      if (!gesture || gesture.pointerType === \"mouse\") return;\n      if (gesture.state) close();\n      else openNow();\n    };\n    const onKey = () => tap.drop();\n    const onFocusIn = () => {\n      if (!focusFromKeyboard()) return;\n      keyboardFocus = true;\n      openNow(true);\n    };\n    const onFocusOut = (event: FocusEvent) => {\n      if (trigger.contains(event.relatedTarget as Node | null)) return;\n      const fromKeyboard = keyboardFocus;\n      keyboardFocus = false;\n      finish(fromKeyboard);\n    };\n\n    // Both element kinds dispatch the same events; one type keeps the listeners typed.\n    const el = trigger as HTMLElement;\n    el.addEventListener(\"pointerenter\", onEnter);\n    el.addEventListener(\"pointerleave\", onLeave);\n    el.addEventListener(\"pointerdown\", onDown);\n    el.addEventListener(\"pointercancel\", tap.drop);\n    el.addEventListener(\"click\", onClick);\n    el.addEventListener(\"keydown\", onKey);\n    el.addEventListener(\"focusin\", onFocusIn);\n    el.addEventListener(\"focusout\", onFocusOut);\n    return () => {\n      el.removeEventListener(\"pointerenter\", onEnter);\n      el.removeEventListener(\"pointerleave\", onLeave);\n      el.removeEventListener(\"pointerdown\", onDown);\n      el.removeEventListener(\"pointercancel\", tap.drop);\n      el.removeEventListener(\"click\", onClick);\n      el.removeEventListener(\"keydown\", onKey);\n      el.removeEventListener(\"focusin\", onFocusIn);\n      el.removeEventListener(\"focusout\", onFocusOut);\n    };\n  }, [\n    anchorRef,\n    trigger,\n    followCursor,\n    hover,\n    tap,\n    requestOpen,\n    requestClose,\n    openNow,\n    close,\n    finish,\n    clearTimers,\n    stopGrace,\n    startGrace,\n  ]);\n\n  // While open, a trigger that turns disabled loses focus without a blur event,\n  // and a window that loses focus never reports the pointer leaving.\n  useEffect(() => {\n    if (!open || anchorRef || !trigger) return;\n    const observer = new MutationObserver(() => {\n      if (trigger.matches(\":disabled, [aria-disabled='true']\")) close();\n    });\n    observer.observe(trigger, { attributes: true, attributeFilter: [\"disabled\", \"aria-disabled\"] });\n    window.addEventListener(\"blur\", close);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"blur\", close);\n    };\n  }, [open, anchorRef, trigger, close]);\n\n  // A chart drives its own open state and swaps content as it goes; only a\n  // trigger-owned label closes itself for having nothing to say.\n  useEffect(() => {\n    if (disabled || (empty && !anchorRef)) close();\n  }, [disabled, empty, anchorRef, close]);\n\n  useEffect(\n    () => () => {\n      clearTimers();\n      stopGrace();\n      if (current === self.current) current = null;\n    },\n    [clearTimers, stopGrace],\n  );\n\n  const insideTooltip = useCallback(\n    (target: Element) => Boolean(floatingRef.current?.contains(target)),\n    [],\n  );\n  // ...and closed by the next tap that lands somewhere else, or Escape. The\n  // label covers nothing interactive, so that tap passes through to what it hit.\n  // Escape is a key press, so the label goes at once.\n  const dismiss = useCallback((reason: DismissReason) => finish(reason === \"escape\"), [finish]);\n  useDismiss(open, dismiss, anchorObject, { ignore: insideTooltip });\n\n  const onContentEnter = useCallback(() => {\n    stopGrace();\n    clearTimers();\n  }, [stopGrace, clearTimers]);\n\n  const onContentLeave = useCallback(\n    (event: ReactPointerEvent) => {\n      const floating = floatingRef.current;\n      if (!floating) return;\n      if (anchorRef) {\n        // Bridge the small gap back onto a chart; it reopens on its own terms.\n        clearTimers();\n        closeTimer.current = setTimeout(close, 100);\n        return;\n      }\n      startGrace({ x: event.clientX, y: event.clientY }, floating, anchorObject.current);\n    },\n    [anchorRef, clearTimers, close, startGrace],\n  );\n\n  const value = useMemo<TooltipContextValue>(\n    () => ({\n      open,\n      instant,\n      contentId,\n      labelId,\n      asLabel,\n      empty,\n      followCursor,\n      anchor,\n      triggered: !anchorRef,\n      floatingRef,\n      pointer,\n      setTrigger,\n      setEmpty,\n      close,\n      onContentEnter,\n      onContentLeave,\n    }),\n    [\n      open,\n      instant,\n      contentId,\n      labelId,\n      asLabel,\n      empty,\n      followCursor,\n      anchor,\n      anchorRef,\n      pointer,\n      close,\n      onContentEnter,\n      onContentLeave,\n    ],\n  );\n\n  return <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Trigger                                                                    */\n/* -------------------------------------------------------------------------- */\n\nfunction mergeIds(...ids: unknown[]) {\n  return ids.filter((value) => typeof value === \"string\" && value).join(\" \") || undefined;\n}\n\nexport interface TooltipTriggerProps extends ComponentProps<\"button\"> {\n  /** Use the single child element as the trigger instead of rendering a button. */\n  asChild?: boolean;\n}\n\nexport function TooltipTrigger({ asChild = false, children, ref, ...props }: TooltipTriggerProps) {\n  const { open, contentId, labelId, asLabel, empty, setTrigger } =\n    useTooltipContext(\"TooltipTrigger\");\n  const child = asChild && isValidElement(children) ? children : null;\n  const childProps = (child?.props ?? props) as Record<string, unknown>;\n  const childRef = child ? (childProps.ref as Ref<TooltipAnchor> | undefined) : undefined;\n  const attached = useRef<TooltipAnchor | null>(null);\n\n  const setRef = useCallback(\n    (element: TooltipAnchor | null) => {\n      attached.current = element;\n      setTrigger(element);\n      assignRef(childRef ?? (ref as Ref<TooltipAnchor> | undefined), element);\n    },\n    [setTrigger, childRef, ref],\n  );\n\n  useEffect(() => {\n    if (process.env.NODE_ENV !== \"production\" && child && !attached.current) {\n      console.warn(\n        \"TooltipTrigger: the child did not attach a ref, so the tooltip has nothing to listen to. Render a DOM element or a component that passes `ref` through.\",\n      );\n    }\n  }, [child]);\n\n  const aria = asLabel\n    ? {\n        \"aria-labelledby\": empty\n          ? (childProps[\"aria-labelledby\"] as string | undefined)\n          : labelId,\n      }\n    : {\n        \"aria-describedby\": mergeIds(\n          childProps[\"aria-describedby\"],\n          open && !empty ? contentId : undefined,\n        ),\n      };\n\n  if (asChild) {\n    if (!child) return children;\n    return cloneElement(child as ReactElement<Record<string, unknown>>, { ref: setRef, ...aria });\n  }\n\n  return (\n    <button\n      type=\"button\"\n      data-state={open ? \"open\" : \"closed\"}\n      {...props}\n      ref={setRef as Ref<HTMLButtonElement>}\n      {...aria}\n    >\n      {children}\n    </button>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Content                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface TooltipContentProps {\n  children?: ReactNode;\n  /** Preferred side of the anchor. Flips when there is no room. Default: \"top\" */\n  side?: TooltipSide;\n  /** Alignment along the chosen side. Default: \"center\" */\n  align?: TooltipAlign;\n  /** Gap between anchor and tooltip (px). */\n  sideOffset?: number;\n  /** Draw an arrow pointing at the anchor. */\n  arrow?: boolean;\n  /** Point within the anchor, as fractions of its rendered width and height. */\n  anchorPoint?: TooltipPoint;\n  /** Classes merged onto the tooltip surface. */\n  className?: string;\n}\n\nexport function TooltipContent({\n  children,\n  side = \"top\",\n  align = \"center\",\n  sideOffset,\n  arrow = false,\n  anchorPoint,\n  className,\n}: TooltipContentProps) {\n  const {\n    open,\n    instant,\n    contentId,\n    labelId,\n    asLabel,\n    followCursor,\n    anchor,\n    floatingRef,\n    pointer,\n    setEmpty,\n    close,\n    onContentEnter,\n    onContentLeave,\n  } = useTooltipContext(\"TooltipContent\");\n  const empty = isEmpty(children);\n  const arrowRef = useRef<SVGSVGElement | null>(null);\n\n  useLayoutEffect(() => {\n    setEmpty(empty);\n  }, [empty, setEmpty]);\n\n  if (typeof document === \"undefined\") return null;\n\n  return createPortal(\n    <>\n      {/* The name has to exist while the label is closed, so it lives apart from the surface. */}\n      {asLabel && !empty ? (\n        <span id={labelId} hidden>\n          {children}\n        </span>\n      ) : null}\n      {/* `custom` reaches a surface that is already exiting, so a label closed\n          from the keyboard or replaced by a neighbour leaves without animating. */}\n      <AnimatePresence custom={instant}>\n        {open && !empty ? (\n          <TooltipPositioner\n            key=\"tooltip\"\n            anchor={anchor}\n            floatingRef={floatingRef}\n            arrowRef={arrow ? arrowRef : undefined}\n            anchorPoint={anchorPoint}\n            followCursor={followCursor}\n            side={side}\n            align={align}\n            sideOffset={sideOffset}\n            onDismiss={close}\n            pointer={pointer}\n          >\n            {(positioned, isPresent, placedSide) => (\n              <TooltipSurface\n                id={asLabel ? undefined : contentId}\n                aria-hidden={asLabel || undefined}\n                ready={positioned}\n                instant={instant}\n                onPointerEnter={onContentEnter}\n                onPointerLeave={onContentLeave}\n                style={{ pointerEvents: isPresent && !followCursor ? \"auto\" : \"none\" }}\n                className={cn(\n                  \"max-w-[min(20rem,calc(100vw-16px))] whitespace-normal break-words\",\n                  arrow && \"relative\",\n                  className,\n                )}\n              >\n                {children}\n                {arrow ? <TooltipArrow ref={arrowRef} side={placedSide} /> : null}\n              </TooltipSurface>\n            )}\n          </TooltipPositioner>\n        ) : null}\n      </AnimatePresence>\n    </>,\n    document.body,\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Tooltip (root, or one-line shorthand when given `content`)                 */\n/* -------------------------------------------------------------------------- */\n\nexport interface TooltipProps\n  extends TooltipRootProps,\n    Omit<TooltipContentProps, \"children\" | \"className\"> {\n  /**\n   * Shorthand: the tooltip's content. With it, `children` is the trigger\n   * element; without it, compose `TooltipTrigger` and `TooltipContent`.\n   */\n  content?: ReactNode;\n  /** Shorthand only: classes for the tooltip surface. */\n  className?: string;\n}\n\nexport function Tooltip(props: TooltipProps) {\n  if (!(\"content\" in props)) return <TooltipRoot {...props} />;\n  const {\n    content,\n    children,\n    side,\n    align,\n    sideOffset,\n    arrow,\n    anchorPoint,\n    className,\n    ...root\n  } = props;\n  if (!root.anchorRef && !isValidElement(children)) return children ?? null;\n  return (\n    <TooltipRoot {...root} initialEmpty={isEmpty(content)}>\n      {isValidElement(children) ? <TooltipTrigger asChild>{children}</TooltipTrigger> : null}\n      <TooltipContent\n        side={side}\n        align={align}\n        sideOffset={sideOffset}\n        arrow={arrow}\n        anchorPoint={anchorPoint}\n        className={className}\n      >\n        {content}\n      </TooltipContent>\n    </TooltipRoot>\n  );\n}\n"},{"path":"components/agents/agent-code.tsx","type":"util","content":"\"use client\";\n\nimport {\n  type CSSProperties,\n  Fragment,\n  useEffect,\n  useState,\n} from \"react\";\nimport { createHighlighter, type Highlighter } from \"shiki\";\nimport { cn } from \"@/lib/utils\";\n\nexport type AgentCodeLanguage =\n  | \"bash\"\n  | \"diff\"\n  | \"json\"\n  | \"text\"\n  | \"tsx\"\n  | \"typescript\";\n\nexport interface AgentCodeToken {\n  content: string;\n  offset: number;\n  light?: string;\n  dark?: string;\n}\n\nexport type AgentCodeTokenLines = AgentCodeToken[][];\n\nexport interface AgentCodeProps {\n  code: string;\n  language?: AgentCodeLanguage;\n  className?: string;\n}\n\nexport interface AgentCodeLineProps {\n  code: string;\n  tokens?: AgentCodeToken[];\n  className?: string;\n}\n\nconst LIGHT_THEME = \"github-light-high-contrast\";\nconst DARK_THEME = \"github-dark-high-contrast\";\nlet agentCodeHighlighter: Promise<Highlighter> | null = null;\n\n// Streamed code changes on every chunk, and each version is a new key, so the\n// cache keeps only the most recently used entries.\nconst TOKEN_CACHE_LIMIT = 50;\nconst tokenCache = new Map<string, AgentCodeTokenLines>();\n\nfunction readTokens(key: string) {\n  const lines = tokenCache.get(key);\n  if (lines) {\n    tokenCache.delete(key);\n    tokenCache.set(key, lines);\n  }\n  return lines;\n}\n\nfunction storeTokens(key: string, lines: AgentCodeTokenLines) {\n  tokenCache.delete(key);\n  tokenCache.set(key, lines);\n  while (tokenCache.size > TOKEN_CACHE_LIMIT) {\n    const oldest = tokenCache.keys().next().value;\n    if (oldest === undefined) break;\n    tokenCache.delete(oldest);\n  }\n}\n\nfunction getAgentCodeHighlighter() {\n  if (!agentCodeHighlighter) {\n    agentCodeHighlighter = createHighlighter({\n      themes: [LIGHT_THEME, DARK_THEME],\n      langs: [\"bash\", \"diff\", \"json\", \"tsx\", \"typescript\"],\n    });\n    // A failed load is not kept, so the next block tries again.\n    agentCodeHighlighter.catch(() => {\n      agentCodeHighlighter = null;\n    });\n  }\n  return agentCodeHighlighter;\n}\n\nfunction tokenCacheKey(code: string, language: AgentCodeLanguage) {\n  return `${language}\\u0000${code}`;\n}\n\nexport function useAgentCodeTokens(\n  code: string,\n  language: AgentCodeLanguage,\n) {\n  const key = tokenCacheKey(code, language);\n  const cached = tokenCache.get(key);\n  const [result, setResult] = useState<{\n    key: string;\n    code: string;\n    language: AgentCodeLanguage;\n    lines: AgentCodeTokenLines;\n  } | null>(cached ? { key, code, language, lines: cached } : null);\n\n  useEffect(() => {\n    const current = readTokens(key);\n    if (current) {\n      setResult({ key, code, language, lines: current });\n      return;\n    }\n\n    let cancelled = false;\n    getAgentCodeHighlighter().then((highlighter) => {\n      if (cancelled) return;\n      const lines = highlighter\n        .codeToTokensWithThemes(code, {\n          lang: language,\n          themes: {\n            light: LIGHT_THEME,\n            dark: DARK_THEME,\n          },\n        })\n        .map((line) =>\n          line.map((token) => ({\n            content: token.content,\n            offset: token.offset,\n            light: token.variants.light?.color,\n            dark: token.variants.dark?.color,\n          })),\n      );\n      storeTokens(key, lines);\n      setResult({ key, code, language, lines });\n    }, () => {\n      // Highlighting is decoration: the code still renders as plain text.\n    });\n    return () => {\n      cancelled = true;\n    };\n  }, [code, key, language]);\n\n  if (result?.key === key) return result.lines;\n  if (result?.language === language && code.startsWith(result.code)) {\n    return result.lines;\n  }\n  return null;\n}\n\nexport function AgentCodeLine({\n  code,\n  tokens,\n  className,\n}: AgentCodeLineProps) {\n  // While code streams, the tokens can lag a few characters behind the line.\n  // Keep the coloured part and show the new characters plain after it: the\n  // text is always current, and nothing already coloured flashes back to plain.\n  const tokenText = tokens?.map((token) => token.content).join(\"\") ?? \"\";\n  const usable = tokens && code.startsWith(tokenText) ? tokens : undefined;\n  const rest = usable ? code.slice(tokenText.length) : \"\";\n  return (\n    <span className={className}>\n      {usable\n        ? usable.map((token) => (\n            <span\n              key={`${token.offset}-${token.content}`}\n              style={\n                {\n                  \"--agent-code-light\": token.light ?? \"currentColor\",\n                  \"--agent-code-dark\": token.dark ?? token.light ?? \"currentColor\",\n                } as CSSProperties\n              }\n              className=\"text-[var(--agent-code-light)] dark:text-[var(--agent-code-dark)]\"\n            >\n              {token.content}\n            </span>\n          ))\n        : code}\n      {rest}\n    </span>\n  );\n}\n\nexport function AgentCode({\n  code,\n  language = \"bash\",\n  className,\n}: AgentCodeProps) {\n  const tokens = useAgentCodeTokens(code, language);\n  let offset = 0;\n  const lines = code.split(\"\\n\").map((content) => {\n    const line = { content, offset };\n    offset += content.length + 1;\n    return line;\n  });\n\n  return (\n    <pre\n      className={cn(\n        \"m-0 overflow-x-auto whitespace-pre font-mono text-xs leading-5 text-foreground/85\",\n        className,\n      )}\n    >\n      <code>\n        {lines.map((line, index) => (\n          <Fragment key={line.offset}>\n            <AgentCodeLine code={line.content} tokens={tokens?.[index]} />\n            {index < lines.length - 1 ? \"\\n\" : null}\n          </Fragment>\n        ))}\n      </code>\n    </pre>\n  );\n}\n"},{"path":"lib/hooks/use-copy.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\n/** How long the copied state holds after a copy, in ms. */\nconst COPIED_MS = 1600;\n\n/**\n * A copy action and a `copied` flag that holds for a moment after it works.\n *\n * `copy` runs `onCopy` when given, else writes `text` to the clipboard. The\n * flag turns on only once that succeeded: no clipboard (an insecure origin),\n * a refused write or a throwing `onCopy` leave it off rather than claiming a\n * copy that never happened.\n */\nexport function useCopy({\n  text,\n  onCopy,\n}: {\n  text?: string;\n  onCopy?: () => void | Promise<void>;\n}) {\n  const [copied, setCopied] = useState(false);\n  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n  useEffect(() => () => clearTimeout(timer.current), []);\n\n  const copy = useCallback(async () => {\n    try {\n      if (onCopy) await onCopy();\n      else if (text !== undefined && navigator.clipboard) {\n        await navigator.clipboard.writeText(text);\n      } else return;\n    } catch {\n      return;\n    }\n    setCopied(true);\n    clearTimeout(timer.current);\n    timer.current = setTimeout(() => setCopied(false), COPIED_MS);\n  }, [onCopy, text]);\n\n  return { copied, copy };\n}\n"},{"path":"lib/hooks/use-hover-capable.ts","type":"util","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Returns true only on devices that have a true hover (mouse / trackpad).\n * Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere\n * - gate hover-only effects (scale lifts, magnetic pulls) behind this.\n */\nexport function useHoverCapable() {\n  const [canHover, setCanHover] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\" || !window.matchMedia) return;\n    const mq = window.matchMedia(\"(hover: hover) and (pointer: fine)\");\n    const update = () => setCanHover(mq.matches);\n    update();\n    mq.addEventListener?.(\"change\", update);\n    return () => mq.removeEventListener?.(\"change\", update);\n  }, []);\n\n  return canHover;\n}\n"},{"path":"components/agents/loading-states/messages.ts","type":"util","content":"/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const loadingStatesMessages = {\n  thinking: \"Thinking…\",\n  churning: \"Churning\",\n  inProgress: \"{label}, in progress\",\n  reasoning: \"Reasoning\",\n  phraseThinking: \"Thinking\",\n  phraseReading: \"Reading the context\",\n  phraseConnecting: \"Connecting the details\",\n  phraseForming: \"Forming a response\",\n};\n\nexport type LoadingStatesMessages = typeof loadingStatesMessages;\n"},{"path":"components/motion/text-shimmer.tsx","type":"util","content":"import { cn } from \"@/lib/utils\";\nimport type { ElementType, ReactNode } from \"react\";\nimport {\n  TEXT_SHIMMER_CLASS_NAME,\n  TEXT_SHIMMER_KEYFRAMES,\n  textShimmerStyle,\n} from \"@/lib/text-shimmer\";\n\nexport interface TextShimmerProps {\n  children: ReactNode;\n  /** Element to render the text as. Default: \"span\" */\n  as?: ElementType;\n  /** Length of one shimmer sweep (s). Default: 2.5 */\n  duration?: number;\n  /** Classes merged onto the text element. */\n  className?: string;\n}\n\nexport function TextShimmer({ children, as: Comp = \"span\", duration = 2.5, className }: TextShimmerProps) {\n  return (\n    <>\n      <style>\n        {TEXT_SHIMMER_KEYFRAMES}\n      </style>\n      <Comp\n        style={textShimmerStyle(duration)}\n        className={cn(\n          \"inline-block\",\n          TEXT_SHIMMER_CLASS_NAME,\n          className,\n        )}\n      >\n        {children}\n      </Comp>\n    </>\n  );\n}\n"},{"path":"components/agents/message-context.tsx","type":"util","content":"\"use client\";\n\nimport { createContext } from \"react\";\n\nexport type MessageSide = \"start\" | \"end\";\n\nexport const MessageSideContext = createContext<MessageSide | undefined>(\n  undefined,\n);\n"},{"path":"lib/merge-refs.ts","type":"util","content":"import type { Ref } from \"react\";\n\n/** Points a callback or object ref at `value`. */\nexport function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) ref.current = value;\n}\n\n/** One callback ref that sets every ref it is given. */\nexport function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) assignRef(ref, node);\n  };\n}\n"},{"path":"components/motion/preview-rail.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type MouseEvent,\n  type PointerEvent,\n  type ReactNode,\n  useCallback,\n  useId,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_LAYOUT } from \"@/lib/ease\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useHoverGesture } from \"@/lib/hooks/use-hover-gesture\";\nimport { useTapGesture } from \"@/lib/hooks/use-tap-gesture\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const previewRailMessages = {\n  label: \"Section navigation\",\n};\n\nexport type PreviewRailMessages = typeof previewRailMessages;\n\nexport interface PreviewRailItem {\n  /** Unique key, used for the active item and passed to `onActiveChange`. */\n  id: string;\n  /** Title of the preview card and the tick's accessible name. */\n  label: string;\n  /** Accessible name for the tick when it should differ from `label`. */\n  ariaLabel?: string;\n  /** Muted text under the title in the preview card. */\n  description?: ReactNode;\n  /** Makes the tick a link; on touch, the first tap shows the preview. */\n  href?: string;\n  /** Link target for `href`. */\n  target?: \"_blank\" | \"_self\" | \"_parent\" | \"_top\";\n  /** Link `rel`. Default: \"noreferrer noopener\" when `target` is \"_blank\" */\n  rel?: string;\n}\n\nexport interface PreviewRailProps {\n  /** Rail entries, each a tick with a preview card and an optional link. */\n  items: PreviewRailItem[];\n  /** Accessible name for the rail's nav element. Default: \"Section navigation\" */\n  label?: string;\n  /** Lay the ticks out in a column or a row. Default: \"vertical\" */\n  orientation?: \"vertical\" | \"horizontal\";\n  /** The selected item id, for controlled use. */\n  activeId?: string;\n  /** The initial selected item id when uncontrolled. Default: the first item. */\n  defaultActiveId?: string;\n  /** Called with the item id when an item is selected. */\n  onActiveChange?: (id: string) => void;\n  /** Called with the item when it is clicked or tapped. */\n  onItemSelect?: (item: PreviewRailItem) => void;\n  /** Custom content for the hover card. Default: the item's label and description. */\n  renderPreview?: (item: PreviewRailItem) => ReactNode;\n  /** Show a preview card beside the hovered or focused tick. Default: true */\n  showPreview?: boolean;\n  /** Which side of the rail the vertical preview card sits on. Default: \"after\" */\n  previewSide?: \"before\" | \"after\";\n  /** Keep the selected tick lit when nothing is hovered or focused. Default: false */\n  highlightActive?: boolean;\n  /** Length of each tick's slot along the rail (px). Default: 24 */\n  itemSize?: number;\n  children?: ReactNode;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes merged onto the nav element that holds the ticks. */\n  railClassName?: string;\n  /** Classes merged onto the layer that positions the preview cards. */\n  previewContainerClassName?: string;\n  /** Classes merged onto the wrapper around the shown preview card. */\n  previewClassName?: string;\n  /** Override any built-in string. */\n  labels?: Partial<PreviewRailMessages>;\n}\n\nfunction DefaultPreview({ item }: { item: PreviewRailItem }) {\n  return (\n    <div\n      data-slot=\"preview-rail-card\"\n      className=\"rounded-2xl border border-border bg-card p-4 shadow-sm\"\n    >\n      <p\n        data-slot=\"preview-rail-title\"\n        className=\"font-medium text-card-foreground\"\n      >\n        {item.label}\n      </p>\n      {item.description ? (\n        <div\n          data-slot=\"preview-rail-description\"\n          className=\"mt-1 text-sm leading-6 text-muted-foreground\"\n        >\n          {item.description}\n        </div>\n      ) : null}\n    </div>\n  );\n}\n\nexport function PreviewRail({\n  items,\n  label: labelProp,\n  orientation = \"vertical\",\n  activeId,\n  defaultActiveId,\n  onActiveChange,\n  onItemSelect,\n  renderPreview,\n  showPreview = true,\n  previewSide = \"after\",\n  highlightActive = false,\n  itemSize = 24,\n  children,\n  className,\n  railClassName,\n  previewContainerClassName,\n  previewClassName,\n  labels,\n}: PreviewRailProps) {\n  const t = useMessages(\"previewRail\", previewRailMessages, labels);\n  const label = labelProp ?? t(\"label\");\n  const uid = useId();\n  const reduce = useReducedMotion();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const [internalActiveId, setInternalActiveId] = useState(\n    defaultActiveId ?? items[0]?.id ?? \"\",\n  );\n  const [hoveredId, setHoveredId] = useState<string | null>(null);\n  // A finger cannot hover, so a tap lights the tick instead. Kept apart from\n  // the hovered one: they end in different ways, and a stray mouse move must\n  // not clear a tick the keyboard or a tap chose.\n  const [pinnedId, setPinnedId] = useState<string | null>(null);\n  const [focusedId, setFocusedId] = useState<string | null>(null);\n  // A click carries no pointerType, so the pointerdown before it is what says\n  // whether the activation was a tap. Keyboard activation has none at all.\n  const tap = useTapGesture<boolean>();\n  const hover = useHoverGesture();\n\n  const clearPinned = useCallback(() => setPinnedId(null), []);\n\n  // The next tap outside the rail stands in for the pointer leaving it. The\n  // card is a preview, so that tap passes through to whatever it landed on.\n  useDismiss(pinnedId !== null, clearPinned, rootRef);\n\n  const requestedActiveId = activeId ?? internalActiveId;\n  const selectedId = items.some((item) => item.id === requestedActiveId)\n    ? requestedActiveId\n    : (items[0]?.id ?? \"\");\n  const displayedId = hoveredId ?? pinnedId ?? focusedId ?? \"\";\n  const highlightedId = displayedId || (highlightActive ? selectedId : \"\");\n  const displayedIndex = items.findIndex((item) => item.id === highlightedId);\n  const rowTemplate = items.length\n    ? `repeat(${items.length}, ${itemSize}px)`\n    : undefined;\n  const isHorizontal = orientation === \"horizontal\";\n\n  const selectItem = (id: string) => {\n    if (activeId === undefined) setInternalActiveId(id);\n    onActiveChange?.(id);\n  };\n\n  return (\n    <motion.div\n      layoutRoot\n      ref={rootRef}\n      onBlur={(event) => {\n        // Both tick sources leave with the focus: a tap does not always land\n        // focus, but when it does, tabbing away must not strand the card.\n        if (!event.currentTarget.contains(event.relatedTarget)) {\n          setFocusedId(null);\n          setPinnedId(null);\n        }\n      }}\n      className={cn(\n        \"isolate relative flex w-full overflow-visible\",\n        isHorizontal\n          ? \"min-h-64 flex-col items-center justify-center\"\n          : \"min-h-80\",\n        className,\n      )}\n    >\n      <nav\n        aria-label={label}\n        onPointerLeave={(event) => {\n          // A touch pointer leaves on lift, which would clear the tick the tap\n          // just chose - that one is cleared by the outside tap instead.\n          if (hover.leave(event)) setHoveredId(null);\n        }}\n        style={\n          isHorizontal\n            ? { gridTemplateColumns: rowTemplate }\n            : { gridTemplateRows: rowTemplate }\n        }\n        className={cn(\n          \"relative z-10 grid shrink-0\",\n          isHorizontal\n            ? \"h-12 w-fit max-w-full self-center justify-center\"\n            : \"w-12 content-center\",\n          railClassName,\n        )}\n      >\n        {items.map((item, index) => {\n          const selected = item.id === selectedId;\n          const highlighted = item.id === highlightedId;\n          const distance =\n            displayedIndex < 0 ? Number.POSITIVE_INFINITY : Math.abs(index - displayedIndex);\n          const scale = highlighted\n            ? 1\n            : distance === 1\n              ? 0.68\n              : distance === 2\n                ? 0.44\n                : 0.25;\n\n          const itemContent = (\n            <>\n              <motion.span\n                data-slot=\"preview-rail-tick\"\n                aria-hidden=\"true\"\n                animate={isHorizontal ? { scaleY: scale } : { scaleX: scale }}\n                transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n                className={cn(\n                  \"block bg-current\",\n                  isHorizontal\n                    ? \"h-12 w-0.5 origin-bottom\"\n                    : \"h-0.5 w-12 origin-left\",\n                  highlighted ? \"text-foreground\" : undefined,\n                )}\n              />\n            </>\n          );\n\n          const sharedClassName = cn(\n            \"relative flex text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n            isHorizontal\n              ? \"h-12 w-6 items-end justify-center\"\n              : \"h-6 w-12 items-center\",\n          );\n          const sharedStyle = isHorizontal\n            ? { width: itemSize }\n            : { height: itemSize };\n          const handlePointerEnter = (event: PointerEvent<HTMLElement>) => {\n            if (hover.enter(event)) setHoveredId(item.id);\n          };\n          const handlePointerDown = (event: PointerEvent<HTMLElement>) => {\n            tap.start(event, pinnedId === item.id);\n            setFocusedId(null);\n          };\n          // A gesture the platform takes away sends no click, and a key press\n          // starts an activation that never had a pointer behind it: either\n          // one leaves a record the next click would read as a tap of its own.\n          const dropGesture = () => tap.drop();\n          const handleFocus = (currentTarget: HTMLElement) => {\n            if (currentTarget.matches(\":focus-visible\")) {\n              setFocusedId(item.id);\n            }\n          };\n          const handleSelect = (event: MouseEvent<HTMLElement>) => {\n            const gesture = tap.take();\n            const tapped =\n              gesture !== null && gesture.pointerType !== \"mouse\";\n\n            if (tapped) {\n              // A link would otherwise show its preview and leave the page in\n              // the same tap, so the card is never read: the first tap lights\n              // the tick, the second follows the link.\n              if (item.href && !gesture.state) {\n                event.preventDefault();\n                setPinnedId(item.id);\n                return;\n              }\n              setPinnedId(item.id);\n            }\n\n            selectItem(item.id);\n            onItemSelect?.(item);\n          };\n\n          return item.href ? (\n            <a\n              key={item.id}\n              data-slot=\"preview-rail-item\"\n              href={item.href}\n              target={item.target}\n              rel={\n                item.rel ??\n                (item.target === \"_blank\" ? \"noreferrer noopener\" : undefined)\n              }\n              aria-label={item.ariaLabel ?? item.label}\n              aria-current={selected ? \"page\" : undefined}\n              onPointerEnter={handlePointerEnter}\n              onPointerDown={handlePointerDown}\n              onPointerCancel={dropGesture}\n              onKeyDown={dropGesture}\n              onFocus={(event) => handleFocus(event.currentTarget)}\n              onClick={handleSelect}\n              style={sharedStyle}\n              className={sharedClassName}\n            >\n              {itemContent}\n            </a>\n          ) : (\n            <button\n              key={item.id}\n              data-slot=\"preview-rail-item\"\n              type=\"button\"\n              aria-label={item.ariaLabel ?? item.label}\n              aria-current={selected ? \"location\" : undefined}\n              onPointerEnter={handlePointerEnter}\n              onPointerDown={handlePointerDown}\n              onPointerCancel={dropGesture}\n              onKeyDown={dropGesture}\n              onFocus={(event) => handleFocus(event.currentTarget)}\n              onClick={handleSelect}\n              style={sharedStyle}\n              className={sharedClassName}\n            >\n              {itemContent}\n            </button>\n          );\n        })}\n      </nav>\n\n      {showPreview ? (\n        <div\n          aria-hidden=\"true\"\n          style={\n            isHorizontal\n              ? { gridTemplateColumns: rowTemplate }\n              : { gridTemplateRows: rowTemplate }\n          }\n          className={cn(\n            \"pointer-events-none absolute z-50 grid\",\n            isHorizontal\n              ? \"top-1/2 left-1/2 h-5 w-fit max-w-full -translate-x-1/2 -translate-y-1/2 justify-center\"\n              : previewSide === \"before\"\n                ? \"inset-y-0 right-16 left-4 content-center\"\n                : \"inset-y-0 right-4 left-16 content-center\",\n            previewContainerClassName,\n          )}\n        >\n          {items.map((item) => (\n            <div\n              key={item.id}\n              style={\n                isHorizontal ? { width: itemSize } : { height: itemSize }\n              }\n              className={cn(\n                \"relative flex items-center\",\n                isHorizontal ? \"justify-center\" : undefined,\n              )}\n            >\n              {item.id === displayedId ? (\n                <div\n                  className={cn(\n                    isHorizontal\n                      ? \"absolute bottom-12 left-1/2 w-72 -translate-x-1/2\"\n                      : cn(\n                          \"w-full max-w-sm\",\n                          previewSide === \"before\" && \"ml-auto\",\n                        ),\n                    previewClassName,\n                  )}\n                >\n                  <motion.div\n                    layoutId={`preview-rail-card-${uid}`}\n                    transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n                  >\n                    <AnimatePresence mode=\"wait\" initial={false}>\n                      <motion.div\n                        key={item.id}\n                        initial={\n                          reduce\n                            ? { opacity: 0 }\n                            : { opacity: 0, y: 4, filter: \"blur(6px)\" }\n                        }\n                        animate={\n                          reduce\n                            ? { opacity: 1 }\n                            : { opacity: 1, y: 0, filter: \"blur(0px)\" }\n                        }\n                        exit={\n                          reduce\n                            ? { opacity: 0 }\n                            : {\n                                opacity: 0,\n                                y: -2,\n                                filter: \"blur(4px)\",\n                                transition: {\n                                  duration: 0.12,\n                                  ease: EASE_OUT,\n                                },\n                              }\n                        }\n                        transition={{\n                          duration: reduce ? 0 : 0.18,\n                          ease: EASE_OUT,\n                        }}\n                      >\n                        {renderPreview ? (\n                          renderPreview(item)\n                        ) : (\n                          <DefaultPreview item={item} />\n                        )}\n                      </motion.div>\n                    </AnimatePresence>\n                  </motion.div>\n                </div>\n              ) : null}\n            </div>\n          ))}\n        </div>\n      ) : null}\n\n      {children ? (\n        <div className=\"min-h-0 min-w-0 flex-1\">{children}</div>\n      ) : null}\n    </motion.div>\n  );\n}\n"},{"path":"components/motion/dropdown-menu.tsx","type":"util","content":"\"use client\";\n\nimport { Check, ChevronRight } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type MouseEvent as ReactMouseEvent,\n  type MutableRefObject,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { enabledItems } from \"@/components/motion/menu/use-menu-navigation\";\nimport { SPRING_PANEL } from \"@/lib/ease\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { PresenceGate } from \"@/lib/presence-gate\";\nimport { useSound } from \"@/lib/sound\";\nimport { closeSound } from \"@/lib/sounds/close\";\nimport { openSound } from \"@/lib/sounds/open\";\nimport { selectSound } from \"@/lib/sounds/select\";\nimport { assignRef } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\nimport { type FocusTarget, RootContext, type RootContextValue, useLevel, useRoot } from \"./dropdown-menu/context\";\nimport { type DropdownMenuItemProps, ItemBase } from \"./dropdown-menu/item-base\";\nimport { MenuPanel } from \"./dropdown-menu/menu-panel\";\nimport type { Align } from \"./dropdown-menu/placement\";\n\nexport type { DropdownMenuItemProps } from \"./dropdown-menu/item-base\";\n\n// Long enough to skip the submenus a pointer crosses on its way somewhere else.\nconst SUB_OPEN_DELAY = 100;\n// How long a pointer heading for an open submenu may cross sibling rows.\nconst SUB_GRACE = 300;\n\ntype TriggerElementProps = React.HTMLAttributes<HTMLElement> & {\n  ref?: Ref<HTMLElement>;\n  \"data-state\"?: \"open\" | \"closed\";\n};\n\n/* -------------------------------------------------------------------------- */\n/* Root                                                                       */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuProps {\n  children: ReactNode;\n  /** Whether the menu is open, for controlled use. */\n  open?: boolean;\n  /** Whether the menu starts open when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new open state when the menu opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /**\n   * Play a soft sweep as the menu opens and closes, and a tick for checkbox\n   * and radio rows. Off by default; a `SoundProvider` can mute it app-wide.\n   */\n  sound?: boolean;\n}\n\nexport function DropdownMenu({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  sound = false,\n}: DropdownMenuProps) {\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const [focusTarget, setFocusTarget] = useState<FocusTarget>(\"first\");\n  const [instant, setInstant] = useState(false);\n  const [mounted, setMounted] = useState(false);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const menuId = useId();\n  const triggerId = useId();\n  const reduce = useReducedMotion() ?? false;\n  const playOpen = useSound(openSound, { enabled: sound });\n  const playClose = useSound(closeSound, { enabled: sound });\n  const playSelect = useSound(selectSound, { enabled: sound });\n\n  useEffect(() => setMounted(true), []);\n\n  const setOpen = useCallback(\n    (next: boolean, focus: FocusTarget = \"first\", now = false) => {\n      if (next !== open) {\n        if (next) playOpen();\n        else playClose();\n        setInstant(now);\n      }\n      if (next) setFocusTarget(focus);\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange, open, playOpen, playClose],\n  );\n\n  // Focus goes back to the trigger when the menu closes from inside it, or\n  // with nothing focused. A click elsewhere keeps the focus it landed on.\n  const wasOpen = useRef(open);\n  useEffect(() => {\n    if (wasOpen.current === open) return;\n    wasOpen.current = open;\n    if (open) return;\n    const active = document.activeElement;\n    if (\n      !active ||\n      active === document.body ||\n      active.closest(`[data-menu-root=\"${CSS.escape(menuId)}\"]`)\n    ) {\n      triggerRef.current?.focus({ preventScroll: true });\n    }\n  }, [open, menuId]);\n\n  const value = useMemo<RootContextValue>(\n    () => ({\n      open,\n      setOpen,\n      focusTarget,\n      instant,\n      menuId,\n      triggerId,\n      triggerRef,\n      reduce,\n      mounted,\n      playSelect,\n    }),\n    [open, setOpen, focusTarget, instant, menuId, triggerId, reduce, mounted, playSelect],\n  );\n\n  return <RootContext.Provider value={value}>{children}</RootContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Trigger                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuTriggerProps {\n  /** A single focusable element, usually a button. */\n  children: ReactElement<TriggerElementProps>;\n  /** Stops clicks and arrow keys from opening the menu. Default: false */\n  disabled?: boolean;\n}\n\nexport function DropdownMenuTrigger({ children, disabled = false }: DropdownMenuTriggerProps) {\n  const root = useRoot(\"DropdownMenuTrigger\");\n  if (!isValidElement(children)) {\n    throw new Error(\"<DropdownMenuTrigger> requires a single React element\");\n  }\n  const childProps = children.props;\n  const childRef = children.props.ref;\n\n  return cloneElement(children, {\n    ref: (node: HTMLElement | null) => {\n      root.triggerRef.current = node;\n      assignRef(childRef, node);\n    },\n    id: childProps.id ?? root.triggerId,\n    \"aria-haspopup\": \"menu\",\n    \"aria-expanded\": root.open,\n    \"aria-controls\": root.open ? root.menuId : undefined,\n    \"data-state\": root.open ? \"open\" : \"closed\",\n    onClick: (event: ReactMouseEvent<HTMLElement>) => {\n      childProps.onClick?.(event);\n      if (event.defaultPrevented || disabled) return;\n      // `detail` is 0 for a click the keyboard synthesized from Enter or Space:\n      // that opener wants the first row and no animation, a pointer wants no\n      // row picked yet and the menu to grow out of the trigger.\n      const keyboard = event.detail === 0;\n      root.setOpen(!root.open, keyboard ? \"first\" : \"panel\", keyboard);\n    },\n    onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => {\n      childProps.onKeyDown?.(event);\n      if (event.defaultPrevented || disabled) return;\n      if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n        event.preventDefault();\n        root.setOpen(true, event.key === \"ArrowDown\" ? \"first\" : \"last\", true);\n      }\n    },\n  });\n}\n\n/* -------------------------------------------------------------------------- */\n/* Content                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuContentProps {\n  children: ReactNode;\n  /** Classes merged onto the menu panel. */\n  className?: string;\n  /** Preferred side. Flips when the viewport has no room. Default \"bottom\". */\n  side?: \"top\" | \"bottom\";\n  /** Default \"start\". */\n  align?: Align;\n  /** Gap between trigger and menu in px. Default 6. */\n  sideOffset?: number;\n}\n\nexport function DropdownMenuContent({\n  children,\n  className,\n  side = \"bottom\",\n  align = \"start\",\n  sideOffset = 6,\n}: DropdownMenuContentProps) {\n  const root = useRoot(\"DropdownMenuContent\");\n  const panelRef = useRef<HTMLDivElement | null>(null);\n\n  const { setOpen, triggerRef, menuId } = root;\n  // Escape and Tab are keys, so the menu goes at once; a press outside lets it fold away.\n  const dismiss = useCallback(\n    (reason: DismissReason) => setOpen(false, \"first\", reason === \"escape\"),\n    [setOpen],\n  );\n  const closeFromKey = useCallback(() => setOpen(false, \"first\", true), [setOpen]);\n  const ignore = useCallback(\n    (target: Element) =>\n      Boolean(triggerRef.current?.contains(target)) ||\n      Boolean(target.closest(`[data-menu-root=\"${CSS.escape(menuId)}\"]`)),\n    [triggerRef, menuId],\n  );\n  useDismiss(root.open, dismiss, null, { ignore });\n\n  if (!root.mounted) return null;\n\n  return (\n    <AnimatePresence custom={root.instant}>\n      {root.open && (\n        <PresenceGate>\n          {({ isPresent, gate }) => (\n            <MenuPanel\n              id={root.menuId}\n              anchorRef={root.triggerRef}\n              panelRef={panelRef}\n              side={side}\n              align={align}\n              sideOffset={sideOffset}\n              focus={root.focusTarget}\n              instant={root.instant}\n              present={isPresent}\n              gate={gate}\n              labelledBy={root.triggerRef.current?.id ?? root.triggerId}\n              onClose={closeFromKey}\n              className={className}\n            >\n              {children}\n            </MenuPanel>\n          )}\n        </PresenceGate>\n      )}\n    </AnimatePresence>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Items                                                                      */\n/* -------------------------------------------------------------------------- */\n\nexport function DropdownMenuItem(props: DropdownMenuItemProps) {\n  return <ItemBase {...props} />;\n}\n\nexport interface DropdownMenuCheckboxItemProps extends Omit<DropdownMenuItemProps, \"onSelect\" | \"tone\" | \"inset\"> {\n  /** Whether the row is checked. */\n  checked: boolean;\n  /** Called with the new checked state when the row is toggled. */\n  onCheckedChange?: (checked: boolean) => void;\n}\n\n/** Stays open after a toggle by default, so the check can be seen landing. */\nexport function DropdownMenuCheckboxItem({\n  checked,\n  onCheckedChange,\n  closeOnSelect = false,\n  children,\n  ...props\n}: DropdownMenuCheckboxItemProps) {\n  const root = useRoot(\"DropdownMenuCheckboxItem\");\n  return (\n    <ItemBase\n      {...props}\n      role=\"menuitemcheckbox\"\n      checked={checked}\n      closeOnSelect={closeOnSelect}\n      onSelect={() => {\n        if (!closeOnSelect) root.playSelect();\n        onCheckedChange?.(!checked);\n      }}\n    >\n      {children}\n      {/* The mark sits at the end of the row, never before the label. */}\n      <span aria-hidden=\"true\" className=\"ml-auto flex size-4 shrink-0 items-center justify-center\">\n        <AnimatePresence initial={false}>\n          {checked ? (\n            <motion.span\n              key=\"check\"\n              initial={root.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n              animate={{ opacity: 1, scale: 1 }}\n              exit={root.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n              transition={root.reduce ? { duration: 0.1 } : SPRING_PANEL}\n              className=\"flex\"\n            >\n              <Check className=\"size-3.5 text-foreground\" strokeWidth={2.4} />\n            </motion.span>\n          ) : null}\n        </AnimatePresence>\n      </span>\n    </ItemBase>\n  );\n}\n\ninterface RadioGroupContextValue {\n  value: string;\n  onValueChange?: (value: string) => void;\n}\n\nconst RadioGroupContext = createContext<RadioGroupContextValue | null>(null);\n\nexport interface DropdownMenuRadioGroupProps {\n  /** The `value` of the checked radio row. */\n  value: string;\n  /** Called with the picked row's value when a radio row is selected. */\n  onValueChange?: (value: string) => void;\n  children: ReactNode;\n  /** Classes merged onto the group wrapper. */\n  className?: string;\n}\n\nexport function DropdownMenuRadioGroup({ value, onValueChange, children, className }: DropdownMenuRadioGroupProps) {\n  const context = useMemo(() => ({ value, onValueChange }), [value, onValueChange]);\n  return (\n    <RadioGroupContext.Provider value={context}>\n      <div className={className}>{children}</div>\n    </RadioGroupContext.Provider>\n  );\n}\n\nexport interface DropdownMenuRadioItemProps extends Omit<DropdownMenuItemProps, \"onSelect\" | \"tone\" | \"inset\"> {\n  /** The row's value. Checked when it matches the group's `value`. */\n  value: string;\n}\n\n/** Stays open after a pick by default, so the check can be seen moving. */\nexport function DropdownMenuRadioItem({ value, closeOnSelect = false, children, ...props }: DropdownMenuRadioItemProps) {\n  const root = useRoot(\"DropdownMenuRadioItem\");\n  const group = useContext(RadioGroupContext);\n  if (!group) throw new Error(\"DropdownMenuRadioItem must be used within <DropdownMenuRadioGroup>\");\n  const checked = group.value === value;\n  return (\n    <ItemBase\n      {...props}\n      role=\"menuitemradio\"\n      checked={checked}\n      closeOnSelect={closeOnSelect}\n      onSelect={() => {\n        // A pick that closes the menu sounds through the close sweep instead.\n        if (!closeOnSelect && !checked) root.playSelect();\n        group.onValueChange?.(value);\n      }}\n    >\n      {children}\n      {/* The mark sits at the end of the row, never before the label. */}\n      <span aria-hidden=\"true\" className=\"ml-auto flex size-4 shrink-0 items-center justify-center\">\n        <motion.span\n          initial={false}\n          animate={root.reduce ? { opacity: checked ? 1 : 0 } : { opacity: checked ? 1 : 0, scale: checked ? 1 : 0.6 }}\n          transition={root.reduce ? { duration: 0.1 } : SPRING_PANEL}\n          className=\"flex\"\n        >\n          <Check className=\"size-3.5 text-foreground\" strokeWidth={2.4} />\n        </motion.span>\n      </span>\n    </ItemBase>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Submenus                                                                   */\n/* -------------------------------------------------------------------------- */\n\ninterface SubContextValue {\n  id: string;\n  contentId: string;\n  open: boolean;\n  focus: FocusTarget;\n  triggerRef: MutableRefObject<HTMLElement | null>;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n  setOpen: (open: boolean, focus?: FocusTarget, instant?: boolean) => void;\n}\n\nconst SubContext = createContext<SubContextValue | null>(null);\n\nfunction useSub(component: string) {\n  const context = useContext(SubContext);\n  if (!context) throw new Error(`${component} must be used within <DropdownMenuSub>`);\n  return context;\n}\n\nexport interface DropdownMenuSubProps {\n  children: ReactNode;\n}\n\nexport function DropdownMenuSub({ children }: DropdownMenuSubProps) {\n  const level = useLevel(\"DropdownMenuSub\");\n  const id = useId();\n  const contentId = useId();\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const panelRef = useRef<HTMLDivElement | null>(null);\n  // Closes with its parent: an exiting menu takes its submenu out with it.\n  const open = level.openSub === id && level.present;\n  const { setOpenSub } = level;\n  const setOpen = useCallback(\n    (next: boolean, focus: FocusTarget = \"none\", instant?: boolean) =>\n      setOpenSub(next ? id : null, focus, instant),\n    [setOpenSub, id],\n  );\n  const value = useMemo(\n    () => ({ id, contentId, open, focus: level.subFocus, triggerRef, panelRef, setOpen }),\n    [id, contentId, open, level.subFocus, setOpen],\n  );\n  return <SubContext.Provider value={value}>{children}</SubContext.Provider>;\n}\n\nexport interface DropdownMenuSubTriggerProps {\n  children: ReactNode;\n  /** Stops hover, click and keys from opening the submenu. */\n  disabled?: boolean;\n  /** Indent to line up with rows that start with an icon. */\n  inset?: boolean;\n  /** Text matched by typeahead when the label is not plain text. */\n  textValue?: string;\n  /** Classes merged onto the trigger row. */\n  className?: string;\n}\n\nexport function DropdownMenuSubTrigger({ children, disabled, inset, textValue, className }: DropdownMenuSubTriggerProps) {\n  const level = useLevel(\"DropdownMenuSubTrigger\");\n  const sub = useSub(\"DropdownMenuSubTrigger\");\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  const clearTimer = useCallback(() => {\n    if (timer.current) clearTimeout(timer.current);\n    timer.current = null;\n  }, []);\n  useEffect(() => clearTimer, [clearTimer]);\n\n  return (\n    <ItemBase\n      disabled={disabled}\n      inset={inset}\n      textValue={textValue}\n      className={className}\n      subTrigger={{\n        id: sub.id,\n        open: sub.open,\n        controls: sub.contentId,\n        ref: sub.triggerRef,\n        onPointerMove: (event) => {\n          if (document.activeElement !== event.currentTarget) {\n            event.currentTarget.focus({ preventScroll: true });\n          }\n          if (disabled || sub.open || timer.current) return;\n          // Another row's submenu closes as soon as the pointer settles here.\n          if (level.openSub) level.setOpenSub(null);\n          timer.current = setTimeout(() => {\n            timer.current = null;\n            sub.setOpen(true, \"none\");\n          }, SUB_OPEN_DELAY);\n        },\n        onPointerLeave: (event) => {\n          clearTimer();\n          const panel = sub.panelRef.current;\n          if (!sub.open || !panel || event.pointerType === \"touch\") return;\n          // Leave a corridor from the pointer to the submenu's near edge, so a\n          // diagonal path across the rows below does not close it.\n          const rect = panel.getBoundingClientRect();\n          const right = rect.left >= event.clientX;\n          const edge = right ? rect.left : rect.right;\n          const back = right ? -5 : 5;\n          level.grace.current = {\n            polygon: [\n              { x: event.clientX + back, y: event.clientY },\n              { x: edge, y: rect.top },\n              { x: edge, y: rect.bottom },\n            ],\n            until: Date.now() + SUB_GRACE,\n          };\n        },\n        onKeyDown: (event) => {\n          if (disabled) return;\n          if (event.key === \"ArrowRight\" || event.key === \"Enter\" || event.key === \" \") {\n            event.preventDefault();\n            event.stopPropagation();\n            sub.setOpen(true, \"first\");\n            // Already open from a hover: the panel's focus effect will not run\n            // again, so hand focus in here.\n            if (sub.open) enabledItems(sub.panelRef.current)[0]?.focus();\n          }\n        },\n        // Keys open the submenu in onKeyDown, so a click here is a pointer or a tap.\n        onClick: () => {\n          if (!disabled) sub.setOpen(true, \"first\", false);\n        },\n      }}\n    >\n      {children}\n      <ChevronRight aria-hidden=\"true\" className=\"ml-auto size-4\" />\n    </ItemBase>\n  );\n}\n\nexport interface DropdownMenuSubContentProps {\n  children: ReactNode;\n  /** Classes merged onto the submenu panel. */\n  className?: string;\n  /** Gap between the menu's edge and the submenu in px. Default 6. */\n  sideOffset?: number;\n}\n\nexport function DropdownMenuSubContent({ children, className, sideOffset = 6 }: DropdownMenuSubContentProps) {\n  const root = useRoot(\"DropdownMenuSubContent\");\n  const level = useLevel(\"DropdownMenuSubContent\");\n  const sub = useSub(\"DropdownMenuSubContent\");\n\n  return (\n    <AnimatePresence custom={level.subInstant}>\n      {sub.open && (\n        <PresenceGate>\n          {({ isPresent, gate }) => (\n            <MenuPanel\n              id={sub.contentId}\n              anchorRef={sub.triggerRef}\n              panelRef={sub.panelRef}\n              side=\"right\"\n              align=\"start\"\n              sideOffset={sideOffset}\n              focus={sub.focus}\n              instant={level.subInstant}\n              present={isPresent}\n              gate={gate}\n              labelledBy={sub.id}\n              onClose={() => root.setOpen(false, \"first\", true)}\n              onPointerEnter={() => {\n                level.grace.current = null;\n              }}\n              onKeyDown={(event) => {\n                if (event.key !== \"ArrowLeft\") return false;\n                event.preventDefault();\n                sub.setOpen(false, \"none\", true);\n                sub.triggerRef.current?.focus({ preventScroll: true });\n                return true;\n              }}\n              className={className}\n            >\n              {children}\n            </MenuPanel>\n          )}\n        </PresenceGate>\n      )}\n    </AnimatePresence>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Decoration                                                                 */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuLabelProps {\n  children: ReactNode;\n  /** Indent to line up with rows that start with an icon. */\n  inset?: boolean;\n  /** Classes merged onto the label element. */\n  className?: string;\n}\n\nexport function DropdownMenuLabel({ children, inset, className }: DropdownMenuLabelProps) {\n  return (\n    <div className={cn(\"px-3 py-1.5 text-xs font-medium text-muted-foreground\", inset && \"pl-9\", className)}>\n      {children}\n    </div>\n  );\n}\n\nexport interface DropdownMenuSeparatorProps {\n  /** Classes merged onto the separator line. */\n  className?: string;\n}\n\nexport function DropdownMenuSeparator({ className }: DropdownMenuSeparatorProps) {\n  return <hr className={cn(\"-mx-2 my-1 h-px border-0 bg-border\", className)} />;\n}\n\nexport interface DropdownMenuShortcutProps {\n  children: ReactNode;\n  /** Classes merged onto the shortcut text. */\n  className?: string;\n}\n\nexport function DropdownMenuShortcut({ children, className }: DropdownMenuShortcutProps) {\n  return (\n    <span aria-hidden=\"true\" className={cn(\"ml-auto pl-4 text-xs tracking-wide text-muted-foreground\", className)}>\n      {children}\n    </span>\n  );\n}\n"},{"path":"components/motion/menu/menu-item-highlight.tsx","type":"util","content":"\"use client\";\n\nimport { motion } from \"motion/react\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\n/** The row shape every menu item shares. Menus add their own gap and states. */\nexport const MENU_ITEM_CLASS =\n  \"relative isolate flex w-full select-none items-center rounded-lg px-3 py-1.5 text-left text-sm outline-none\";\n\nexport interface MenuItemHighlightProps {\n  /** Shared by every row of one panel, so the highlight glides between them. */\n  layoutId: string;\n  tone?: \"default\" | \"destructive\";\n  reduce: boolean;\n  /**\n   * Jump instead of gliding: the highlight was moved by the keyboard, where a\n   * spring only trails behind fast arrowing.\n   */\n  instant?: boolean;\n}\n\n/** The highlight behind the active row. Render it only inside the active row. */\nexport function MenuItemHighlight({\n  layoutId,\n  tone = \"default\",\n  reduce,\n  instant = false,\n}: MenuItemHighlightProps) {\n  return (\n    <motion.span\n      aria-hidden=\"true\"\n      layoutId={layoutId}\n      className={cn(\n        \"absolute inset-0 -z-10 rounded-lg\",\n        tone === \"destructive\" ? \"bg-destructive/10\" : \"bg-foreground/[0.07]\",\n      )}\n      transition={reduce || instant ? { duration: 0 } : SPRING_LAYOUT}\n    />\n  );\n}\n"},{"path":"lib/hooks/use-row-cursor.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\n\n/**\n * Where the keyboard or the pointer last moved to: the row's id, stamped with\n * the query it was placed under.\n */\ntype RowCursor = { id: string; query: string };\n\n/** The cursor's row, or -1 once the query has moved on or the row has left. */\nfunction indexOfCursor(\n  rows: readonly { id: string }[],\n  query: string,\n  cursor: RowCursor | null,\n) {\n  if (cursor === null || cursor.query !== query) return -1;\n  return rows.findIndex((row) => row.id === cursor.id);\n}\n\n/**\n * The highlighted row of a list whose rows can change under it.\n *\n * Which row is highlighted is resolved during render, never in a passive\n * effect: a passive effect runs after the commit, so a list that had just\n * changed would carry an `aria-activedescendant` naming a row that has left it,\n * and a key pressed in that window would commit the wrong row or nothing at\n * all.\n *\n * The cursor holds the row's id, not its position. A position alone cannot tell\n * a list that shrank from one that swapped its rows for a different set of the\n * same length, and the second case is the one that silently hands Enter to a\n * row the user never chose. A cursor whose row has left the list returns the\n * highlight to the first row rather than to the nearest surviving one: the row\n * the user aimed at is gone, and the first row is where a new query already\n * puts the highlight.\n *\n * Pass the query the list is filtered by. The cursor is stamped with it and\n * dropped when it changes, so a caller cannot forget to clear it - including a\n * caller whose query arrives as a prop and so never runs its own handler. Rows\n * that come back under a query that has moved on cannot revive it either.\n * `moveTo(null)` is for deliberate resets, such as reopening the list.\n *\n * Both callbacks keep one identity for the life of the component, and read the\n * rows and the query through a ref to do it. A caller will put them in an\n * effect's dependencies - the exhaustive-deps rule makes it - and a `moveTo`\n * rebuilt on every keystroke would re-run that effect on every keystroke.\n */\nexport function useRowCursor(rows: readonly { id: string }[], query: string) {\n  const [cursor, setCursor] = useState<RowCursor | null>(null);\n  // Written after commit, not during render: a render React discards or has not\n  // finished still runs the component body, and an event handler that read this\n  // in that window would stamp the cursor with a query the committed tree does\n  // not have.\n  const latest = useRef({ rows, query });\n  useLayoutEffect(() => {\n    latest.current = { rows, query };\n  });\n\n  const cursorRow = indexOfCursor(rows, query, cursor);\n  // Cleared rather than ignored: React re-runs this render with the cursor\n  // already gone, so rows that come back cannot revive a highlight the user has\n  // stopped aiming at.\n  if (cursor !== null && cursorRow < 0) setCursor(null);\n\n  const moveTo = useCallback(\n    (id: string | null) =>\n      setCursor(id === null ? null : { id, query: latest.current.query }),\n    [],\n  );\n\n  const moveActive = useCallback((direction: 1 | -1) => {\n    const { rows: live, query: liveQuery } = latest.current;\n    const last = live.length - 1;\n    if (last < 0) return;\n    // Steps from the row the cursor is really on, inside the update, so that\n    // two keys landing in one batch move two rows rather than one.\n    setCursor((current) => {\n      const at = Math.max(indexOfCursor(live, liveQuery, current), 0);\n      const next = Math.min(Math.max(at + direction, 0), last);\n      return { id: live[next].id, query: liveQuery };\n    });\n  }, []);\n\n  return { activeIndex: cursorRow < 0 ? 0 : cursorRow, moveTo, moveActive };\n}\n"},{"path":"components/agents/citations.tsx","type":"util","content":"\"use client\";\n\nimport { BookOpenText, ChevronDown, ExternalLink, Globe2 } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { AgentDisclosure } from \"@/components/agents/agent-disclosure\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useFavicon } from \"@/lib/hooks/use-favicon\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport const citationsMessages = {\n  title: \"Sources\",\n  viewCitation: \"View citation {index}\",\n};\n\nexport type CitationsMessages = typeof citationsMessages;\n\nexport interface CitationItem {\n  /** Unique key for the source, matched by a `Citation` marker's `citationId`. */\n  id: string;\n  /** Source name shown as the row's main text. */\n  title: ReactNode;\n  /** Muted text after the title, such as the site's host. */\n  domain?: ReactNode;\n  /** Link opened in a new tab and the favicon source. Omit for a plain row. */\n  url?: string;\n  /**\n   * Replaces the URL favicon, e.g. a document icon for non-web sources. An svg\n   * child is sized to match the favicon; falsy values fall back to the favicon.\n   */\n  icon?: ReactNode;\n}\n\nexport interface CitationsProps {\n  /** Sources listed in order, numbered from 1. */\n  citations: CitationItem[];\n  /** Text of the toggle button. Default: \"Sources\" */\n  title?: ReactNode;\n  /** Whether the list is expanded, for controlled use. */\n  open?: boolean;\n  /** Whether the list starts expanded when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new state when the list expands or collapses. */\n  onOpenChange?: (open: boolean) => void;\n  /** Prefix for row ids that `Citation` markers link to. Generated when omitted. */\n  idPrefix?: string;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Override any built-in string. */\n  labels?: Partial<CitationsMessages>;\n}\n\nexport interface CitationProps {\n  /** Id of the `CitationItem` this marker links to. */\n  citationId: string;\n  /** Number shown on the marker. */\n  index: number;\n  /** Must match the related Citations idPrefix. */\n  idPrefix: string;\n  /**\n   * Accessible name for the marker. Defaults to `View citation {index}`. Include\n   * the index so voice control users can say the number they see.\n   */\n  label?: string;\n  /** Classes merged onto the marker link. */\n  className?: string;\n}\n\nexport interface CitationListProps {\n  /** Sources listed in order, numbered from 1. */\n  citations: CitationItem[];\n  /** Prefix for row ids that `Citation` markers link to. Generated when omitted. */\n  idPrefix?: string;\n  /** The citation a marker just led to; its row is lit. */\n  highlightedId?: string;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nexport interface CitationStackProps {\n  /** Sources whose favicons are stacked. */\n  citations: CitationItem[];\n  /** Most favicons to show. Default: 3 */\n  limit?: number;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nfunction citationTargetId(prefix: string, citationId: string) {\n  return `${prefix}-${citationId.replace(/[^a-zA-Z0-9_-]/g, \"-\")}`;\n}\n\nexport function Citation({\n  citationId,\n  index,\n  idPrefix,\n  label,\n  className,\n}: CitationProps) {\n  const t = useMessages(\"citations\", citationsMessages);\n  return (\n    <a\n      href={`#${citationTargetId(idPrefix, citationId)}`}\n      aria-label={label ?? t(\"viewCitation\", { index })}\n      className={cn(\n        // A foreground tint, not bg-muted: muted is the bubble colour, so a\n        // muted marker would vanish inside a soft bubble.\n        \"mx-0.5 inline-flex min-w-4 -translate-y-0.5 items-center justify-center rounded-full bg-foreground/[0.07] px-1 py-0.5 text-[11px] font-medium leading-none text-muted-foreground no-underline outline-none transition-colors hover:bg-foreground/[0.12] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n        className,\n      )}\n    >\n      {index}\n    </a>\n  );\n}\n\nexport function CitationFavicon({\n  url,\n  icon,\n  className,\n}: {\n  /** Page whose site favicon is shown. A globe icon shows when absent or broken. */\n  url?: string;\n  /** Drawn instead of the favicon when truthy. */\n  icon?: ReactNode;\n  className?: string;\n}) {\n  const favicon = useFavicon(icon ? undefined : url);\n\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={cn(\n        \"grid size-5 shrink-0 place-items-center text-muted-foreground [&>svg]:size-3.5\",\n        className,\n      )}\n    >\n      {icon ? (\n        icon\n      ) : favicon.src ? (\n        <img\n          ref={favicon.ref}\n          src={favicon.src}\n          alt=\"\"\n          width={16}\n          height={16}\n          referrerPolicy=\"no-referrer\"\n          className=\"size-4 rounded-sm object-contain\"\n        />\n      ) : (\n        <Globe2 className=\"size-3.5\" />\n      )}\n    </span>\n  );\n}\n\nexport function CitationStack({\n  citations,\n  limit = 3,\n  className,\n}: CitationStackProps) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={cn(\"flex -space-x-1.5\", className)}\n    >\n      {citations.slice(0, limit).map((citation) => (\n        <CitationFavicon\n          key={citation.id}\n          url={citation.url}\n          icon={citation.icon}\n          className=\"size-6 rounded-full bg-background ring-2 ring-background\"\n        />\n      ))}\n    </span>\n  );\n}\n\nfunction CitationRow({\n  citation,\n  index,\n  idPrefix,\n  highlighted,\n}: {\n  citation: CitationItem;\n  index: number;\n  idPrefix: string;\n  highlighted: boolean;\n}) {\n  const content = (\n    <>\n      <CitationFavicon url={citation.url} icon={citation.icon} />\n      <span className=\"flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5\">\n        <span className=\"truncate text-sm font-medium text-foreground/80 transition-colors group-hover/citation:text-foreground\">\n          {citation.title}\n        </span>\n        {citation.domain ? (\n          <span className=\"min-w-0 truncate text-xs text-muted-foreground/60\">\n            {citation.domain}\n          </span>\n        ) : null}\n      </span>\n      <span className=\"flex shrink-0 items-center gap-1.5\">\n        <span className=\"grid size-5 place-items-center rounded-full bg-foreground/[0.05] text-[11px] font-medium tabular-nums text-muted-foreground\">\n          {index}\n        </span>\n        {citation.url ? (\n          <ExternalLink className=\"size-3.5 text-muted-foreground/40 transition-colors group-hover/citation:text-muted-foreground\" />\n        ) : null}\n      </span>\n    </>\n  );\n  // The row a marker just led to is lit, so the reader sees which source they\n  // landed on: `highlighted` from Citations, or `:target` after a plain jump.\n  const className = cn(\n    \"group/citation flex scroll-my-3 items-center gap-2 rounded-lg px-1.5 py-1 outline-none transition-colors duration-200 hover:bg-foreground/[0.04] focus-visible:ring-2 focus-visible:ring-ring target:bg-foreground/[0.07]\",\n    highlighted && \"bg-foreground/[0.07] hover:bg-foreground/[0.07]\",\n  );\n  const id = citationTargetId(idPrefix, citation.id);\n\n  return citation.url ? (\n    <a\n      id={id}\n      href={citation.url}\n      target=\"_blank\"\n      rel=\"noreferrer noopener\"\n      className={className}\n    >\n      {content}\n    </a>\n  ) : (\n    <div id={id} className={className}>\n      {content}\n    </div>\n  );\n}\n\nexport function CitationList({\n  citations,\n  idPrefix,\n  highlightedId,\n  className,\n}: CitationListProps) {\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const resolvedPrefix =\n    idPrefix ?? `citation-list-${baseId.replace(/:/g, \"\")}`;\n\n  return (\n    <div className={cn(\"grid gap-0.5\", className)}>\n      <AnimatePresence mode=\"popLayout\">\n        {citations.map((citation, index) => (\n          <motion.div\n            layout=\"position\"\n            key={citation.id}\n            initial={reduce ? { opacity: 1 } : { opacity: 0, y: 6 }}\n            animate={{ opacity: 1, y: 0 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3 }}\n            transition={\n              reduce\n                ? { duration: 0 }\n                : {\n                    opacity: { duration: 0.18, ease: EASE_OUT },\n                    y: SPRING_LAYOUT,\n                    layout: SPRING_LAYOUT,\n                  }\n            }\n          >\n            <CitationRow\n              citation={citation}\n              index={index + 1}\n              idPrefix={resolvedPrefix}\n              highlighted={citation.id === highlightedId}\n            />\n          </motion.div>\n        ))}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nexport function Citations({\n  citations,\n  title,\n  open,\n  defaultOpen = false,\n  onOpenChange,\n  idPrefix,\n  className,\n  labels,\n}: CitationsProps) {\n  const t = useMessages(\"citations\", citationsMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const contentId = `${baseId}-content`;\n  const resolvedPrefix =\n    idPrefix ?? `citation-${baseId.replace(/:/g, \"\")}`;\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const currentOpen = open ?? internalOpen;\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (open === undefined) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [onOpenChange, open],\n  );\n\n  // A marker links to its source row. While the list is folded that row is\n  // hidden, so the jump would land on nothing: open the list, then bring the\n  // row into view once it is shown.\n  const [highlightedId, setHighlightedId] = useState<string>();\n  const latest = useRef({ currentOpen, setOpen, citations, reduce });\n  useLayoutEffect(() => {\n    latest.current = { currentOpen, setOpen, citations, reduce };\n  });\n  useEffect(() => {\n    // Returns true when the hash names one of this list's sources.\n    const reveal = (hash: string) => {\n      const now = latest.current;\n      const citation = now.citations.find(\n        (item) => citationTargetId(resolvedPrefix, item.id) === hash,\n      );\n      if (!citation) return false;\n      if (!now.currentOpen) now.setOpen(true);\n      setHighlightedId(citation.id);\n      // After the list has opened, bring the row just into view: no jump to\n      // the top of the page, where a sticky header would cover it.\n      window.setTimeout(() => {\n        document.getElementById(hash)?.scrollIntoView({\n          block: \"nearest\",\n          behavior: now.reduce ? \"auto\" : \"smooth\",\n        });\n      }, 0);\n      return true;\n    };\n    const onHash = () => reveal(decodeURIComponent(window.location.hash.slice(1)));\n    // Marker clicks are handled here rather than as a plain jump, which\n    // lands on nothing while the list is folded and pins the row under the\n    // page header when it is open.\n    const onClick = (event: MouseEvent) => {\n      const link = (event.target as Element | null)?.closest?.(\"a[href^='#']\");\n      if (!link) return;\n      if (reveal(decodeURIComponent(link.getAttribute(\"href\")?.slice(1) ?? \"\"))) {\n        event.preventDefault();\n      }\n    };\n    window.addEventListener(\"hashchange\", onHash);\n    document.addEventListener(\"click\", onClick);\n    return () => {\n      window.removeEventListener(\"hashchange\", onHash);\n      document.removeEventListener(\"click\", onClick);\n    };\n  }, [resolvedPrefix]);\n\n  return (\n    <div className={cn(\"w-full text-sm\", className)}>\n      <button\n        type=\"button\"\n        aria-expanded={currentOpen}\n        aria-controls={contentId}\n        onClick={() => setOpen(!currentOpen)}\n        className=\"group -ml-1 flex min-h-8 items-center gap-2 rounded-full px-1 text-left text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n      >\n        <BookOpenText className=\"size-4\" />\n        <span className=\"font-medium\">{title ?? t(\"title\")}</span>\n        <span className=\"rounded-full bg-foreground/[0.06] px-1.5 py-0.5 text-[11px] font-medium tabular-nums\">\n          {citations.length}\n        </span>\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: currentOpen ? 180 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n          className=\"text-muted-foreground/60\"\n        >\n          <ChevronDown className=\"size-3.5\" />\n        </motion.span>\n      </button>\n\n      <AgentDisclosure\n        id={contentId}\n        open={currentOpen}\n      >\n        <CitationList\n          citations={citations}\n          idPrefix={resolvedPrefix}\n          highlightedId={highlightedId}\n          className=\"mt-1\"\n        />\n      </AgentDisclosure>\n    </div>\n  );\n}\n"},{"path":"components/motion/animated-sidebar/context.ts","type":"util","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport type { useMessages } from \"@/lib/i18n\";\n\nexport type SidebarState = \"expanded\" | \"collapsed\";\nexport type SidebarSide = \"left\" | \"right\";\nexport type SidebarVariant = \"sidebar\" | \"floating\" | \"inset\";\nexport type SidebarCollapsible = \"offcanvas\" | \"icon\" | \"none\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const animatedSidebarMessages = {\n  label: \"Sidebar\",\n  toggle: \"Toggle sidebar\",\n  close: \"Close sidebar\",\n};\n\nexport type AnimatedSidebarMessages = typeof animatedSidebarMessages;\n\ninterface AnimatedSidebarContextValue {\n  isMobile: boolean;\n  layoutId: string;\n  open: boolean;\n  openMobile: boolean;\n  reduce: boolean;\n  setOpen: (open: boolean) => void;\n  setOpenMobile: (open: boolean) => void;\n  state: SidebarState;\n  toggleSidebar: () => void;\n  triggerRef: React.RefObject<HTMLButtonElement | null>;\n  t: ReturnType<typeof useMessages<AnimatedSidebarMessages>>;\n}\n\nexport const AnimatedSidebarContext =\n  createContext<AnimatedSidebarContextValue | null>(null);\n\ninterface AnimatedSidebarPanelContextValue {\n  collapsed: boolean;\n  collapsible: SidebarCollapsible;\n  side: SidebarSide;\n}\n\nexport const AnimatedSidebarPanelContext =\n  createContext<AnimatedSidebarPanelContextValue | null>(null);\n\nexport function useAnimatedSidebar() {\n  const context = useContext(AnimatedSidebarContext);\n  if (!context) {\n    throw new Error(\n      \"useAnimatedSidebar must be used inside AnimatedSidebarProvider.\",\n    );\n  }\n  return context;\n}\n\nexport function useAnimatedSidebarPanel() {\n  const context = useContext(AnimatedSidebarPanelContext);\n  if (!context) {\n    throw new Error(\n      \"Animated Sidebar parts must be used inside AnimatedSidebar.\",\n    );\n  }\n  return context;\n}\n"},{"path":"components/motion/animated-sidebar/menu-button.tsx","type":"util","content":"\"use client\";\n\nimport { ChevronRight } from \"lucide-react\";\nimport { motion } from \"motion/react\";\nimport type { ReactNode } from \"react\";\nimport { SPRING_LAYOUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { useAnimatedSidebar, useAnimatedSidebarPanel } from \"./context\";\nimport {\n  LABEL_ENTER_TRANSITION,\n  LABEL_EXIT_TRANSITION,\n  REDUCED_TRANSITION,\n} from \"./motion\";\n\nexport interface AnimatedSidebarMenuButtonProps {\n  children: ReactNode;\n  /** Icon shown before the label; stays visible in the collapsed rail. */\n  icon?: ReactNode;\n  /** Trailing content such as a count, hidden while collapsed. */\n  badge?: ReactNode;\n  /** Renders a link to this URL instead of a button. */\n  href?: string;\n  /** Marks the current page and moves the shared highlight here. Default: false */\n  isActive?: boolean;\n  /** Expanded state of a submenu this button toggles; also shows a chevron. */\n  ariaExpanded?: boolean;\n  /** Disables the item. Default: false */\n  disabled?: boolean;\n  /** Close the mobile drawer on select. Defaults to true unless `ariaExpanded` is set. */\n  closeOnSelect?: boolean;\n  /** Link target, used with `href`. */\n  target?: \"_blank\" | \"_self\" | \"_parent\" | \"_top\";\n  /** Link rel, used with `href`. Defaults to \"noreferrer noopener\" for `_blank`. */\n  rel?: string;\n  /** Called when the item is clicked. */\n  onSelect?: () => void;\n  /** Classes merged onto the button or link element. */\n  className?: string;\n}\n\nexport function AnimatedSidebarMenuButton({\n  children,\n  icon,\n  badge,\n  href,\n  isActive = false,\n  ariaExpanded,\n  disabled = false,\n  closeOnSelect,\n  target,\n  rel,\n  onSelect,\n  className,\n}: AnimatedSidebarMenuButtonProps) {\n  const context = useAnimatedSidebar();\n  const panel = useAnimatedSidebarPanel();\n  const textLabel = typeof children === \"string\" ? children : undefined;\n\n  const select = (\n    event: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement>,\n  ) => {\n    if (disabled) {\n      event.preventDefault();\n      return;\n    }\n    onSelect?.();\n    const shouldCloseOnSelect =\n      closeOnSelect ?? ariaExpanded === undefined;\n    if (context.isMobile && shouldCloseOnSelect) {\n      context.setOpenMobile(false);\n    }\n    // A submenu cannot render in the icon rail, so opening one from there\n    // leaves its children unreachable - a pointer can still fall back to the\n    // rail or the shortcut, a finger has nothing. Selecting a group unfolds\n    // the panel that is about to hold it.\n    if (ariaExpanded !== undefined && panel.collapsed && !context.isMobile) {\n      context.setOpen(true);\n    }\n  };\n\n  const content = (\n    <>\n      {isActive ? (\n        <motion.span\n          layoutId={context.layoutId}\n          transition={context.reduce ? { duration: 0 } : SPRING_LAYOUT}\n          className=\"absolute inset-0 rounded-full bg-muted\"\n        />\n      ) : null}\n      {icon ? (\n        <span\n          aria-hidden=\"true\"\n          className=\"relative z-10 grid size-5 shrink-0 place-items-center\"\n        >\n          {icon}\n        </span>\n      ) : null}\n      <motion.span\n        initial={false}\n        animate={{\n          opacity: panel.collapsed ? 0 : 1,\n          x: panel.collapsed ? -4 : 0,\n        }}\n        transition={\n          context.reduce\n            ? REDUCED_TRANSITION\n            : panel.collapsed\n              ? LABEL_EXIT_TRANSITION\n              : LABEL_ENTER_TRANSITION\n        }\n        aria-hidden={panel.collapsed}\n        className={cn(\n          \"relative z-10 min-w-0 flex-1 truncate\",\n          panel.collapsed && \"pointer-events-none\",\n        )}\n      >\n        {children}\n      </motion.span>\n      {badge && !panel.collapsed ? (\n        <span className=\"relative z-10 shrink-0 text-xs text-muted-foreground\">\n          {badge}\n        </span>\n      ) : null}\n      {ariaExpanded !== undefined ? (\n        <motion.span\n          aria-hidden=\"true\"\n          initial={false}\n          animate={{\n            opacity: panel.collapsed ? 0 : 1,\n            rotate: ariaExpanded ? 90 : 0,\n            x: panel.collapsed ? 4 : 0,\n          }}\n          transition={context.reduce ? { duration: 0 } : SPRING_LAYOUT}\n          className=\"relative z-10 grid size-4 shrink-0 place-items-center text-muted-foreground\"\n        >\n          <ChevronRight className=\"size-3.5\" />\n        </motion.span>\n      ) : null}\n    </>\n  );\n\n  const interactiveClassName = cn(\n    \"relative flex min-h-9 w-full min-w-0 items-center gap-2.5 overflow-hidden rounded-full px-3 text-left text-sm font-medium outline-none\",\n    \"text-muted-foreground transition-colors hover:text-foreground\",\n    \"focus-visible:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring\",\n    isActive && \"text-foreground\",\n    disabled && \"cursor-not-allowed opacity-40\",\n    className,\n  );\n\n  return href ? (\n    <motion.a\n      href={href}\n      target={target}\n      rel={\n        rel ??\n        (target === \"_blank\" ? \"noreferrer noopener\" : undefined)\n      }\n      aria-current={isActive ? \"page\" : undefined}\n      aria-expanded={ariaExpanded}\n      aria-disabled={disabled || undefined}\n      aria-label={panel.collapsed ? textLabel : undefined}\n      title={panel.collapsed ? textLabel : undefined}\n      tabIndex={disabled ? -1 : undefined}\n      onClick={select}\n      whileTap={context.reduce || disabled ? undefined : { scale: 0.98 }}\n      transition={SPRING_PRESS}\n      className={interactiveClassName}\n    >\n      {content}\n    </motion.a>\n  ) : (\n    <motion.button\n      type=\"button\"\n      disabled={disabled}\n      aria-current={isActive ? \"page\" : undefined}\n      aria-expanded={ariaExpanded}\n      aria-label={panel.collapsed ? textLabel : undefined}\n      title={panel.collapsed ? textLabel : undefined}\n      onClick={select}\n      whileTap={context.reduce || disabled ? undefined : { scale: 0.98 }}\n      transition={SPRING_PRESS}\n      className={interactiveClassName}\n    >\n      {content}\n    </motion.button>\n  );\n}\n"},{"path":"components/motion/animated-sidebar/menu-sub-button.tsx","type":"util","content":"\"use client\";\n\nimport { motion } from \"motion/react\";\nimport type { ReactNode } from \"react\";\nimport { SPRING_PRESS } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { useAnimatedSidebar } from \"./context\";\n\nexport interface AnimatedSidebarMenuSubButtonProps {\n  children: ReactNode;\n  /** Leading icon. Defaults to a small dot. */\n  icon?: ReactNode;\n  /** Renders a link to this URL instead of a button. */\n  href?: string;\n  /** Marks the row as the current page. Default: false */\n  isActive?: boolean;\n  /** Dims the row and blocks selection. Default: false */\n  disabled?: boolean;\n  /** Closes the mobile sidebar after selecting. Default: true */\n  closeOnSelect?: boolean;\n  /** Link target, used with `href`. */\n  target?: \"_blank\" | \"_self\" | \"_parent\" | \"_top\";\n  /** Link rel, used with `href`. Defaults to \"noreferrer noopener\" for \"_blank\". */\n  rel?: string;\n  /** Called when the row is clicked and not disabled. */\n  onSelect?: () => void;\n  /** Classes merged onto the button or link. */\n  className?: string;\n}\n\nexport function AnimatedSidebarMenuSubButton({\n  children,\n  icon,\n  href,\n  isActive = false,\n  disabled = false,\n  closeOnSelect = true,\n  target,\n  rel,\n  onSelect,\n  className,\n}: AnimatedSidebarMenuSubButtonProps) {\n  const context = useAnimatedSidebar();\n\n  const select = (\n    event: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement>,\n  ) => {\n    if (disabled) {\n      event.preventDefault();\n      return;\n    }\n    onSelect?.();\n    if (context.isMobile && closeOnSelect) context.setOpenMobile(false);\n  };\n\n  const content = (\n    <>\n      <span\n        aria-hidden=\"true\"\n        className=\"grid size-4 shrink-0 place-items-center\"\n      >\n        {icon ?? <span className=\"size-1 rounded-full bg-current\" />}\n      </span>\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n    </>\n  );\n\n  const interactiveClassName = cn(\n    \"flex min-h-8 w-full min-w-0 items-center gap-2 rounded-full px-3 text-left text-xs outline-none\",\n    \"text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground\",\n    \"focus-visible:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring\",\n    isActive && \"bg-muted/70 text-foreground\",\n    disabled && \"cursor-not-allowed opacity-40\",\n    className,\n  );\n\n  return href ? (\n    <motion.a\n      href={href}\n      target={target}\n      rel={\n        rel ??\n        (target === \"_blank\" ? \"noreferrer noopener\" : undefined)\n      }\n      aria-current={isActive ? \"page\" : undefined}\n      aria-disabled={disabled || undefined}\n      tabIndex={disabled ? -1 : undefined}\n      onClick={select}\n      whileTap={context.reduce || disabled ? undefined : { scale: 0.98 }}\n      transition={SPRING_PRESS}\n      className={interactiveClassName}\n    >\n      {content}\n    </motion.a>\n  ) : (\n    <motion.button\n      type=\"button\"\n      disabled={disabled}\n      aria-current={isActive ? \"page\" : undefined}\n      onClick={select}\n      whileTap={context.reduce || disabled ? undefined : { scale: 0.98 }}\n      transition={SPRING_PRESS}\n      className={interactiveClassName}\n    >\n      {content}\n    </motion.button>\n  );\n}\n"},{"path":"components/motion/animated-sidebar/mobile-sidebar.tsx","type":"util","content":"\"use client\";\n\nimport { motion } from \"motion/react\";\nimport {\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { useFocusTrap } from \"@/lib/hooks/use-focus-trap\";\nimport { useScrollLock } from \"@/lib/scroll-lock\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  AnimatedSidebarPanelContext,\n  type SidebarSide,\n  useAnimatedSidebar,\n} from \"./context\";\nimport { PANEL_TRANSITION, REDUCED_TRANSITION } from \"./motion\";\n\nexport function MobileSidebar({\n  ariaLabel,\n  children,\n  className,\n  side,\n}: {\n  ariaLabel: string;\n  children: ReactNode;\n  className?: string;\n  side: SidebarSide;\n}) {\n  const context = useAnimatedSidebar();\n  const panelRef = useRef<HTMLDivElement>(null);\n  const [mounted, setMounted] = useState(false);\n  // The sheet is mounted for as long as the viewport is mobile, so it hides\n  // itself while closed rather than sitting there transparent and interactive.\n  // Opening shows it in the same commit that starts the slide - a delayed show\n  // would run the focus effect below against a still-hidden panel, and focus()\n  // on a hidden element is ignored. Closing waits for the slide to finish, and\n  // the panel's own exit tells us when that is: no duration to keep in sync.\n  const [hidden, setHidden] = useState(!context.openMobile);\n  // The completion callback fires for the open slide too, and it reads state\n  // from whenever motion settles: a ref keeps it on the current one.\n  const openMobileRef = useRef(context.openMobile);\n\n  useEffect(() => setMounted(true), []);\n\n  useEffect(() => {\n    openMobileRef.current = context.openMobile;\n    if (context.openMobile) setHidden(false);\n  }, [context.openMobile]);\n\n  // A modal sheet: focus moves in, Tab stays inside, Escape closes, and focus\n  // returns to the opener. The fixed body lock holds on iOS Safari too.\n  const { openMobile, setOpenMobile } = context;\n  const closeMobile = useCallback(() => setOpenMobile(false), [setOpenMobile]);\n  useFocusTrap(openMobile && mounted, panelRef, { onEscape: closeMobile });\n  useScrollLock(openMobile, { fixed: true });\n\n  if (!mounted) return null;\n\n  // This container groups the sheet for hiding and the z-index and carries no\n  // box: both children are `fixed` and resolve against the viewport themselves.\n  // The scrim spans the viewport edges but paints a colour, and the panel is\n  // inset off one side and paints its own surface, so no layer here is a\n  // transparent edge-spanning one.\n  return createPortal(\n    <div\n      className={cn(\n        \"pointer-events-none fixed left-0 top-0 z-50 size-0 md:hidden\",\n        hidden && !context.openMobile ? \"invisible\" : \"visible\",\n      )}\n    >\n      <motion.button\n        type=\"button\"\n        aria-label={context.t(\"close\")}\n        tabIndex={context.openMobile ? 0 : -1}\n        initial={false}\n        animate={{ opacity: context.openMobile ? 1 : 0 }}\n        transition={\n          context.reduce ? REDUCED_TRANSITION : PANEL_TRANSITION\n        }\n        onClick={() => context.setOpenMobile(false)}\n        className={cn(\n          \"fixed inset-0 bg-black/40\",\n          context.openMobile\n            ? \"pointer-events-auto\"\n            : \"pointer-events-none\",\n        )}\n      />\n\n      <motion.div\n        ref={panelRef}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-label={ariaLabel}\n        aria-hidden={!context.openMobile}\n        inert={!context.openMobile}\n        tabIndex={-1}\n        data-mobile=\"true\"\n        data-state={context.openMobile ? \"expanded\" : \"collapsed\"}\n        data-side={side}\n        initial={false}\n        animate={{\n          opacity: context.reduce\n            ? context.openMobile\n              ? 1\n              : 0\n            : 1,\n          x: context.reduce\n            ? 0\n            : context.openMobile\n              ? \"0%\"\n              : side === \"left\"\n                ? \"-100%\"\n                : \"100%\",\n        }}\n        transition={\n          context.reduce ? REDUCED_TRANSITION : PANEL_TRANSITION\n        }\n        onAnimationComplete={() => {\n          if (!openMobileRef.current) setHidden(true);\n        }}\n        className={cn(\n          \"pointer-events-auto fixed inset-y-0 flex h-dvh w-(--sidebar-width-mobile) max-w-[88vw] flex-col overflow-hidden\",\n          \"border-border bg-background shadow-2xl will-change-transform\",\n          side === \"left\" ? \"left-0 border-r\" : \"right-0 border-l\",\n          !context.openMobile && \"pointer-events-none\",\n          className,\n        )}\n      >\n        <AnimatedSidebarPanelContext.Provider\n          value={{ collapsed: false, collapsible: \"none\", side }}\n        >\n          {children}\n        </AnimatedSidebarPanelContext.Provider>\n      </motion.div>\n    </div>,\n    document.body,\n  );\n}\n"},{"path":"components/motion/animated-sidebar/motion.ts","type":"util","content":"import type { Variants } from \"motion/react\";\nimport { EASE_DRAWER, EASE_OUT } from \"@/lib/ease\";\n\nexport const PANEL_TRANSITION = {\n  duration: 0.36,\n  ease: EASE_DRAWER,\n} as const;\n\n// The desktop rail settles at a hard zero-width boundary. Keep the spring\n// critically damped so it cannot overshoot, pause against that boundary, and\n// then snap back during the final frame.\nexport const SIDEBAR_MORPH_TRANSITION = {\n  type: \"spring\",\n  stiffness: 380,\n  damping: 35,\n  mass: 0.75,\n} as const;\n\nexport const LABEL_ENTER_TRANSITION = {\n  duration: 0.2,\n  delay: 0.08,\n  ease: EASE_OUT,\n} as const;\n\nexport const LABEL_EXIT_TRANSITION = {\n  duration: 0.12,\n  ease: EASE_OUT,\n} as const;\n\nconst SUBMENU_TRANSITION = {\n  duration: 0.18,\n  ease: EASE_OUT,\n} as const;\n\nexport const SUBMENU_VARIANTS: Variants = {\n  closed: {\n    opacity: 0,\n    clipPath: \"inset(0 0 100% 0 round 8px)\",\n    transition: {\n      duration: 0.14,\n      ease: EASE_OUT,\n      staggerChildren: 0.025,\n      staggerDirection: -1,\n    },\n  },\n  open: {\n    opacity: 1,\n    clipPath: \"inset(0 0 0% 0 round 8px)\",\n    transition: {\n      duration: 0.2,\n      delayChildren: 0.035,\n      ease: EASE_OUT,\n      staggerChildren: 0.045,\n    },\n  },\n};\n\nexport const SUBMENU_ITEM_VARIANTS: Variants = {\n  closed: {\n    opacity: 0,\n    y: -6,\n    filter: \"blur(3px)\",\n  },\n  open: {\n    opacity: 1,\n    y: 0,\n    filter: \"blur(0px)\",\n    transition: SUBMENU_TRANSITION,\n  },\n};\n\nexport const REDUCED_TRANSITION = {\n  duration: 0.16,\n  ease: EASE_OUT,\n} as const;\n"},{"path":"components/motion/animated-sidebar/use-is-mobile.ts","type":"util","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\nconst MOBILE_QUERY = \"(max-width: 767px)\";\n\nfunction subscribeToMobileQuery(callback: () => void) {\n  const query = window.matchMedia(MOBILE_QUERY);\n  query.addEventListener(\"change\", callback);\n  return () => query.removeEventListener(\"change\", callback);\n}\n\nfunction getMobileSnapshot() {\n  return window.matchMedia(MOBILE_QUERY).matches;\n}\n\nfunction getServerMobileSnapshot() {\n  return false;\n}\n\nexport function useIsMobile() {\n  return useSyncExternalStore(\n    subscribeToMobileQuery,\n    getMobileSnapshot,\n    getServerMobileSnapshot,\n  );\n}\n"},{"path":"components/motion/shared-layout-bg.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  type HTMLMotionProps,\n  motion,\n  useReducedMotion,\n  type Variants,\n} from \"motion/react\";\nimport {\n  Children,\n  cloneElement,\n  forwardRef,\n  type HTMLAttributes,\n  type FocusEvent,\n  isValidElement,\n  type MouseEvent,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useId,\n  useRef,\n  useState,\n} from \"react\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface SharedLayoutBgProps\n  extends Omit<HTMLAttributes<HTMLElement>, \"children\"> {\n  children: ReactNode;\n  /** Semantic container used for the children. */\n  as?: \"div\" | \"ul\";\n  /** Tailwind class applied to the moving pill. Defaults to a subtle foreground tint. */\n  pillClassName?: string;\n  /** Horizontal inset of the pill relative to each row (px). Default 20. */\n  inset?: number;\n  /** Optional positioning override for the pill wrapper inside each item. */\n  pillContainerClassName?: string;\n}\n\nconst variants: Variants = {\n  initial: { opacity: 0, filter: \"blur(6px)\" },\n  animate: { opacity: 1, filter: \"blur(0px)\" },\n  exit: (isActive: boolean) =>\n    !isActive ? { opacity: 0, filter: \"blur(6px)\" } : {},\n};\n\nconst reducedVariants: Variants = {\n  initial: { opacity: 0 },\n  animate: { opacity: 1 },\n  exit: (isActive: boolean) => (!isActive ? { opacity: 0 } : {}),\n};\n\nexport const SharedLayoutBg = forwardRef<HTMLElement, SharedLayoutBgProps>(\n  function SharedLayoutBg(\n    {\n      children,\n      as = \"div\",\n      className,\n      onMouseLeave,\n      onBlur,\n      pillClassName,\n      pillContainerClassName,\n      inset = 20,\n      ...props\n    },\n    forwardedRef,\n  ) {\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const uid = useId();\n  const reduce = useReducedMotion();\n  // Focus leaving the list only clears the pill when the pointer is not\n  // still resting on an item.\n  const hovering = useRef(false);\n\n    const renderedChildren = Children.toArray(children)\n      .filter(isValidElement)\n      .map((child, index) => {\n        const el = child as ReactElement<{\n          className?: string;\n          onMouseEnter?: (event: MouseEvent<HTMLElement>) => void;\n          onFocus?: (event: FocusEvent<HTMLElement>) => void;\n          children?: ReactNode;\n        }>;\n        const childKey = el.key ? String(el.key) : `item-${index}`;\n        return cloneElement(\n          el,\n          {\n            key: childKey,\n            className: cn(\"relative\", el.props.className),\n            onMouseEnter: (event: MouseEvent<HTMLElement>) => {\n              el.props.onMouseEnter?.(event);\n              hovering.current = true;\n              setActiveId(childKey);\n            },\n            // Focus bubbles in React, so a link or button anywhere inside the\n            // item brings the pill to it for keyboard users too.\n            onFocus: (event: FocusEvent<HTMLElement>) => {\n              el.props.onFocus?.(event);\n              setActiveId(childKey);\n            },\n          },\n          <>\n            <AnimatePresence custom={activeId !== null}>\n              {activeId !== null ? (\n                <motion.div\n                  variants={reduce ? reducedVariants : variants}\n                  initial=\"initial\"\n                  animate=\"animate\"\n                  exit=\"exit\"\n                  custom={activeId !== null}\n                  className={cn(\n                    \"pointer-events-none absolute inset-y-0\",\n                    pillContainerClassName,\n                  )}\n                  style={{ left: -inset, right: -inset }}\n                >\n                  {activeId === childKey ? (\n                    <motion.div\n                      layoutId={`shared-bg-${uid}`}\n                      transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n                      className={cn(\n                        \"pointer-events-none h-full w-full rounded-2xl bg-muted/80\",\n                        pillClassName,\n                      )}\n                    />\n                  ) : null}\n                </motion.div>\n              ) : null}\n            </AnimatePresence>\n            <div className=\"relative z-10\">{el.props.children}</div>\n          </>,\n        );\n      });\n\n    const handleMouseLeave = (event: MouseEvent<HTMLElement>) => {\n      hovering.current = false;\n      // Keep the pill on a focused item so keyboard position stays visible.\n      if (!event.currentTarget.contains(document.activeElement))\n        setActiveId(null);\n      onMouseLeave?.(event);\n    };\n\n    const handleBlur = (event: FocusEvent<HTMLElement>) => {\n      const next = event.relatedTarget;\n      if (\n        !hovering.current &&\n        !(next instanceof Node && event.currentTarget.contains(next))\n      )\n        setActiveId(null);\n      onBlur?.(event);\n    };\n\n    // layoutRoot scopes the pill's layout projection to this list, so fixed or\n    // scrolled ancestors can't smear scroll offsets into its movement.\n    return as === \"ul\" ? (\n      <motion.ul\n        {...(props as HTMLMotionProps<\"ul\">)}\n        ref={forwardedRef as Ref<HTMLUListElement>}\n        layoutRoot\n        onMouseLeave={handleMouseLeave}\n        onBlur={handleBlur}\n        className={cn(\"flex w-full flex-col\", className)}\n      >\n        {renderedChildren}\n      </motion.ul>\n    ) : (\n      <motion.div\n        {...(props as HTMLMotionProps<\"div\">)}\n        ref={forwardedRef as Ref<HTMLDivElement>}\n        layoutRoot\n        onMouseLeave={handleMouseLeave}\n        onBlur={handleBlur}\n        className={cn(\"flex w-full flex-col\", className)}\n      >\n        {renderedChildren}\n      </motion.div>\n    );\n  },\n);\n"},{"path":"lib/hooks/use-controllable.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\n\n/**\n * A value that is controlled when `value` is defined and uncontrolled\n * otherwise. Returns the current value, a setter whose identity never changes,\n * and the raw internal setter for callers that resolve state during render.\n *\n * The setter calls `onChange` only when the value actually changes, so a\n * consumer is never told about a no-op.\n */\nexport function useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange?: (next: T) => void,\n) {\n  const [internal, setInternal] = useState(defaultValue);\n  const latest = useRef({ value, internal, onChange });\n  useLayoutEffect(() => {\n    latest.current = { value, internal, onChange };\n  });\n  const set = useCallback((next: T) => {\n    const current = latest.current;\n    if (current.value === undefined) setInternal(next);\n    if ((current.value === undefined ? current.internal : current.value) !== next)\n      current.onChange?.(next);\n  }, []);\n  return [value === undefined ? internal : value, set, setInternal] as const;\n}\n"},{"path":"components/agents/ai-sidebar/marquee-label.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\n\nconst ROW_REVEAL = {\n  duration: 0.16,\n  ease: EASE_OUT,\n} as const;\n\n/** A row label that scrolls its overflow into view while the row is active. */\nexport function MarqueeLabel({ active, children }: { active: boolean; children: string }) {\n  const reduce = useReducedMotion() ?? false;\n  const viewportRef = useRef<HTMLSpanElement>(null);\n  const labelRef = useRef<HTMLSpanElement>(null);\n  const [distance, setDistance] = useState(0);\n\n  useEffect(() => {\n    const measure = () => {\n      const viewport = viewportRef.current;\n      const label = labelRef.current;\n      if (!viewport || !label) return;\n      setDistance(label.scrollWidth > viewport.clientWidth ? label.scrollWidth + 24 : 0);\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    if (viewportRef.current) observer.observe(viewportRef.current);\n    if (labelRef.current) observer.observe(labelRef.current);\n    return () => observer.disconnect();\n  }, []);\n\n  const running = active && distance > 0 && !reduce;\n\n  return (\n    <span ref={viewportRef} className=\"block min-w-0 flex-1 overflow-hidden\">\n      <motion.span\n        className=\"flex w-max items-center gap-6 whitespace-nowrap\"\n        animate={{ x: running ? [0, -distance] : 0 }}\n        transition={\n          running\n            ? {\n                duration: Math.max(2.4, distance / 34),\n                ease: \"linear\",\n                repeat: Number.POSITIVE_INFINITY,\n                repeatDelay: 2,\n              }\n            : ROW_REVEAL\n        }\n      >\n        <span ref={labelRef}>{children}</span>\n        {running ? <span aria-hidden=\"true\">{children}</span> : null}\n      </motion.span>\n    </span>\n  );\n}\n"},{"path":"components/agents/ai-sidebar/resource-menu-action.tsx","type":"util","content":"\"use client\";\n\nimport type { LucideIcon } from \"lucide-react\";\nimport type { ReactNode } from \"react\";\n\nexport function ResourceMenuAction({\n  icon: Icon,\n  onSelect,\n  children,\n}: {\n  icon: LucideIcon;\n  onSelect: () => void;\n  children: ReactNode;\n}) {\n  return (\n    <button\n      type=\"button\"\n      onClick={onSelect}\n      // The same row shape as every library menu: rounded-lg inside the\n      // panel's p-2 (16 − 8), and a foreground tint for hover and focus.\n      className=\"flex h-8 w-full items-center gap-2 rounded-lg px-3 text-left text-xs text-foreground outline-none transition-colors hover:bg-foreground/[0.07] focus-visible:bg-foreground/[0.07] focus-visible:ring-2 focus-visible:ring-ring\"\n    >\n      <Icon aria-hidden=\"true\" className=\"size-3.5 shrink-0\" />\n      <span className=\"min-w-0 truncate\">{children}</span>\n    </button>\n  );\n}\n"},{"path":"components/motion/popover-morph.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useMotionValue,\n  usePresence,\n  useReducedMotion,\n  useTransform,\n} from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { FOCUSABLE_SELECTOR } from \"@/lib/focusable\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { mergeRefs } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\n\ntype Side = \"top\" | \"bottom\";\ntype Align = \"start\" | \"end\";\n\ntype MorphContextValue = {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n  toggle: () => void;\n  triggerId: string;\n  contentId: string;\n  /** The element the panel measures against - see `registerTrigger`. */\n  triggerRef: React.MutableRefObject<HTMLElement | null>;\n  registerTrigger: (node: HTMLElement | null) => void;\n  contentRef: React.MutableRefObject<HTMLDivElement | null>;\n  /** Arms or disarms moving focus into the panel as it next appears. */\n  armFocusOnOpen: (armed: boolean) => void;\n  /** Reads and disarms the flag set by `armFocusOnOpen`. */\n  takeFocusOnOpen: () => boolean;\n};\n\nconst MorphContext = createContext<MorphContextValue | null>(null);\n\nfunction useMorphContext(component: string) {\n  const ctx = useContext(MorphContext);\n  if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);\n  return ctx;\n}\n\nexport interface MorphPopoverProps {\n  children: ReactNode;\n  /** Controlled open state. */\n  open?: boolean;\n  /** Uncontrolled initial open state. */\n  defaultOpen?: boolean;\n  /** Called with the new open state when the panel opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /** Classes merged onto the wrapper around the trigger. */\n  className?: string;\n}\n\n/**\n * A popover whose full-size panel reveals from the corner nearest the trigger\n * on one spring, then retraces the same clip on close. Content and surface\n * edges keep their size throughout. Closes on outside pointer / Escape.\n * Controlled or uncontrolled.\n */\nexport function MorphPopover({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  className,\n}: MorphPopoverProps) {\n  const baseId = useId();\n  const [root, setRoot] = useState<HTMLDivElement | null>(null);\n  const [trigger, setTrigger] = useState<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange],\n  );\n  const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n\n  // A keyboard open arms focus for the panel to take as it appears. Any later\n  // key or pointer press disarms it, so an open the parent declined cannot\n  // leave it armed for a later open that nobody asked to focus.\n  const focusOnOpenRef = useRef(false);\n  const disarmRef = useRef<AbortController | null>(null);\n  const armFocusOnOpen = useCallback((armed: boolean) => {\n    disarmRef.current?.abort();\n    disarmRef.current = null;\n    focusOnOpenRef.current = armed;\n    if (!armed) return;\n    const controller = new AbortController();\n    const disarm = () => {\n      focusOnOpenRef.current = false;\n      controller.abort();\n    };\n    const options = { capture: true, signal: controller.signal };\n    document.addEventListener(\"keydown\", disarm, options);\n    document.addEventListener(\"pointerdown\", disarm, options);\n    disarmRef.current = controller;\n  }, []);\n  const takeFocusOnOpen = useCallback(() => {\n    const armed = focusOnOpenRef.current;\n    armFocusOnOpen(false);\n    return armed;\n  }, [armFocusOnOpen]);\n  useEffect(() => () => disarmRef.current?.abort(), []);\n\n  // A trigger normally registers itself through MorphPopoverTrigger. It can't\n  // when something else already clones the element - a Tooltip wrapping the\n  // button, say - and an unregistered trigger leaves the panel with nothing to\n  // measure against, so it renders permanently invisible. The root boxes the\n  // trigger exactly (the content portals out of it), so it stands in until a\n  // real trigger registers, and stands in again if that one unmounts. Both are\n  // state, so a trigger arriving while the panel is open re-anchors it.\n  const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(\n    () => ({ current: trigger ?? root }),\n    [root, trigger],\n  );\n\n  // The panel is a `role=\"dialog\"` and goes inert the moment it closes, so\n  // focus cannot be left sitting inside it: a dismissal hands it back to the\n  // trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes\n  // the focus onward itself when it lands on something focusable - this only\n  // catches the case where it would otherwise be stranded. When no trigger has\n  // registered, the root anchor stands in only if it can actually hold focus;\n  // there is nowhere better than where the keyboard already is, so leave it.\n  const close = useCallback(() => {\n    setOpen(false);\n    const focused = document.activeElement;\n    const inPanel =\n      focused instanceof HTMLElement && contentRef.current?.contains(focused);\n    if (!inPanel) return;\n    const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);\n    restore?.focus();\n  }, [root, setOpen, trigger]);\n\n  // Inside is the root anchor and the portaled panel. Until the root mounts\n  // there is nothing to measure \"outside\" against, so nothing dismisses.\n  const insidePopover = useCallback(\n    (target: Element) =>\n      !root || root.contains(target) || Boolean(contentRef.current?.contains(target)),\n    [root],\n  );\n  useDismiss(open, close, null, { ignore: insidePopover });\n\n  const ctx = useMemo<MorphContextValue>(\n    () => ({\n      open,\n      setOpen,\n      toggle,\n      triggerId: `${baseId}-trigger`,\n      contentId: `${baseId}-content`,\n      triggerRef: anchorRef,\n      registerTrigger: setTrigger,\n      contentRef,\n      armFocusOnOpen,\n      takeFocusOnOpen,\n    }),\n    [open, setOpen, toggle, baseId, anchorRef, armFocusOnOpen, takeFocusOnOpen],\n  );\n\n  return (\n    <MorphContext.Provider value={ctx}>\n      <div ref={setRoot} className={cn(\"relative inline-flex\", className)}>\n        {children}\n      </div>\n    </MorphContext.Provider>\n  );\n}\n\nexport interface MorphPopoverTriggerProps {\n  children: ReactElement;\n}\n\n/** Wraps a single element, toggling the popover on click. */\nexport function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {\n  const ctx = useMorphContext(\"MorphPopoverTrigger\");\n  const child = children as ReactElement<Record<string, unknown>>;\n  const childOnClick = child?.props?.onClick as\n    | ((e: unknown) => void)\n    | undefined;\n  const childOnKeyDown = child?.props?.onKeyDown as\n    | ((e: unknown) => void)\n    | undefined;\n  const childOnPointerDown = child?.props?.onPointerDown as\n    | ((e: unknown) => void)\n    | undefined;\n  // Set by an Enter or Space keydown on the trigger, cleared by a pointer\n  // press, read by the click that follows.\n  const keyboardRef = useRef(false);\n  const childRef = (child?.props as { ref?: Ref<HTMLElement> } | undefined)\n    ?.ref;\n  // Register once per actual ref change, not once per open-state render.\n  const mergedRef = useMemo(\n    () => mergeRefs(childRef, ctx.registerTrigger),\n    [childRef, ctx.registerTrigger],\n  );\n  if (!isValidElement(children)) return children;\n\n  return cloneElement(child, {\n    id: ctx.triggerId,\n    ref: mergedRef,\n    onKeyDown: (e: unknown) => {\n      childOnKeyDown?.(e);\n      const key = (e as { key?: string } | undefined)?.key;\n      keyboardRef.current = key === \"Enter\" || key === \" \";\n    },\n    onPointerDown: (e: unknown) => {\n      childOnPointerDown?.(e);\n      keyboardRef.current = false;\n    },\n    onClick: (e: unknown) => {\n      childOnClick?.(e);\n      // Enter and Space reach here as a click with `detail` 0 after their\n      // keydown on this element. A pointer click counts at least 1, and a\n      // scripted click() has no keydown before it. Only a keyboard open\n      // moves focus into the panel.\n      const keyboard =\n        keyboardRef.current &&\n        (e as { detail?: number } | undefined)?.detail === 0;\n      keyboardRef.current = false;\n      ctx.armFocusOnOpen(!ctx.open && keyboard);\n      ctx.toggle();\n    },\n    \"aria-haspopup\": \"dialog\",\n    \"aria-expanded\": ctx.open,\n    \"aria-controls\": ctx.open ? ctx.contentId : undefined,\n  });\n}\n\n// Full-distance clip travel needs a shorter curve than SPRING_PANEL's slow\n// overdamped tail. A non-bouncing spring reaches its rest within 260 ms.\nconst MORPH_ENTER = { type: \"spring\", duration: 0.26, bounce: 0 } as const;\nconst MORPH_EXIT = { duration: 0.2, ease: EASE_OUT } as const;\n\n// Keep the panel and content at their final size. An inset clip reveals the\n// nearest corner without scaling borders, shadows or keyboard-focus geometry.\n// A full-size clip keeps content at its final coordinates without box-to-box\n// scale correction. One progress value keeps clip and opacity synchronized;\n// clip-path and the shadow may paint, so this is not a compositor-only morph.\nfunction clipAt(side: Side, align: Align, radius: number, inset: number) {\n  return `inset(${side === \"top\" ? inset : 0}% ${align === \"start\" ? inset : 0}% ${side === \"bottom\" ? inset : 0}% ${align === \"end\" ? inset : 0}% round ${radius}px)`;\n}\n\nexport interface MorphPopoverContentProps {\n  children: ReactNode;\n  /** Preferred side of the trigger. Flips when there is no room. Default: \"bottom\" */\n  side?: Side;\n  /** Lines the panel up with the trigger's start or end edge. Default: \"end\" */\n  align?: Align;\n  /** Gap between trigger and panel, in px. Default 8. */\n  sideOffset?: number;\n  /** Panel corner radius, in px. Default 16 (rounded-2xl), like every floating panel. */\n  radius?: number;\n  /** Draw the surface shadow. Default true. */\n  shadow?: boolean;\n  /**\n   * Runs after the portalled surface is positioned and visible. Passing it\n   * hands focus to the caller: the panel then moves no focus on its own.\n   */\n  onOpenAutoFocus?: (content: HTMLDivElement) => void;\n  /**\n   * Element to focus when the trigger opens the panel by keyboard. Defaults\n   * to the first focusable element in the panel, or the panel itself. A\n   * pointer open does not move focus. Ignored with `onOpenAutoFocus`.\n   */\n  initialFocus?: RefObject<HTMLElement | null>;\n  /** Classes merged onto the panel surface. */\n  className?: string;\n}\n\nexport function MorphPopoverContent(props: MorphPopoverContentProps) {\n  const ctx = useMorphContext(\"MorphPopoverContent\");\n  const [portalReady, setPortalReady] = useState(false);\n  useEffect(() => setPortalReady(true), []);\n  if (!portalReady) return null;\n  return createPortal(\n    <AnimatePresence>\n      {ctx.open && <MorphPopoverSurface {...props} />}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n\n// Measurement belongs to the mounted portal session: reopening must not start\n// an entrance at the previous session's coordinates before measuring this one.\nfunction MorphPopoverSurface({\n  children,\n  side = \"bottom\",\n  align = \"end\",\n  sideOffset = 8,\n  radius = 16,\n  shadow = true,\n  onOpenAutoFocus,\n  initialFocus,\n  className,\n}: MorphPopoverContentProps) {\n  const ctx = useMorphContext(\"MorphPopoverContent\");\n  const reduce = useReducedMotion() ?? false;\n  const [isPresent, safeToRemove] = usePresence();\n  const layout = usePopoverPortalPosition(\n    ctx.triggerRef,\n    ctx.contentRef,\n    isPresent,\n  );\n\n  const preferredLeft = layout\n    ? align === \"end\"\n      ? layout.trigger.left + layout.trigger.width - layout.content.width\n      : layout.trigger.left\n    : 0;\n  // Keep larger compositions, such as calendars, inside the viewport. Prefer\n  // the requested side, then use the roomier side when it cannot fit there.\n  const gutter = 12;\n  const below = layout\n    ? Math.max(\n        0,\n        window.innerHeight -\n          layout.trigger.top -\n          layout.trigger.height -\n          sideOffset -\n          gutter,\n      )\n    : 0;\n  const above = layout\n    ? Math.max(0, layout.trigger.top - sideOffset - gutter)\n    : 0;\n  const requestedSpace = side === \"bottom\" ? below : above;\n  const otherSpace = side === \"bottom\" ? above : below;\n  const resolvedSide =\n    layout &&\n    layout.content.height > requestedSpace &&\n    otherSpace > requestedSpace\n      ? side === \"bottom\"\n        ? \"top\"\n        : \"bottom\"\n      : side;\n  const availableHeight = resolvedSide === \"bottom\" ? below : above;\n  const left = layout\n    ? Math.max(\n        gutter,\n        Math.min(\n          preferredLeft,\n          window.innerWidth - layout.content.width - gutter,\n        ),\n      )\n    : 0;\n  const top = layout\n    ? resolvedSide === \"bottom\"\n      ? layout.trigger.top + layout.trigger.height + sideOffset\n      : Math.max(\n          gutter,\n          layout.trigger.top - layout.content.height - sideOffset,\n        )\n    : 0;\n\n  const progress = useMotionValue(0);\n  const clipPath = useTransform(progress, (p) =>\n    clipAt(resolvedSide, align, radius, 92 * (1 - p)),\n  );\n  const surfaceOpacity = useTransform(progress, [0, 0.15], [0, 1]);\n  // Reduced motion has no travel, so a short fade carries the whole entrance\n  // and exit on its own.\n  const fade = useMotionValue(reduce ? 0 : 1);\n  const ready = layout !== null;\n  const focusedOnOpen = useRef(false);\n  useEffect(() => {\n    if (\n      !ready ||\n      !isPresent ||\n      focusedOnOpen.current ||\n      !ctx.contentRef.current\n    )\n      return;\n    focusedOnOpen.current = true;\n    onOpenAutoFocus?.(ctx.contentRef.current);\n  }, [ready, isPresent, ctx.contentRef, onOpenAutoFocus]);\n  // `safeToRemove` is a new function on every render: AnimatePresence\n  // rebuilds its context each time its parent renders. Read it through a ref\n  // so a render during the exit (a consumer's state change, a list streaming\n  // in) does not restart the exit from where it got to - restarted every\n  // render, it would close in ever smaller steps and never report completion,\n  // leaving an inert, invisible panel mounted for good.\n  const safeToRemoveRef = useRef(safeToRemove);\n  useLayoutEffect(() => {\n    safeToRemoveRef.current = safeToRemove;\n  });\n  useEffect(() => {\n    if (!ready) {\n      if (!isPresent) safeToRemoveRef.current?.();\n      return;\n    }\n    const settle = () => {\n      if (!isPresent) safeToRemoveRef.current?.();\n    };\n    if (reduce) {\n      progress.jump(1);\n      const animation = animate(fade, isPresent ? 1 : 0, {\n        duration: 0.12,\n        onComplete: settle,\n      });\n      return () => animation.stop();\n    }\n    const animation = animate(progress, isPresent ? 1 : 0, {\n      ...(isPresent ? MORPH_ENTER : MORPH_EXIT),\n      onComplete: settle,\n    });\n    return () => animation.stop();\n  }, [fade, progress, ready, isPresent, reduce]);\n\n  // The wrapper stays `visibility: hidden` until the first measurement, and\n  // focus() inside a hidden subtree is silently ignored. So move focus in the\n  // commit that makes the panel visible, not when it mounts. A CSS transition\n  // on `visibility` can still hold the controls hidden for a moment after\n  // that commit (a reduced-motion reset that gives every element a short\n  // transition-duration does), so while focus rests on the panel or has not\n  // moved, each such transition that ends tries the candidates again, until\n  // the user presses a key or pointer. The effect runs once per open, so it\n  // reads the caller's props through refs: a new ref or callback passed\n  // mid-open must not tear down a pending retry.\n  const initialFocusRef = useRef(initialFocus);\n  const callerFocusesRef = useRef(onOpenAutoFocus !== undefined);\n  useLayoutEffect(() => {\n    initialFocusRef.current = initialFocus;\n    callerFocusesRef.current = onOpenAutoFocus !== undefined;\n  });\n  const { contentRef, takeFocusOnOpen } = ctx;\n  useLayoutEffect(() => {\n    if (!ready || !isPresent) return;\n    if (!takeFocusOnOpen() || callerFocusesRef.current) return;\n    const panel = contentRef.current;\n    const wrapper = panel?.parentElement;\n    if (!panel || !wrapper) return;\n    const from = document.activeElement;\n    const unmoved = () =>\n      document.activeElement === from || document.activeElement === panel;\n    // The selector also matches elements focus() refuses: a hidden input, a\n    // disabled button that carries a tabindex, anything under display: none.\n    // Keep the first candidate that takes focus, else hold it on the panel.\n    const focusFirst = () => {\n      const candidates = [\n        initialFocusRef.current?.current,\n        ...panel.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),\n      ];\n      for (const candidate of candidates) {\n        if (!candidate) continue;\n        candidate.focus({ preventScroll: true });\n        if (unmoved()) continue;\n        // preventScroll keeps the page still, but it also stops the panel's\n        // own scroll area from bringing a row below the fold into view.\n        candidate.scrollIntoView?.({ block: \"nearest\" });\n        return true;\n      }\n      panel.focus({ preventScroll: true });\n      return false;\n    };\n    if (focusFirst()) return;\n    const retry = (event: TransitionEvent) => {\n      if (event.propertyName !== \"visibility\") return;\n      if (!unmoved() || focusFirst()) stop();\n    };\n    const stop = () => {\n      wrapper.removeEventListener(\"transitionend\", retry);\n      document.removeEventListener(\"keydown\", stop, true);\n      document.removeEventListener(\"pointerdown\", stop, true);\n    };\n    wrapper.addEventListener(\"transitionend\", retry);\n    document.addEventListener(\"keydown\", stop, true);\n    document.addEventListener(\"pointerdown\", stop, true);\n    return stop;\n  }, [ready, isPresent, contentRef, takeFocusOnOpen]);\n\n  return (\n    <motion.div\n      data-morph-popover-portal=\"\"\n      inert={!isPresent}\n      style={{\n        left,\n        top,\n        opacity: reduce ? fade : surfaceOpacity,\n        pointerEvents: isPresent ? \"auto\" : \"none\",\n        visibility: layout ? \"visible\" : \"hidden\",\n      }}\n      // A drop-shadow follows the clipped surface; box-shadow would be cut\n      // off by its own clip. Caller surface classes retain their old target.\n      className={cn(\n        \"fixed z-[9999]\",\n        shadow && \"[filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]\",\n      )}\n    >\n      <motion.div\n        ref={ctx.contentRef}\n        id={ctx.contentId}\n        role=\"dialog\"\n        aria-labelledby={ctx.triggerId}\n        tabIndex={-1}\n        style={{\n          clipPath: reduce ? undefined : clipPath,\n          borderRadius: radius,\n          maxHeight: layout ? availableHeight : undefined,\n          overflowX: \"hidden\",\n          overflowY: \"auto\",\n        }}\n        className={cn(\n          // The panel holds focus when nothing inside it can. An inset ring\n          // stays inside the clip that would cut off an outline.\n          \"border border-border bg-background outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring\",\n          className,\n        )}\n      >\n        {children}\n      </motion.div>\n    </motion.div>\n  );\n}\n"},{"path":"lib/hooks/use-touch-capable.ts","type":"util","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Returns true on devices that can be touched, whatever else they claim.\n *\n * This is not the inverse of `useHoverCapable`: iPadOS Safari browses\n * desktop-class and answers `(hover: hover) and (pointer: fine)` with true\n * while a finger is the only input there is, so anything that treats\n * hover-capable as \"no touch here\" strands every iPad. Gate the *touch path*\n * of an interaction on this hook and leave hover-only polish on\n * `useHoverCapable`, so a component that opens on hover also opens on tap.\n */\nexport function useTouchCapable() {\n  const [canTouch, setCanTouch] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\") return;\n    const mq = window.matchMedia?.(\"(any-pointer: coarse)\");\n    // iPadOS disguises its pointer media queries; maxTouchPoints it reports\n    // honestly, which is what makes it the standard iPad tell.\n    const update = () =>\n      setCanTouch(Boolean(mq?.matches) || navigator.maxTouchPoints > 0);\n    update();\n    mq?.addEventListener?.(\"change\", update);\n    return () => mq?.removeEventListener?.(\"change\", update);\n  }, []);\n\n  return canTouch;\n}\n"},{"path":"components/motion/action-swap.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence, type HTMLMotionProps, motion, useReducedMotion, type Variants } from \"motion/react\";\nimport type { ReactNode } from \"react\";\nimport { useState } from \"react\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_PRESS, SPRING_SWAP } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ActionSwapItem = {\n  /** Unique key, used as the button's value. */\n  id: string;\n  /** Text shown on the button while this item is active. Hidden when `iconOnly`. */\n  label: ReactNode;\n  /** Icon shown before the label while this item is active. */\n  icon?: ReactNode;\n  /** Accessible name while active. Falls back to a string label when `iconOnly`. */\n  ariaLabel?: string;\n};\n\nexport type ActionSwapButtonVariant = \"primary\" | \"secondary\" | \"outline\" | \"ghost\";\nexport type ActionSwapButtonSize = \"sm\" | \"md\" | \"lg\" | \"icon\";\nexport type ActionSwapAnimation = \"blur\" | \"roll\" | \"cascade\";\n\n/** Animations with a single-element variant set (cascade animates per letter). */\ntype CoreAnimation = \"blur\" | \"roll\";\n\nexport interface ActionSwapButtonProps extends Omit<\n  HTMLMotionProps<\"button\">,\n  \"children\" | \"onChange\"\n> {\n  /** States the button steps through, each with a label and optional icon. */\n  items: ActionSwapItem[];\n  /** The id of the shown item, for controlled use. */\n  value?: string;\n  /** The initial item id when uncontrolled. Default: the first item. */\n  defaultValue?: string;\n  /** Called with the next item's id and the item when a press advances it. */\n  onValueChange?: (value: string, item: ActionSwapItem) => void;\n  /** Visual style of the button. Default: \"secondary\" */\n  variant?: ActionSwapButtonVariant;\n  /** Button height and padding. Default: \"md\" */\n  size?: ActionSwapButtonSize;\n  /** How the label and icon swap between items. Default: \"blur\" */\n  animation?: ActionSwapAnimation;\n  /** Show only the icon and use the label as the accessible name. Default: true for size \"icon\" */\n  iconOnly?: boolean;\n  /** Advance to the next item on each press, wrapping at the end. Default: true */\n  cycle?: boolean;\n}\n\nexport interface ActionSwapTextProps {\n  /** Key for the current text; a new value plays the swap. */\n  value: string;\n  children: ReactNode;\n  /** How the old text leaves and the new text enters. Default: \"blur\" */\n  animation?: ActionSwapAnimation;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nexport interface ActionSwapIconProps {\n  /** Key for the current icon; a new value plays the swap. */\n  value: string;\n  children: ReactNode;\n  /** How the old icon leaves and the new one enters. \"cascade\" plays as \"roll\". Default: \"blur\" */\n  animation?: ActionSwapAnimation;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\n// The arriving layer springs in, so a second press mid-swap bends it toward\n// the new target instead of restarting. The leaving layer is a little quicker,\n// still long enough to cross the arrival so the swap reads as one morph.\nconst BLUR_TRANSITION = SPRING_SWAP;\nconst BLUR_EXIT_TRANSITION = { duration: 0.16, ease: EASE_OUT } as const;\nconst ROLL_TRANSITION = SPRING_SWAP;\nconst ROLL_EXIT_TRANSITION = { duration: 0.14, ease: EASE_OUT } as const;\n// A light blur softens the crossing without smearing small glyphs.\nconst SWAP_BLUR = \"blur(2px)\";\nconst ROLL_BLUR = \"blur(3px)\";\n\n// Cascade rolls the label one letter at a time, left to right. The leaving\n// and landing strings overlap as independent layers (no shared cells), so\n// proportional glyph widths never jitter. Exits cascade at half the enter\n// stagger so the tail of the old label lingers briefly.\nconst CASCADE_STAGGER = 0.025;\n\nconst CASCADE_LETTER_VARIANTS: Variants = {\n  initial: { opacity: 0, y: \"105%\", filter: ROLL_BLUR },\n  animate: (delay: number = 0) => ({\n    opacity: 1,\n    y: \"0%\",\n    filter: \"blur(0px)\",\n    transition: { ...SPRING_SWAP, delay },\n  }),\n  exit: (delay: number = 0) => ({\n    opacity: 0,\n    y: \"-105%\",\n    filter: ROLL_BLUR,\n    transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },\n  }),\n};\n\nconst TEXT_VARIANTS: Record<CoreAnimation, Variants> = {\n  blur: {\n    initial: { opacity: 0, scale: 0.9, filter: SWAP_BLUR },\n    animate: {\n      opacity: 1,\n      scale: 1,\n      filter: \"blur(0px)\",\n      transition: BLUR_TRANSITION,\n    },\n    exit: {\n      opacity: 0,\n      scale: 0.96,\n      filter: SWAP_BLUR,\n      transition: BLUR_EXIT_TRANSITION,\n    },\n  },\n  roll: {\n    initial: { opacity: 0, y: \"90%\", filter: ROLL_BLUR },\n    animate: {\n      opacity: 1,\n      y: \"0%\",\n      filter: \"blur(0px)\",\n      transition: ROLL_TRANSITION,\n    },\n    exit: {\n      opacity: 0,\n      y: \"-90%\",\n      filter: ROLL_BLUR,\n      transition: ROLL_EXIT_TRANSITION,\n    },\n  },\n};\n\nconst ICON_VARIANTS: Record<CoreAnimation, Variants> = {\n  blur: {\n    initial: { opacity: 0, scale: 0.25, filter: SWAP_BLUR },\n    animate: {\n      opacity: 1,\n      scale: 1,\n      filter: \"blur(0px)\",\n      transition: BLUR_TRANSITION,\n    },\n    exit: {\n      opacity: 0,\n      scale: 0.25,\n      filter: SWAP_BLUR,\n      transition: BLUR_EXIT_TRANSITION,\n    },\n  },\n  roll: {\n    initial: { opacity: 0, y: 12, filter: ROLL_BLUR },\n    animate: {\n      opacity: 1,\n      y: 0,\n      filter: \"blur(0px)\",\n      transition: ROLL_TRANSITION,\n    },\n    exit: {\n      opacity: 0,\n      y: -12,\n      filter: ROLL_BLUR,\n      transition: ROLL_EXIT_TRANSITION,\n    },\n  },\n};\n\nconst VARIANT_CLASS: Record<ActionSwapButtonVariant, string> = {\n  primary: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n  secondary: \"border border-border bg-card text-foreground hover:border-border\",\n  outline: \"border border-border bg-transparent text-foreground hover:bg-muted/60\",\n  ghost: \"text-muted-foreground hover:bg-muted/60 hover:text-foreground\",\n};\n\nconst SIZE_CLASS: Record<ActionSwapButtonSize, string> = {\n  sm: \"h-8 gap-1.5 rounded-full px-3 text-xs\",\n  md: \"h-10 gap-2 rounded-full px-4 text-sm\",\n  lg: \"h-12 gap-2.5 rounded-full px-5 text-base\",\n  icon: \"h-10 w-10 rounded-full\",\n};\n\nexport function ActionSwapText({\n  value,\n  children,\n  animation = \"blur\",\n  className,\n}: ActionSwapTextProps) {\n  const reduce = useReducedMotion();\n\n  // Cascade needs a plain string to split into letters; non-string content\n  // and reduced motion fall back to the closest single-element animation.\n  const label = typeof children === \"string\" ? children : null;\n  const cascade = animation === \"cascade\" && label !== null && !reduce;\n  const coreAnimation: CoreAnimation =\n    animation === \"cascade\" ? \"roll\" : animation;\n\n  return (\n    <span\n      className={cn(\n        \"relative -my-[0.08em] inline-block max-w-full whitespace-nowrap py-[0.08em] align-bottom\",\n        className,\n      )}\n      style={{\n        clipPath: \"inset(0 -999px)\",\n        WebkitClipPath: \"inset(0 -999px)\",\n      }}\n    >\n      <span\n        aria-hidden\n        className=\"invisible inline-block whitespace-nowrap\"\n      >\n        {cascade\n          ? label.split(\"\").map((char, index) => (\n              <span\n                // biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.\n                key={index}\n                className=\"inline-block whitespace-pre\"\n              >\n                {char}\n              </span>\n            ))\n          : children}\n      </span>\n      {cascade ? (\n        <>\n          {/* Letters are decorative fragments; readers get the whole label. */}\n          <span className=\"sr-only\">{label}</span>\n          <AnimatePresence initial={false}>\n            <motion.span\n              key={`cascade-${value}`}\n              aria-hidden\n              initial=\"initial\"\n              animate=\"animate\"\n              exit=\"exit\"\n              className=\"absolute left-0 top-[0.08em] inline-block whitespace-pre\"\n            >\n              {label.split(\"\").map((char, i) => (\n                <motion.span\n                  // biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity - the letter at a position is exactly what rolls.\n                  key={i}\n                  custom={i * CASCADE_STAGGER}\n                  variants={CASCADE_LETTER_VARIANTS}\n                  // Own states: a label that swaps away and straight back\n                  // re-enters mid-exit, and only owned targets are restored.\n                  initial=\"initial\"\n                  animate=\"animate\"\n                  exit=\"exit\"\n                  className=\"inline-block whitespace-pre will-change-[opacity,filter,transform]\"\n                >\n                  {char}\n                </motion.span>\n              ))}\n            </motion.span>\n          </AnimatePresence>\n        </>\n      ) : (\n        <AnimatePresence initial={false}>\n          <motion.span\n            key={`${animation}-${value}`}\n            variants={TEXT_VARIANTS[coreAnimation]}\n            initial={reduce ? false : \"initial\"}\n            animate={reduce ? { opacity: 1, filter: \"blur(0px)\", scale: 1, y: 0 } : \"animate\"}\n            exit={reduce ? undefined : \"exit\"}\n            // Truncation lives on the layer that holds the text - the layer\n            // moves as a whole, so clipping it never eats the roll.\n            className=\"absolute left-0 top-[0.08em] inline-block max-w-full truncate will-change-[opacity,filter,transform]\"\n          >\n            {children}\n          </motion.span>\n        </AnimatePresence>\n      )}\n    </span>\n  );\n}\n\nexport function ActionSwapIcon({\n  value,\n  children,\n  animation = \"blur\",\n  className,\n}: ActionSwapIconProps) {\n  const reduce = useReducedMotion();\n  // Icons are single elements - cascade maps to its closest motion, roll.\n  const coreAnimation: CoreAnimation =\n    animation === \"cascade\" ? \"roll\" : animation;\n\n  return (\n    <span className={cn(\"relative inline-grid shrink-0 place-items-center overflow-hidden\", className)}>\n      <AnimatePresence mode=\"popLayout\" initial={false}>\n        <motion.span\n          key={`${animation}-${value}`}\n          aria-hidden\n          variants={ICON_VARIANTS[coreAnimation]}\n          initial={reduce ? false : \"initial\"}\n          animate={reduce ? { opacity: 1, filter: \"blur(0px)\", scale: 1, y: 0 } : \"animate\"}\n          exit={reduce ? undefined : \"exit\"}\n          className=\"col-start-1 row-start-1 inline-flex items-center justify-center will-change-[opacity,filter,transform]\"\n        >\n          {children}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n\nexport function ActionSwapButton({\n  items,\n  value,\n  defaultValue,\n  onValueChange,\n  variant = \"secondary\",\n  size = \"md\",\n  animation = \"blur\",\n  iconOnly = size === \"icon\",\n  cycle = true,\n  className,\n  disabled,\n  onClick,\n  style,\n  ...rest\n}: ActionSwapButtonProps) {\n  const reduce = useReducedMotion();\n  const [internalValue, setInternalValue] = useState(defaultValue ?? items[0]?.id);\n  const currentValue = value ?? internalValue;\n  const activeIndex = Math.max(0, items.findIndex((item) => item.id === currentValue));\n  const activeItem = items[activeIndex] ?? items[0];\n  const hasIcon = items.some((item) => item.icon);\n  const nextItem = cycle && items.length > 0 ? items[(activeIndex + 1) % items.length] : undefined;\n\n  if (!activeItem) return null;\n\n  const accessibleLabel = activeItem.ariaLabel ?? (iconOnly && typeof activeItem.label === \"string\" ? activeItem.label : undefined);\n  const layoutTransition = reduce ? { duration: 0 } : SPRING_LAYOUT;\n\n  return (\n    <motion.button\n      type=\"button\"\n      disabled={disabled}\n      // A label of a different length resizes the button: glide the width on\n      // the soft layout spring, and only when the value changes, so unrelated\n      // page reflow never animates the button.\n      layout\n      layoutDependency={activeItem.id}\n      whileTap={reduce || disabled ? undefined : { scale: 0.97 }}\n      transition={{ ...SPRING_PRESS, layout: layoutTransition }}\n      // Layout animations only correct a radius set inline.\n      style={{ borderRadius: 9999, ...style }}\n      className={cn(\n        \"inline-flex items-center justify-center overflow-hidden font-medium transition-colors\",\n        \"disabled:pointer-events-none disabled:opacity-50\",\n        VARIANT_CLASS[variant],\n        SIZE_CLASS[size],\n        className,\n      )}\n      aria-label={accessibleLabel}\n      onClick={(event) => {\n        onClick?.(event);\n        if (event.defaultPrevented || disabled || !cycle || !nextItem) return;\n        if (value === undefined) setInternalValue(nextItem.id);\n        onValueChange?.(nextItem.id, nextItem);\n      }}\n      {...rest}\n    >\n      {/* Position-only layout keeps the contents from stretching with the\n          button while its width glides. */}\n      {hasIcon ? (\n        <motion.span\n          layout=\"position\"\n          layoutDependency={activeItem.id}\n          transition={layoutTransition}\n          className=\"inline-flex shrink-0\"\n        >\n          <ActionSwapIcon value={activeItem.id} animation={animation} className=\"h-4 w-4\">\n            {activeItem.icon ?? null}\n          </ActionSwapIcon>\n        </motion.span>\n      ) : null}\n      {!iconOnly ? (\n        <motion.span\n          layout=\"position\"\n          layoutDependency={activeItem.id}\n          transition={layoutTransition}\n          className=\"inline-flex min-w-0 max-w-full\"\n        >\n          <ActionSwapText value={activeItem.id} animation={animation}>\n            {activeItem.label}\n          </ActionSwapText>\n        </motion.span>\n      ) : null}\n    </motion.button>\n  );\n}\n"},{"path":"components/motion/button/base.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  type HTMLMotionProps,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  forwardRef,\n  type MouseEvent,\n  type PointerEvent,\n  type ReactNode,\n  useCallback,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { useSound } from \"@/lib/sound\";\nimport { pressSound } from \"@/lib/sounds/press\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ButtonVariant = \"primary\" | \"secondary\" | \"ghost\" | \"outline\";\nexport type ButtonSize = \"sm\" | \"md\" | \"lg\" | \"icon\";\n\nexport interface ButtonProps extends Omit<\n  HTMLMotionProps<\"button\">,\n  \"children\"\n> {\n  /** Visual style: filled, card, ghost or outline. Default: \"primary\" */\n  variant?: ButtonVariant;\n  /** Height and padding; \"icon\" is a square icon-only button. Default: \"md\" */\n  size?: ButtonSize;\n  /** Scale while pressed. Default 0.97: subtle, so the press reads as feedback, not a squash. */\n  pressScale?: number;\n  /** Spawn a Material-style ripple from the press point. Off by default. */\n  ripple?: boolean;\n  /** Play a soft press sound. Off by default; a `SoundProvider` can mute it app-wide. */\n  sound?: boolean;\n  children?: ReactNode;\n}\n\nexport interface ButtonLinkProps extends Omit<\n  HTMLMotionProps<\"a\">,\n  \"children\"\n> {\n  /** Visual style: filled, card, ghost or outline. Default: \"primary\" */\n  variant?: ButtonVariant;\n  /** Height and padding; \"icon\" is a square icon-only link. Default: \"md\" */\n  size?: ButtonSize;\n  /** Scale while pressed. Default 0.97. */\n  pressScale?: number;\n  children?: ReactNode;\n}\n\ntype Ripple = { id: number; x: number; y: number; size: number };\n\nconst VARIANT_CLASS: Record<ButtonVariant, string> = {\n  primary: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n  secondary: \"border border-border bg-card text-foreground hover:border-border\",\n  ghost: \"text-muted-foreground hover:text-foreground hover:bg-muted/60\",\n  outline:\n    \"border border-border bg-transparent text-foreground hover:bg-muted/60\",\n};\n\nconst SIZE_CLASS: Record<ButtonSize, string> = {\n  sm: \"h-8 px-3 text-xs gap-1.5 rounded-full\",\n  md: \"h-10 px-5 text-sm gap-2 rounded-full\",\n  lg: \"h-12 px-6 text-base gap-2 rounded-full\",\n  icon: \"h-8 w-8 rounded-full\",\n};\n\nexport const Button = forwardRef<HTMLButtonElement, ButtonProps>(\n  function Button(\n    {\n      variant = \"primary\",\n      size = \"md\",\n      pressScale = 0.97,\n      ripple = false,\n      sound = false,\n      className,\n      children,\n      onPointerDown,\n      onClick,\n      ...rest\n    },\n    ref,\n  ) {\n    const reduce = useReducedMotion();\n    const [ripples, setRipples] = useState<Ripple[]>([]);\n    const nextId = useRef(0);\n    const play = useSound(pressSound, { enabled: sound });\n\n    const handleClick = useCallback(\n      (event: MouseEvent<HTMLButtonElement>) => {\n        // `detail` is 0 for a click the keyboard made; a pointer press already sounded.\n        if (event.detail === 0) play();\n        onClick?.(event);\n      },\n      [play, onClick],\n    );\n\n    const handlePointerDown = useCallback(\n      (event: PointerEvent<HTMLButtonElement>) => {\n        play();\n        if (ripple && !reduce) {\n          const rect = event.currentTarget.getBoundingClientRect();\n          const size = Math.max(rect.width, rect.height) * 2;\n          const id = nextId.current++;\n          setRipples((prev) => [\n            ...prev,\n            {\n              id,\n              x: event.clientX - rect.left,\n              y: event.clientY - rect.top,\n              size,\n            },\n          ]);\n        }\n        onPointerDown?.(event);\n      },\n      [ripple, reduce, onPointerDown, play],\n    );\n\n    return (\n      // Hover changes colour only: a hover scale blurs the label, and buttons\n      // are hovered far too often for movement to earn its place.\n      <motion.button\n        ref={ref}\n        type=\"button\"\n        whileTap={reduce ? undefined : { scale: pressScale }}\n        transition={SPRING_PRESS}\n        onPointerDown={handlePointerDown}\n        onClick={handleClick}\n        className={cn(\n          \"inline-flex items-center justify-center font-medium select-none\",\n          \"transition-colors\",\n          \"disabled:pointer-events-none disabled:opacity-50\",\n          ripple && \"relative overflow-hidden\",\n          VARIANT_CLASS[variant],\n          SIZE_CLASS[size],\n          className,\n        )}\n        {...rest}\n      >\n        {ripple && !reduce ? (\n          <span className=\"pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]\">\n            <AnimatePresence>\n              {ripples.map((r) => (\n                <motion.span\n                  key={r.id}\n                  className=\"absolute rounded-full bg-current\"\n                  style={{\n                    left: r.x,\n                    top: r.y,\n                    width: r.size,\n                    height: r.size,\n                    x: \"-50%\",\n                    y: \"-50%\",\n                  }}\n                  initial={{ scale: 0.05, opacity: 0.3 }}\n                  animate={{ scale: 1, opacity: 0 }}\n                  exit={{ opacity: 0 }}\n                  transition={{ duration: 0.8, ease: EASE_OUT }}\n                  onAnimationComplete={() =>\n                    setRipples((prev) => prev.filter((x) => x.id !== r.id))\n                  }\n                />\n              ))}\n            </AnimatePresence>\n          </span>\n        ) : null}\n        {children}\n      </motion.button>\n    );\n  },\n);\n\nexport const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(\n  function ButtonLink(\n    {\n      variant = \"primary\",\n      size = \"md\",\n      pressScale = 0.97,\n      className,\n      children,\n      ...rest\n    },\n    ref,\n  ) {\n    const reduce = useReducedMotion();\n\n    return (\n      <motion.a\n        ref={ref}\n        whileTap={reduce ? undefined : { scale: pressScale }}\n        transition={SPRING_PRESS}\n        className={cn(\n          \"inline-flex items-center justify-center font-medium select-none\",\n          \"transition-colors\",\n          VARIANT_CLASS[variant],\n          SIZE_CLASS[size],\n          className,\n        )}\n        {...rest}\n      >\n        {children}\n      </motion.a>\n    );\n  },\n);\n"},{"path":"components/motion/button/magnetic.tsx","type":"util","content":"\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { Magnetic } from \"../magnetic\";\nimport { Button, type ButtonProps } from \"./base\";\n\nexport interface MagneticButtonProps extends ButtonProps {\n  /** Magnetic pull strength. Default 0.25. */\n  strength?: number;\n  /** Class applied to the magnetic wrapper. */\n  magneticClassName?: string;\n}\n\nexport const MagneticButton = forwardRef<HTMLButtonElement, MagneticButtonProps>(function MagneticButton(\n  { strength = 0.25, magneticClassName, children, ...rest },\n  ref,\n) {\n  return (\n    <Magnetic strength={strength} className={magneticClassName}>\n      <Button ref={ref} {...rest}>\n        {children}\n      </Button>\n    </Magnetic>\n  );\n});\n"},{"path":"components/motion/button/metallic.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { forwardRef, useState } from \"react\";\nimport { EASE_IN_OUT, EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { Button, type ButtonProps } from \"./base\";\n\nexport interface MetallicButtonProps extends Omit<\n  ButtonProps,\n  \"ripple\" | \"variant\"\n> {\n  /** Stops the traveling reflection while preserving the chrome rim. */\n  paused?: boolean;\n}\n\n// The rim and highlight drift separately so the material stays quiet and reflective.\nconst SILVER_DRIFT = {\n  duration: 8,\n  ease: EASE_IN_OUT,\n  repeat: Infinity,\n};\n\n// One quick sweep on hover. Leaving resets it instantly: both ends sit outside\n// the button, so the jump is invisible and no reverse sweep plays.\nconst CHROME_SHIMMER = {\n  duration: 0.9,\n  ease: EASE_OUT,\n};\nconst CHROME_RESET = { duration: 0 };\n\nexport const MetallicButton = forwardRef<\n  HTMLButtonElement,\n  MetallicButtonProps\n>(function MetallicButton(\n  {\n    size = \"md\",\n    paused = false,\n    className,\n    children,\n    onHoverStart,\n    onHoverEnd,\n    ...rest\n  },\n  ref,\n) {\n  const reduce = useReducedMotion();\n  const still = paused || Boolean(reduce);\n  const [hovered, setHovered] = useState(false);\n\n  return (\n    <Button\n      ref={ref}\n      variant=\"ghost\"\n      size={size}\n      onHoverStart={(event, info) => {\n        setHovered(true);\n        onHoverStart?.(event, info);\n      }}\n      onHoverEnd={(event, info) => {\n        setHovered(false);\n        onHoverEnd?.(event, info);\n      }}\n      className={cn(\n        \"group relative isolate overflow-hidden border-0 bg-transparent text-foreground\",\n        \"hover:bg-transparent hover:text-foreground\",\n        \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2\",\n        \"shadow-[0_8px_22px_rgba(0,0,0,0.16)]\",\n        size === \"icon\" && \"rounded-full\",\n        className,\n      )}\n      {...rest}\n    >\n      <motion.span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-y-0 left-[-18%] z-0 w-[136%] rounded-[inherit] bg-[linear-gradient(105deg,#111_0%,#737373_14%,#fafafa_26%,#525252_38%,#0a0a0a_50%,#a3a3a3_64%,#fff_75%,#404040_87%,#111_100%)]\"\n        animate={still ? undefined : { x: [\"0%\", \"13%\", \"0%\"] }}\n        transition={still ? undefined : SILVER_DRIFT}\n      />\n\n      <motion.span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-y-0 left-[-58%] z-[1] w-[52%] -skew-x-12 bg-[linear-gradient(90deg,transparent,rgba(255,255,255,0.5)_48%,transparent)] opacity-50 blur-[3px] mix-blend-screen\"\n        animate={still ? undefined : { x: hovered ? \"310%\" : \"0%\" }}\n        transition={still ? undefined : hovered ? CHROME_SHIMMER : CHROME_RESET}\n      />\n\n      <span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-[2px] z-[2] rounded-[inherit] bg-background transition-colors group-hover:bg-muted/40\"\n      />\n\n      <span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-[2px] z-[3] rounded-[inherit] shadow-[inset_0_1px_0_rgba(255,255,255,0.28),inset_0_-1px_0_rgba(0,0,0,0.16)]\"\n      />\n\n      <span className=\"relative z-10 inline-flex items-center justify-center gap-2\">\n        {children}\n      </span>\n    </Button>\n  );\n});\n"},{"path":"components/motion/button/stateful.tsx","type":"util","content":"\"use client\";\n\nimport { Check, Loader2, X } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  motion,\n  useReducedMotion,\n  type Variants,\n} from \"motion/react\";\nimport {\n  forwardRef,\n  type ReactNode,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { Button, type ButtonProps } from \"./base\";\n\nexport type ButtonState = \"idle\" | \"loading\" | \"success\" | \"error\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const statefulButtonMessages = {\n  loading: \"Loading\",\n  success: \"Done\",\n  error: \"Try again\",\n};\n\nexport type StatefulButtonMessages = typeof statefulButtonMessages;\n\nexport interface StatefulButtonProps extends Omit<ButtonProps, \"children\"> {\n  /** Which state to show. Loading also disables the button. Default: \"idle\" */\n  state?: ButtonState;\n  children: ReactNode;\n  /** Text shown while loading. Default: \"Loading\" */\n  loadingText?: ReactNode;\n  /** Text shown on success. Default: \"Done\" */\n  successText?: ReactNode;\n  /** Text shown on error. Default: \"Try again\" */\n  errorText?: ReactNode;\n  /** Trailing icon shown only while idle. */\n  icon?: ReactNode;\n  /** Override any built-in string. */\n  labels?: Partial<StatefulButtonMessages>;\n}\n\nconst CASCADE_STAGGER = 0.025;\nconst ROLL_BLUR = \"blur(6px)\";\n\nconst CASCADE_LETTER_VARIANTS: Variants = {\n  initial: { opacity: 0, y: \"105%\", filter: ROLL_BLUR },\n  animate: (delay: number = 0) => ({\n    opacity: 1,\n    y: \"0%\",\n    filter: \"blur(0px)\",\n    transition: { ...SPRING_SWAP, delay },\n  }),\n  exit: (delay: number = 0) => ({\n    opacity: 0,\n    y: \"-105%\",\n    filter: ROLL_BLUR,\n    transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },\n  }),\n};\n\nconst ICON_VARIANTS: Variants = {\n  // Width collapses too, so the icon adds/removes its own space smoothly\n  // instead of popping the row width in a single frame.\n  initial: { opacity: 0, width: 0, scale: 0.7, filter: ROLL_BLUR },\n  animate: {\n    opacity: 1,\n    width: \"1.5rem\",\n    scale: 1,\n    filter: \"blur(0px)\",\n    transition: SPRING_SWAP,\n  },\n  exit: {\n    opacity: 0,\n    width: 0,\n    scale: 0.7,\n    filter: ROLL_BLUR,\n    transition: { duration: 0.16, ease: EASE_OUT },\n  },\n};\n\nfunction IconSlot({ keyId, children }: { keyId: string; children: ReactNode }) {\n  const reduce = useReducedMotion();\n  return (\n    <motion.span\n      key={keyId}\n      variants={ICON_VARIANTS}\n      initial={reduce ? { opacity: 0 } : \"initial\"}\n      animate={reduce ? { opacity: 1 } : \"animate\"}\n      exit={reduce ? { opacity: 0 } : \"exit\"}\n      transition={reduce ? { duration: 0.15 } : undefined}\n      className=\"inline-grid shrink-0 place-items-center overflow-hidden\"\n    >\n      {children}\n    </motion.span>\n  );\n}\n\nfunction TextSlot({\n  value,\n  children,\n}: {\n  value: string;\n  children: ReactNode;\n}) {\n  const reduce = useReducedMotion();\n  const measureRef = useRef<HTMLSpanElement>(null);\n  const [width, setWidth] = useState<number>();\n  const label = typeof children === \"string\" ? children : null;\n  const cascade = label !== null && !reduce;\n\n  // Measure strings with the same per-letter layout as the cascade. Measuring\n  // the whole string preserves kerning, which can make it narrower than the\n  // inline-block letters and clip the final glyph during the width animation.\n  useLayoutEffect(() => {\n    const nextWidth = measureRef.current?.offsetWidth;\n    if (!nextWidth) return;\n    setWidth((current) => (current === nextWidth ? current : nextWidth));\n  });\n\n  return (\n    <motion.span\n      initial={false}\n      animate={{ width }}\n      transition={reduce ? { duration: 0 } : SPRING_SWAP}\n      className=\"relative inline-block overflow-hidden whitespace-nowrap align-bottom\"\n    >\n      <span\n        ref={measureRef}\n        aria-hidden\n        className=\"invisible inline-block whitespace-nowrap\"\n      >\n        {cascade\n          ? label.split(\"\").map((char, index) => (\n              <span\n                // biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.\n                key={index}\n                className=\"inline-block whitespace-pre\"\n              >\n                {char}\n              </span>\n            ))\n          : children}\n      </span>\n\n      {cascade ? (\n        <>\n          <span className=\"sr-only\">{label}</span>\n          <AnimatePresence initial={false}>\n            <motion.span\n              key={`cascade-${value}`}\n              aria-hidden\n              initial=\"initial\"\n              animate=\"animate\"\n              exit=\"exit\"\n              className=\"absolute left-0 top-0 inline-block whitespace-pre\"\n            >\n              {label.split(\"\").map((char, index) => (\n                <motion.span\n                  // biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.\n                  key={index}\n                  custom={index * CASCADE_STAGGER}\n                  variants={CASCADE_LETTER_VARIANTS}\n                  // Own states: a label that swaps away and straight back\n                  // re-enters mid-exit, and only owned targets are restored.\n                  initial=\"initial\"\n                  animate=\"animate\"\n                  exit=\"exit\"\n                  className=\"inline-block whitespace-pre will-change-[opacity,filter,transform]\"\n                >\n                  {char}\n                </motion.span>\n              ))}\n            </motion.span>\n          </AnimatePresence>\n        </>\n      ) : (\n        <AnimatePresence initial={false}>\n          <motion.span\n            key={`text-${value}`}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: ROLL_BLUR }}\n            animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: \"blur(0px)\" }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: ROLL_BLUR }}\n            transition={reduce ? { duration: 0.15 } : SPRING_SWAP}\n            className=\"absolute left-0 top-0 inline-block will-change-[opacity,filter,transform]\"\n          >\n            {children}\n          </motion.span>\n        </AnimatePresence>\n      )}\n    </motion.span>\n  );\n}\n\nexport const StatefulButton = forwardRef<HTMLButtonElement, StatefulButtonProps>(function StatefulButton(\n  {\n    state = \"idle\",\n    children,\n    loadingText,\n    successText,\n    errorText,\n    icon,\n    labels,\n    disabled,\n    ...rest\n  },\n  ref,\n) {\n  const t = useMessages(\"statefulButton\", statefulButtonMessages, labels);\n  const isBusy = state === \"loading\";\n  const stateText =\n    state === \"loading\"\n      ? (loadingText ?? t(\"loading\"))\n      : state === \"success\"\n        ? (successText ?? t(\"success\"))\n        : state === \"error\"\n        ? (errorText ?? t(\"error\"))\n        : children;\n  const textKey =\n    typeof stateText === \"string\" ? `${state}-${stateText}` : state;\n\n  return (\n    <Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} {...rest}>\n      <span\n        aria-live=\"polite\"\n        className=\"relative inline-flex items-center justify-center overflow-hidden\"\n      >\n        <AnimatePresence initial={false}>\n          {state === \"loading\" ? (\n            <IconSlot keyId=\"loading-icon\">\n              <Loader2 className=\"h-4 w-4 animate-spin\" />\n            </IconSlot>\n          ) : null}\n          {state === \"success\" ? (\n            <IconSlot keyId=\"success-icon\">\n              <Check className=\"h-4 w-4\" />\n            </IconSlot>\n          ) : null}\n          {state === \"error\" ? (\n            <IconSlot keyId=\"error-icon\">\n              <X className=\"h-4 w-4\" />\n            </IconSlot>\n          ) : null}\n        </AnimatePresence>\n\n        <TextSlot value={textKey}>{stateText}</TextSlot>\n\n        <AnimatePresence initial={false}>\n          {state === \"idle\" && icon ? (\n            <IconSlot keyId=\"idle-icon\">{icon}</IconSlot>\n          ) : null}\n        </AnimatePresence>\n      </span>\n    </Button>\n  );\n});\n"},{"path":"components/motion/tooltip/grace.ts","type":"util","content":"type Point = { x: number; y: number };\ntype Box = { left: number; top: number; right: number; bottom: number };\n\n/**\n * The corridor a pointer may cross between the trigger and the open tooltip\n * without closing it: the convex hull of where it left and the box it is\n * heading for. A fixed timeout either cuts a slow diagonal move short or keeps\n * the label alive after the pointer has plainly gone elsewhere; this follows\n * the path itself.\n */\nexport function graceArea(exit: Point, target: Box): Point[] {\n  // A few pixels either side of the exit point give the corridor some width at\n  // its narrow end, so a hand that drifts sideways while it moves stays inside.\n  const pad = 5;\n  return hull([\n    { x: exit.x - pad, y: exit.y - pad },\n    { x: exit.x + pad, y: exit.y - pad },\n    { x: exit.x - pad, y: exit.y + pad },\n    { x: exit.x + pad, y: exit.y + pad },\n    { x: target.left, y: target.top },\n    { x: target.right, y: target.top },\n    { x: target.right, y: target.bottom },\n    { x: target.left, y: target.bottom },\n  ]);\n}\n\nexport function inBox(point: Point, box: Box) {\n  return (\n    point.x >= box.left && point.x <= box.right && point.y >= box.top && point.y <= box.bottom\n  );\n}\n\nexport function inPolygon(point: Point, polygon: Point[]) {\n  let inside = false;\n  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n    const a = polygon[i];\n    const b = polygon[j];\n    if (\n      a.y > point.y !== b.y > point.y &&\n      point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x\n    ) {\n      inside = !inside;\n    }\n  }\n  return inside;\n}\n\n// Monotone chain; the corridor is always convex, so a hull is all it needs.\nfunction hull(points: Point[]) {\n  const sorted = [...points].sort((a, b) => a.x - b.x || a.y - b.y);\n  const cross = (o: Point, a: Point, b: Point) =>\n    (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n  const lower: Point[] = [];\n  for (const p of sorted) {\n    while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {\n      lower.pop();\n    }\n    lower.push(p);\n  }\n  const upper: Point[] = [];\n  for (let i = sorted.length - 1; i >= 0; i--) {\n    const p = sorted[i];\n    while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {\n      upper.pop();\n    }\n    upper.push(p);\n  }\n  lower.pop();\n  upper.pop();\n  return lower.concat(upper);\n}\n\n/**\n * How the user last reached for the page. A focus that a mouse press caused is\n * not a request to read the label: the pointer is already on the control and\n * hovering showed it. A focus that followed a key - Tab, or a roving arrow key\n * moving focus in script - is the only way a keyboard user sees it at all.\n */\nlet modality: \"keyboard\" | \"pointer\" = \"keyboard\";\nlet listening = false;\n\nexport function watchModality() {\n  if (listening || typeof window === \"undefined\") return;\n  listening = true;\n  window.addEventListener(\"keydown\", () => (modality = \"keyboard\"), true);\n  window.addEventListener(\"pointerdown\", () => (modality = \"pointer\"), true);\n}\n\nexport function focusFromKeyboard() {\n  return modality === \"keyboard\";\n}\n"},{"path":"components/motion/tooltip/positioner.tsx","type":"util","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport { type CSSProperties, type ReactNode, type Ref, useCallback, useState } from \"react\";\nimport { type TooltipSide, useTooltipPosition } from \"./use-position\";\n\ntype PositionProps = Parameters<typeof useTooltipPosition>[0];\n\n/** Readiness lives with the mounted overlay, not a trigger ref's attach/detach cycle. */\nexport function TooltipPositioner({\n  children,\n  ...position\n}: Omit<PositionProps, \"open\" | \"onPosition\"> & {\n  children: (ready: boolean, present: boolean, side: TooltipSide) => ReactNode;\n}) {\n  const present = useIsPresent();\n  const [ready, setReady] = useState(false);\n  const [side, setSide] = useState<TooltipSide>(position.side);\n  const onPosition = useCallback((placed: TooltipSide) => {\n    setReady(true);\n    setSide(placed);\n  }, []);\n  useTooltipPosition({ ...position, open: present, onPosition });\n  return (\n    <span\n      ref={position.floatingRef}\n      inert={!present}\n      aria-hidden={!present || undefined}\n      className=\"pointer-events-none fixed left-0 top-0 z-[9999] w-max\"\n      style={{ visibility: \"hidden\", maxWidth: \"calc(100vw - 16px)\" }}\n    >\n      {children(ready, present, side)}\n    </span>\n  );\n}\n\n// Each arrow is a 12px box whose base sits on the surface's inner border edge,\n// so its fill covers the border beneath it and only the two outer edges stroke.\nconst ARROW: Record<TooltipSide, { path: string; style: CSSProperties }> = {\n  top: { path: \"M0 6L6 12L12 6\", style: { top: \"calc(100% - 6px)\" } },\n  bottom: { path: \"M0 6L6 0L12 6\", style: { bottom: \"calc(100% - 6px)\" } },\n  left: { path: \"M6 0L12 6L6 12\", style: { left: \"calc(100% - 6px)\" } },\n  right: { path: \"M6 0L0 6L6 12\", style: { right: \"calc(100% - 6px)\" } },\n};\n\nexport function TooltipArrow({ side, ref }: { side: TooltipSide; ref: Ref<SVGSVGElement> }) {\n  const { path, style } = ARROW[side];\n  return (\n    <svg\n      ref={ref}\n      aria-hidden=\"true\"\n      width=\"12\"\n      height=\"12\"\n      viewBox=\"0 0 12 12\"\n      className=\"pointer-events-none absolute overflow-visible\"\n      style={style}\n    >\n      {/* Redrawn to fit the surface's edge once placed (see arrowShape). */}\n      <path data-arrow-fill=\"\" d={`${path}Z`} style={{ fill: \"var(--tooltip-arrow-fill, transparent)\" }} />\n      <path\n        data-arrow-stroke=\"\"\n        d={path}\n        fill=\"none\"\n        strokeWidth=\"1\"\n        style={{ stroke: \"var(--tooltip-arrow-stroke, transparent)\" }}\n      />\n    </svg>\n  );\n}\n"},{"path":"components/motion/tooltip/use-position.ts","type":"util","content":"\"use client\";\n\nimport {\n  arrow as arrowMiddleware,\n  autoUpdate,\n  computePosition,\n  flip,\n  hide,\n  offset,\n  type Placement,\n  shift,\n  type VirtualElement,\n} from \"@floating-ui/dom\";\nimport { type RefObject, useCallback, useLayoutEffect, useMemo, useRef } from \"react\";\n\nexport type TooltipSide = \"top\" | \"right\" | \"bottom\" | \"left\";\nexport type TooltipAlign = \"start\" | \"center\" | \"end\";\nexport type TooltipPoint = {\n  /** Horizontal position; for `anchorPoint`, a 0 to 1 fraction of the anchor's width. */\n  x: number;\n  /** Vertical position; for `anchorPoint`, a 0 to 1 fraction of the anchor's height. */\n  y: number;\n};\nexport type TooltipAnchor = HTMLElement | SVGElement;\n\nconst ORIGIN: Record<TooltipSide, string> = {\n  top: \"center bottom\",\n  bottom: \"center top\",\n  left: \"right center\",\n  right: \"left center\",\n};\n\n/** `top` painted over `bottom`, as one opaque colour. Falls back to `top`. */\nfunction blend(top: string, bottom: string) {\n  const context = document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  if (!context) return top;\n  context.fillStyle = bottom;\n  context.fillRect(0, 0, 1, 1);\n  context.fillStyle = top;\n  context.fillRect(0, 0, 1, 1);\n  const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data;\n  // A see-through background has nothing solid to blend onto.\n  return a === 255 ? `rgb(${r}, ${g}, ${b})` : top;\n}\n\n/** The arrow element's box, which the arrow middleware centres along the edge. */\nconst ARROW_SIZE = 12;\n/** How far the tip reaches past the border's inner edge. */\nconst ARROW_REACH = 6;\n\n/**\n * How far a rounded edge has curved in from its straight line at `position`\n * along an edge of `length`, with corners of `radius`. Zero on the straight\n * stretch between the corners.\n */\nfunction curveDepth(position: number, length: number, radius: number) {\n  const offset =\n    position < radius ? radius - position : position > length - radius ? position - (length - radius) : 0;\n  if (offset <= 0) return 0;\n  return radius - Math.sqrt(Math.max(radius * radius - offset * offset, 0));\n}\n\n/**\n * The arrow's two paths, in the surface's border-box coordinates. Each 45°\n * side runs from the tip until it meets the middle of the surface's border,\n * wherever that is: on a straight stretch, or partway round a pill's curved\n * end. The stroke covers only those two sides, so the border flows straight\n * into them. The fill closes a little inside the surface, hiding the stretch\n * of border the arrow sits on.\n */\nfunction arrowShape({\n  side,\n  center,\n  width,\n  height,\n  radius,\n  border,\n}: {\n  side: TooltipSide;\n  center: number;\n  width: number;\n  height: number;\n  radius: number;\n  border: number;\n}) {\n  const vertical = side === \"top\" || side === \"bottom\";\n  const length = vertical ? width : height;\n  // Work on one edge: `depth` runs inward from the edge's outer line, `along` runs down it.\n  const tip = { depth: border - ARROW_REACH, along: center };\n  // The border's centre line: the stroke meets it there, so the two line up.\n  const line = border / 2;\n  // Both sides follow the same rule, so an arrow a pixel off-centre stays symmetric.\n  const curved =\n    curveDepth(center - ARROW_SIZE / 2, length, radius) > 0 ||\n    curveDepth(center + ARROW_SIZE / 2, length, radius) > 0;\n  const meet = (direction: -1 | 1) => {\n    // On a straight stretch the 45° side meets the border directly.\n    if (!curved) {\n      for (let t = 0; t <= ARROW_SIZE; t += 0.05) {\n        const along = center + direction * t;\n        const depth = tip.depth + t;\n        if (depth >= line) return { depth, along };\n      }\n    }\n    // On a pill's round end a 45° side passes outside the curve, or meets it\n    // at a kink. Run the side tangent to the curve instead, so the border\n    // flows into it without a corner.\n    const curve = radius - line;\n    const centre = { depth: radius, along: direction < 0 ? radius : length - radius };\n    const dx = tip.depth - centre.depth;\n    const dy = tip.along - centre.along;\n    const distance = Math.hypot(dx, dy);\n    if (distance <= curve) return { depth: line, along: center + direction * ARROW_REACH };\n    const base = Math.atan2(dy, dx);\n    const spread = Math.acos(curve / distance);\n    const candidates = [base + spread, base - spread].map((angle) => ({\n      depth: centre.depth + curve * Math.cos(angle),\n      along: centre.along + curve * Math.sin(angle),\n    }));\n    // The tangent on this side of the tip.\n    return direction < 0\n      ? candidates[0].along < candidates[1].along\n        ? candidates[0]\n        : candidates[1]\n      : candidates[0].along > candidates[1].along\n        ? candidates[0]\n        : candidates[1];\n  };\n  const start = meet(-1);\n  const end = meet(1);\n  const inside = Math.max(start.depth, end.depth) + border + 1;\n  const point = ({ depth, along }: { depth: number; along: number }) => {\n    const [x, y] =\n      side === \"right\"\n        ? [depth, along]\n        : side === \"left\"\n          ? [width - depth, along]\n          : side === \"bottom\"\n            ? [along, depth]\n            : [along, height - depth];\n    return `${x.toFixed(2)} ${y.toFixed(2)}`;\n  };\n  return {\n    fill: `M${point(tip)}L${point(start)}L${point({ depth: inside, along: start.along })}L${point({ depth: inside, along: end.along })}L${point(end)}Z`,\n    stroke: `M${point(start)}L${point(tip)}L${point(end)}`,\n  };\n}\n\n/** Position is geometry, not animation. One write per frame, never a spring chasing a pointer. */\nexport function useTooltipPosition({\n  open,\n  anchor,\n  floatingRef,\n  arrowRef,\n  anchorPoint,\n  followCursor,\n  side,\n  align,\n  sideOffset,\n  onDismiss,\n  onPosition,\n  pointer,\n}: {\n  open: boolean;\n  anchor: TooltipAnchor | null;\n  floatingRef: RefObject<HTMLSpanElement | null>;\n  arrowRef?: RefObject<SVGSVGElement | null>;\n  anchorPoint?: TooltipPoint;\n  followCursor: boolean;\n  side: TooltipSide;\n  align: TooltipAlign;\n  sideOffset?: number;\n  onDismiss: () => void;\n  onPosition: (side: TooltipSide) => void;\n  pointer: ReturnType<typeof useTooltipPointer>;\n}) {\n  const { cursor, onMove } = pointer;\n  const preferred: Placement = align === \"center\" ? side : `${side}-${align}`;\n  const cursorSide = useRef<Placement | null>(null);\n  useLayoutEffect(() => {\n    cursorSide.current = open ? preferred : null;\n  }, [open, preferred]);\n  const frame = useRef<number | null>(null);\n  const version = useRef(0);\n  const update = useRef<() => void>(() => {});\n  const schedule = useCallback(() => {\n    // Invalidate older async calculations as soon as new geometry is requested.\n    version.current++;\n    if (frame.current !== null) return;\n    frame.current = requestAnimationFrame(() => {\n      frame.current = null;\n      update.current();\n    });\n  }, []);\n  useLayoutEffect(() => {\n    onMove.current = schedule;\n    return () => {\n      onMove.current = null;\n    };\n  }, [onMove, schedule]);\n  const pointX = anchorPoint?.x;\n  const pointY = anchorPoint?.y;\n\n  // Latest committed inputs are read without recreating observers for every period/content update.\n  useLayoutEffect(() => {\n    update.current = () => {\n      const floating = floatingRef.current;\n      if (!open || !anchor || !floating) return;\n      const revision = ++version.current;\n      const currentCursor = followCursor ? cursor.current : null;\n      const virtual = Boolean(currentCursor) || pointX !== undefined || pointY !== undefined;\n      const reference: Element | VirtualElement = virtual\n        ? {\n            contextElement: anchor,\n            getBoundingClientRect: () => {\n              const rect = anchor.getBoundingClientRect();\n              const x = currentCursor?.x ?? rect.left + rect.width * (pointX ?? 0.5);\n              const y = currentCursor?.y ?? rect.top + rect.height * (pointY ?? 0.5);\n              return { x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 };\n            },\n          }\n        : anchor;\n      const arrowElement = arrowRef?.current ?? null;\n      void computePosition(reference, floating, {\n        strategy: \"fixed\",\n        placement: currentCursor ? (cursorSide.current ?? preferred) : preferred,\n        middleware: [\n          offset(sideOffset ?? (currentCursor ? 12 : 8)),\n          flip({ padding: 8 }),\n          shift({ padding: 8 }),\n          ...(arrowElement ? [arrowMiddleware({ element: arrowElement, padding: 10 })] : []),\n          // A label left floating over whatever scrolled into its trigger's place\n          // describes nothing there. Points inside a chart move with the chart.\n          ...(virtual ? [] : [hide({ strategy: \"referenceHidden\" })]),\n        ],\n      }).then(({ x, y, placement, middlewareData }) => {\n        if (version.current !== revision || !floating.isConnected) return;\n        // Hold the chosen side for this hover session. Crossing a flip threshold\n        // repeatedly must not bounce the surface above and below the pointer.\n        if (currentCursor) cursorSide.current = placement;\n        else cursorSide.current = null;\n        const placedSide = placement.split(\"-\")[0] as TooltipSide;\n        const dpr = window.devicePixelRatio || 1;\n        floating.style.transform = `translate3d(${Math.round(x * dpr) / dpr}px, ${Math.round(y * dpr) / dpr}px, 0)`;\n        floating.style.setProperty(\"--tooltip-origin\", ORIGIN[placedSide]);\n        // A box with no size has no clipped state to report, only a missing layout.\n        const box = anchor.getBoundingClientRect();\n        const clipped =\n          Boolean(middlewareData.hide?.referenceHidden) && (box.width > 0 || box.height > 0);\n        floating.style.visibility = clipped ? \"hidden\" : \"visible\";\n        floating.dataset.placement = placement;\n        const surface = arrowElement?.parentElement;\n        if (arrowElement && surface) {\n          // The middleware centres the 12px arrow box along the edge; its\n          // centre is where the tip points. The paths are drawn in the\n          // surface's border-box coordinates, so the svg sits at its corner.\n          const { x: ax, y: ay } = middlewareData.arrow ?? {};\n          const vertical = placedSide === \"top\" || placedSide === \"bottom\";\n          const width = surface.offsetWidth;\n          const height = surface.offsetHeight;\n          const along = (vertical ? ax : ay) ?? ((vertical ? width : height) - ARROW_SIZE) / 2;\n          const style = getComputedStyle(surface);\n          const shape = arrowShape({\n            side: placedSide,\n            center: along + ARROW_SIZE / 2,\n            width,\n            height,\n            // `rounded-full` resolves to a huge radius; the box clamps it to half its short side.\n            radius: Math.min(Number.parseFloat(style.borderTopLeftRadius) || 0, width / 2, height / 2),\n            border: surface.clientLeft,\n          });\n          Object.assign(arrowElement.style, {\n            left: `${-surface.clientLeft}px`,\n            top: `${-surface.clientTop}px`,\n            right: \"auto\",\n            bottom: \"auto\",\n          });\n          arrowElement.querySelector(\"[data-arrow-fill]\")?.setAttribute(\"d\", shape.fill);\n          arrowElement.querySelector(\"[data-arrow-stroke]\")?.setAttribute(\"d\", shape.stroke);\n          // Paint with whatever the surface resolved to, so a restyled tooltip\n          // keeps a matching arrow without a second set of classes. A\n          // see-through border is drawn over the surface's own background, so\n          // the stroke takes that blended colour: half of it sits over the\n          // page, and it overlaps the border where the two meet.\n          arrowElement.style.setProperty(\"--tooltip-arrow-fill\", style.backgroundColor);\n          arrowElement.style.setProperty(\n            \"--tooltip-arrow-stroke\",\n            blend(style.borderTopColor, style.backgroundColor),\n          );\n        }\n        onPosition(placedSide);\n      });\n    };\n    if (open) schedule();\n  }, [\n    open,\n    anchor,\n    floatingRef,\n    arrowRef,\n    followCursor,\n    pointX,\n    pointY,\n    preferred,\n    sideOffset,\n    schedule,\n    onPosition,\n    cursor,\n  ]);\n\n  useLayoutEffect(() => {\n    const floating = floatingRef.current;\n    if (!open || !anchor || !floating) return;\n    const stop = autoUpdate(anchor, floating, schedule);\n    const onScroll = () => {\n      // A stationary pointer no longer describes the same chart point after scrolling.\n      if (followCursor && cursor.current) onDismiss();\n    };\n    window.addEventListener(\"scroll\", onScroll, true);\n    return () => {\n      stop();\n      window.removeEventListener(\"scroll\", onScroll, true);\n      version.current++;\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n      frame.current = null;\n    };\n  }, [open, anchor, floatingRef, followCursor, onDismiss, schedule, cursor]);\n\n  useLayoutEffect(\n    () => () => {\n      version.current++;\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n    },\n    [],\n  );\n}\n\n/** Pointer lifetime belongs to the anchor, including the opening delay. */\nexport function useTooltipPointer(anchor: TooltipAnchor | null, followCursor: boolean) {\n  const cursor = useRef<TooltipPoint | null>(null);\n  const onMove = useRef<(() => void) | null>(null);\n  const pointerFocus = useRef(false);\n  useLayoutEffect(() => {\n    if (!anchor || !followCursor) return;\n    const point = (event: PointerEvent) => {\n      if (event.type === \"pointermove\" && event.pointerType === \"touch\" && !event.buttons) return;\n      cursor.current = { x: event.clientX, y: event.clientY };\n      if (event.type === \"pointerdown\") pointerFocus.current = true;\n      onMove.current?.();\n    };\n    const keyboard = () => {\n      cursor.current = null;\n      pointerFocus.current = false;\n      onMove.current?.();\n    };\n    const focus = () => {\n      if (!pointerFocus.current) cursor.current = null;\n      pointerFocus.current = false;\n      onMove.current?.();\n    };\n    const leave = () => {\n      cursor.current = null;\n    };\n    anchor.addEventListener(\"pointerenter\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointermove\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointerdown\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointerleave\", leave);\n    anchor.addEventListener(\"pointercancel\", leave);\n    anchor.addEventListener(\"keydown\", keyboard);\n    anchor.addEventListener(\"focusin\", focus);\n    return () => {\n      cursor.current = null;\n      anchor.removeEventListener(\"pointerenter\", point as EventListener);\n      anchor.removeEventListener(\"pointermove\", point as EventListener);\n      anchor.removeEventListener(\"pointerdown\", point as EventListener);\n      anchor.removeEventListener(\"pointerleave\", leave);\n      anchor.removeEventListener(\"pointercancel\", leave);\n      anchor.removeEventListener(\"keydown\", keyboard);\n      anchor.removeEventListener(\"focusin\", focus);\n    };\n  }, [anchor, followCursor]);\n\n  return useMemo(() => ({ cursor, onMove }), []);\n}\n"},{"path":"components/motion/tooltip-surface.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion, type Variants } from \"motion/react\";\nimport type { ComponentProps, ReactNode, Ref } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nconst ENTER = { duration: 0.18, ease: EASE_OUT };\nconst EXIT = { duration: 0.12, ease: EASE_OUT };\nconst INSTANT = { duration: 0 };\n\n/**\n * `custom` is the `instant` flag. An exiting surface reads it from its\n * `AnimatePresence`, so a tooltip replaced by a neighbour vanishes at once\n * even though it has already left the React tree.\n */\nconst variants = (reduce: boolean): Variants => ({\n  closed: (instant = false) => ({\n    opacity: 0,\n    scale: reduce ? 1 : 0.97,\n    transition: instant ? INSTANT : EXIT,\n  }),\n  open: (instant = false) => ({\n    opacity: 1,\n    scale: 1,\n    transition: instant ? INSTANT : ENTER,\n  }),\n});\n\n/** Presentation only: the unanimated parent owns measurement and positioning. */\nexport function TooltipSurface({\n  children,\n  className,\n  ref,\n  ready = true,\n  instant = false,\n  style,\n  ...props\n}: Omit<ComponentProps<typeof motion.span>, \"children\"> & {\n  children?: ReactNode;\n  /** Start the entrance only after the positioning layer has been measured. */\n  ready?: boolean;\n  /**\n   * Appear and disappear without animating: a label opened from the keyboard,\n   * or one of a row of tooltips the pointer is moving along.\n   */\n  instant?: boolean;\n  ref?: Ref<HTMLSpanElement>;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  return (\n    <motion.span\n      ref={ref}\n      role=\"tooltip\"\n      custom={instant}\n      variants={variants(reduce)}\n      initial=\"closed\"\n      animate={ready ? \"open\" : \"closed\"}\n      exit=\"closed\"\n      style={{ transformOrigin: \"var(--tooltip-origin, center)\", ...style }}\n      className={cn(\n        \"block whitespace-nowrap rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)]\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </motion.span>\n  );\n}\n"},{"path":"lib/hooks/use-dismiss.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport {\n  inLayerAbove,\n  inOtherLayer,\n  type Layer,\n  openLayer,\n  ownsEscape,\n} from \"@/lib/layers\";\n\n/**\n * What the dismissing gesture does to the control it landed on.\n *\n * `\"pass-through\"` is the platform norm (native popover light-dismiss): the\n * tap closes the overlay *and* activates whatever was under it. Use\n * `\"consume\"` where the open overlay sits over or beside controls that would\n * be costly to trigger by accident - the dismissal then swallows the\n * activation too, so the gesture only closes.\n */\nexport type DismissBehavior = \"pass-through\" | \"consume\";\n\n/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */\nexport type DismissReason = \"escape\" | \"pointer\" | \"focus\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */\n  focusOutside?: boolean;\n  /**\n   * Dismiss on a pointerdown outside. Default true. Turn it off for an overlay\n   * whose own backdrop handles presses and only needs Escape and layering.\n   */\n  outsidePress?: boolean;\n  /** Return true for an outside target that should *not* dismiss. */\n  ignore?: (target: Element) => boolean;\n}\n\n// preventDefault on pointerdown does not suppress the click that follows, so\n// consuming a gesture means swallowing that click itself. The swallower\n// deliberately outlives the effect that installed it - the dismissal it\n// belongs to has already unmounted or re-rendered by the time the click lands.\n// It releases on that click, or on the next gesture if the pointer is dragged\n// away and no click ever arrives, so it can never eat a later one. A keydown\n// releases it too: a gesture that ends with neither a click nor a cancel would\n// otherwise leave it armed, and the click Enter synthesizes on some focused\n// control is not the one this dismissal was owed.\nfunction consumeActivation(source: Event) {\n  const swallow = (event: MouseEvent) => {\n    event.preventDefault();\n    event.stopPropagation();\n    release();\n  };\n  const restart = (event: Event) => {\n    if (event !== source) release();\n  };\n  const release = () => {\n    window.removeEventListener(\"click\", swallow, true);\n    window.removeEventListener(\"pointerdown\", restart, true);\n    window.removeEventListener(\"pointercancel\", restart, true);\n    window.removeEventListener(\"keydown\", release, true);\n  };\n  window.addEventListener(\"click\", swallow, true);\n  window.addEventListener(\"pointerdown\", restart, true);\n  window.addEventListener(\"pointercancel\", restart, true);\n  window.addEventListener(\"keydown\", release, true);\n}\n\n/**\n * Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`\n * for `ref` when what counts as inside isn't one element, and say so with\n * `ignore` instead.\n *\n * The pointerdown listener is capture-phase: a bubble-phase one is blinded by\n * any handler in between that stops propagation, and an overlay cannot know\n * what it is layered over.\n *\n * Each open dismissal is a layer in `lib/layers.ts`, so only the innermost\n * open overlay answers Escape (a menu inside a drawer closes, the drawer\n * stays), and a drawer's focus trap leaves focus in a menu it portaled out.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: (reason: DismissReason) => void,\n  ref: RefObject<HTMLElement | SVGElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    focusOutside = false,\n    outsidePress = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  // Read through refs, so a callback rebuilt each render neither re-binds the\n  // listeners nor moves this layer to the top of the stack.\n  const dismissRef = useRef(onDismiss);\n  const ignoreRef = useRef(ignore);\n  useLayoutEffect(() => {\n    dismissRef.current = onDismiss;\n    ignoreRef.current = ignore;\n  });\n\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Node) =>\n      Boolean(ref?.current?.contains(target)) ||\n      (target instanceof Element && Boolean(ignoreRef.current?.(target)));\n    const layer: Layer = { contains: inside, escape: dismissOnEscape };\n    const closeLayer = openLayer(layer);\n    const onKey = (event: KeyboardEvent) => {\n      if (!dismissOnEscape || event.key !== \"Escape\" || !ownsEscape(layer, event)) return;\n      event.preventDefault();\n      dismissRef.current(\"escape\");\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // A press in an overlay opened on top of this one (a tooltip or menu\n      // portaled to the body) belongs to that overlay, not outside this one.\n      if (inLayerAbove(layer, target)) return;\n      // Outside this overlay, but inside another open one: the gesture is\n      // that overlay's to answer, and swallowing its click from behind would\n      // cost the user the control they actually aimed at.\n      if (behavior === \"consume\" && !inOtherLayer(layer, target, { traps: false })) {\n        consumeActivation(event);\n      }\n      dismissRef.current(\"pointer\");\n    };\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (target instanceof Node && !inside(target)) dismissRef.current(\"focus\");\n    };\n    window.addEventListener(\"keydown\", onKey);\n    if (outsidePress) window.addEventListener(\"pointerdown\", onPointer, true);\n    if (focusOutside) window.addEventListener(\"focusin\", onFocus);\n    return () => {\n      closeLayer();\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n      window.removeEventListener(\"focusin\", onFocus);\n    };\n  }, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);\n}\n"},{"path":"lib/hooks/use-hover-gesture.ts","type":"util","content":"\"use client\";\n\nimport { useMemo, useRef } from \"react\";\nimport { isHoveringPointer } from \"@/lib/touch\";\n\ninterface BoundaryEvent {\n  pointerId: number;\n  pointerType: string;\n  buttons: number;\n}\n\nexport interface HoverGesture {\n  /** True when this enter starts a hover: the pointer arrived resting, not pressing. */\n  enter: (event: BoundaryEvent) => boolean;\n  /** True when this leave ends a hover that entered as one. */\n  leave: (event: BoundaryEvent) => boolean;\n}\n\n/**\n * Pairs a surface's enter with its leave, per pointer.\n *\n * `isHoveringPointer` answers the question the *enter* asks - is this pointer\n * resting on the surface or pressing it - and both boundary cases go wrong if\n * the leave is asked the same question again:\n *\n * - A pen with no hover never rests. It arrives in contact, taps, and the spec\n *   then requires its boundary events after `pointerup`, so the leave carries\n *   `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid\n *   the tap - the panel the pen had just opened closed under it.\n * - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.\n *   Skipping teardown there strands the surface open: the release happens\n *   outside, and no second leave ever comes.\n *\n * So the state a hover holds is released by the pointer that took it, whatever\n * the buttons say at the boundary, and a pointer that arrived in contact never\n * took it in the first place. Contact is the exception tracked here, not\n * hover: a leave from a pointer this surface never saw enter - mounted under\n * the cursor, say - still counts, since the alternative is state with no way\n * out.\n */\nexport function useHoverGesture(): HoverGesture {\n  const contact = useRef(new Set<number>());\n\n  return useMemo(\n    () => ({\n      enter: (event) => {\n        if (isHoveringPointer(event)) {\n          contact.current.delete(event.pointerId);\n          return true;\n        }\n        contact.current.add(event.pointerId);\n        return false;\n      },\n      leave: (event) => {\n        const arrivedInContact = contact.current.delete(event.pointerId);\n        return !arrivedInContact && event.pointerType !== \"touch\";\n      },\n    }),\n    [],\n  );\n}\n"},{"path":"lib/hooks/use-tap-gesture.ts","type":"util","content":"\"use client\";\n\nimport { useMemo, useRef } from \"react\";\n\n/** What a pointerdown recorded, read back by the click that ends its gesture. */\nexport interface TapRecord<S> {\n  /** Which input started the gesture. */\n  pointerType: string;\n  /** What the surface was showing when it started. */\n  state: S;\n}\n\nexport interface TapGesture<S> {\n  /** Record the gesture a pointerdown starts, with the state it starts in. */\n  start: (event: { pointerType: string }, state: S) => void;\n  /** Read the record and clear it. `null` when no pointer is behind this click. */\n  take: () => TapRecord<S> | null;\n  /** Drop the record: this gesture will never spend it on a click. */\n  drop: () => void;\n}\n\n/**\n * The pointer gesture behind a click, recorded where the click cannot report\n * it. A `click` carries no `pointerType` in the engines that matter, so the\n * `pointerdown` before it is the only thing that says which input activated\n * the control - and whether one did at all, since keyboard activation\n * synthesizes a click with no pointer behind it.\n *\n * State goes in with the record because a click reports that no better: a\n * browser that focuses a control on contact can open the very panel the tap\n * was meant to open, and reading \"is it open\" at click time then undoes it.\n * What the gesture started against is what it acts on.\n *\n * The record is spent by one click and dropped by everything else, because a\n * record that outlives its gesture is worse than none:\n *\n * - A scroll or an OS gesture takes the touch away - `pointercancel`, no click\n *   ever - and the finger would sit in the record until some later click.\n * - That later click is often `Enter` on a keyboard, which arrives with no\n *   pointerdown of its own and would inherit the abandoned finger. A keydown\n *   is the start of a keyboard activation and never part of a tap, so it drops\n *   the record too.\n *\n * Both ends have to be wired by the surface: `drop` on `onPointerCancel` and\n * on `onKeyDown`.\n */\nexport function useTapGesture<S>(): TapGesture<S> {\n  const record = useRef<TapRecord<S> | null>(null);\n\n  return useMemo(\n    () => ({\n      start: (event, state) => {\n        record.current = { pointerType: event.pointerType, state };\n      },\n      take: () => {\n        const spent = record.current;\n        record.current = null;\n        return spent;\n      },\n      drop: () => {\n        record.current = null;\n      },\n    }),\n    [],\n  );\n}\n"},{"path":"lib/text-shimmer.ts","type":"util","content":"import type { CSSProperties } from \"react\";\n\n// The reduced-motion rule travels with the component. The site's globals.css calms CSS\n// animation globally, but the registry bundles imports only, so an installed\n// copy never receives that reset.\n//\n// `!important` because the sweep is an inline style, which outranks a plain rule\n// in a media query. It selects a marker class carried by TEXT_SHIMMER_CLASS_NAME\n// so it also reaches consumers that build their own span out of these exports.\nexport const TEXT_SHIMMER_KEYFRAMES =\n  \"@keyframes beui-text-shimmer{from{background-position:200% 0}to{background-position:-200% 0}}\" +\n  \"@media (prefers-reduced-motion: reduce){.beui-text-shimmer{animation:none !important}}\";\n\nexport const TEXT_SHIMMER_CLASS_NAME =\n  \"beui-text-shimmer bg-[length:200%_100%] bg-clip-text text-transparent bg-[linear-gradient(110deg,var(--muted-foreground)_30%,var(--foreground)_50%,var(--muted-foreground)_70%)]\";\n\n/**\n * Only the moving highlight band, transparent elsewhere. Laid over text drawn\n * in pieces (a letter cascade), so one band sweeps the whole phrase instead\n * of every piece carrying, and flashing, its own gradient.\n */\nexport const TEXT_SHIMMER_HIGHLIGHT_CLASS_NAME =\n  \"beui-text-shimmer bg-[length:200%_100%] bg-clip-text text-transparent bg-[linear-gradient(110deg,transparent_30%,var(--foreground)_50%,transparent_70%)]\";\n\nexport function textShimmerStyle(duration: number): CSSProperties {\n  return {\n    animation: `beui-text-shimmer ${duration}s linear infinite`,\n  };\n}\n"},{"path":"components/motion/dropdown-menu/context.ts","type":"util","content":"\"use client\";\n\nimport { createContext, type MutableRefObject, useContext } from \"react\";\nimport type { Point } from \"./placement\";\n\nexport type FocusTarget = \"first\" | \"last\" | \"panel\" | \"none\";\n\nexport interface RootContextValue {\n  open: boolean;\n  /**\n   * `instant` skips the open or close animation: the keyboard asked for it,\n   * and keyboard users open and close menus far too often to wait on motion.\n   */\n  setOpen: (open: boolean, focus?: FocusTarget, instant?: boolean) => void;\n  focusTarget: FocusTarget;\n  /** Whether the latest open or close skips its animation. */\n  instant: boolean;\n  menuId: string;\n  triggerId: string;\n  triggerRef: MutableRefObject<HTMLElement | null>;\n  reduce: boolean;\n  mounted: boolean;\n  /** Plays the select sound when the menu's `sound` prop is on. */\n  playSelect: () => void;\n}\n\nexport const RootContext = createContext<RootContextValue | null>(null);\n\nexport function useRoot(component: string) {\n  const context = useContext(RootContext);\n  if (!context) throw new Error(`${component} must be used within <DropdownMenu>`);\n  return context;\n}\n\n/** One open panel: the root menu or a submenu. */\nexport interface LevelContextValue {\n  levelId: string;\n  present: boolean;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n  activeId: string | null;\n  setActiveId: (id: string | null) => void;\n  /** The highlight glides after the pointer, and jumps after a key. */\n  glide: boolean;\n  openSub: string | null;\n  /** `instant` defaults to true when a focus target says the keyboard opened it. */\n  setOpenSub: (id: string | null, focus?: FocusTarget, instant?: boolean) => void;\n  subFocus: FocusTarget;\n  /** Whether the submenu's latest open or close skips its animation. */\n  subInstant: boolean;\n  /** A pointer on its way from a submenu trigger to the submenu it opened. */\n  grace: MutableRefObject<{ polygon: Point[]; until: number } | null>;\n}\n\nexport const LevelContext = createContext<LevelContextValue | null>(null);\n\nexport function useLevel(component: string) {\n  const context = useContext(LevelContext);\n  if (!context) {\n    throw new Error(`${component} must be used within <DropdownMenuContent>`);\n  }\n  return context;\n}\n"},{"path":"components/motion/dropdown-menu/item-base.tsx","type":"util","content":"\"use client\";\n\nimport { type MutableRefObject, type KeyboardEvent as ReactKeyboardEvent, type ReactNode, useId } from \"react\";\nimport { MENU_ITEM_CLASS, MenuItemHighlight } from \"@/components/motion/menu/menu-item-highlight\";\nimport { cn } from \"@/lib/utils\";\nimport { useLevel, useRoot } from \"./context\";\nimport { insidePolygon } from \"./placement\";\n\ntype ItemTone = \"default\" | \"destructive\";\n\nexport interface DropdownMenuItemProps {\n  children: ReactNode;\n  /** Called when the item is chosen by click, Enter or Space. */\n  onSelect?: () => void;\n  /** Dims the item and blocks selecting it. Default: false */\n  disabled?: boolean;\n  /** Close the whole menu after selecting. Default true. */\n  closeOnSelect?: boolean;\n  /** \"destructive\" tints the row for dangerous actions. Default: \"default\" */\n  tone?: ItemTone;\n  /** Indent to line up with rows that start with an icon. */\n  inset?: boolean;\n  /** Text matched by typeahead when the label is not plain text. */\n  textValue?: string;\n  /** Classes merged onto the item row. */\n  className?: string;\n}\n\ninterface ItemBaseProps extends DropdownMenuItemProps {\n  role?: \"menuitem\" | \"menuitemcheckbox\" | \"menuitemradio\";\n  checked?: boolean;\n  subTrigger?: {\n    id: string;\n    open: boolean;\n    controls: string;\n    onPointerMove: (event: React.PointerEvent<HTMLButtonElement>) => void;\n    onPointerLeave: (event: React.PointerEvent<HTMLButtonElement>) => void;\n    onKeyDown: (event: ReactKeyboardEvent<HTMLButtonElement>) => void;\n    onClick: () => void;\n    ref: MutableRefObject<HTMLElement | null>;\n  };\n}\n\n/** The row every item kind renders: plain, checkbox, radio and submenu trigger. */\nexport function ItemBase({\n  children,\n  onSelect,\n  disabled = false,\n  closeOnSelect = true,\n  tone = \"default\",\n  inset = false,\n  textValue,\n  className,\n  role = \"menuitem\",\n  checked,\n  subTrigger,\n}: ItemBaseProps) {\n  const root = useRoot(\"DropdownMenuItem\");\n  const level = useLevel(\"DropdownMenuItem\");\n  const ownId = useId();\n  const id = subTrigger?.id ?? ownId;\n  const active = level.activeId === id;\n\n  return (\n    <button\n      type=\"button\"\n      ref={(node) => {\n        if (subTrigger) subTrigger.ref.current = node;\n      }}\n      id={id}\n      role={role}\n      {...(role === \"menuitem\" ? {} : { \"aria-checked\": checked })}\n      aria-haspopup={subTrigger ? \"menu\" : undefined}\n      aria-expanded={subTrigger ? subTrigger.open : undefined}\n      aria-controls={subTrigger?.open ? subTrigger.controls : undefined}\n      aria-disabled={disabled || undefined}\n      tabIndex={-1}\n      data-menu-item=\"\"\n      data-level={level.levelId}\n      data-disabled={disabled ? \"\" : undefined}\n      data-highlighted={active ? \"\" : undefined}\n      data-text-value={textValue}\n      onFocus={() => {\n        level.setActiveId(id);\n        // Moving to another row of this menu closes a submenu it does not own.\n        if (level.openSub && level.openSub !== subTrigger?.id) level.setOpenSub(null);\n      }}\n      onPointerMove={(event) => {\n        if (event.pointerType === \"touch\") return;\n        // On the way to an open submenu, crossing this row changes nothing.\n        const grace = level.grace.current;\n        if (grace && Date.now() < grace.until && insidePolygon({ x: event.clientX, y: event.clientY }, grace.polygon)) {\n          return;\n        }\n        level.grace.current = null;\n        if (subTrigger) {\n          subTrigger.onPointerMove(event);\n          return;\n        }\n        if (level.openSub) level.setOpenSub(null);\n        if (disabled) {\n          if (level.panelRef.current?.contains(document.activeElement)) {\n            level.panelRef.current.focus({ preventScroll: true });\n          }\n          return;\n        }\n        if (document.activeElement !== event.currentTarget) {\n          event.currentTarget.focus({ preventScroll: true });\n        }\n      }}\n      onPointerLeave={subTrigger?.onPointerLeave}\n      onKeyDown={subTrigger?.onKeyDown}\n      onClick={(event) => {\n        if (disabled) return;\n        if (subTrigger) {\n          subTrigger.onClick();\n          return;\n        }\n        onSelect?.();\n        // `detail` is 0 when Enter or Space picked the row: close without animating.\n        if (closeOnSelect) root.setOpen(false, \"first\", event.detail === 0);\n      }}\n      className={cn(\n        MENU_ITEM_CLASS,\n        \"cursor-default gap-2\",\n        \"[&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0\",\n        inset && \"pl-9\",\n        disabled && \"opacity-50\",\n        tone === \"destructive\" ? \"text-destructive [&_svg]:text-destructive\" : \"[&_svg]:text-muted-foreground\",\n        className,\n      )}\n    >\n      {active && !disabled ? (\n        <MenuItemHighlight\n          layoutId={`${level.levelId}-highlight`}\n          tone={tone}\n          reduce={root.reduce}\n          instant={!level.glide}\n        />\n      ) : null}\n      {children}\n    </button>\n  );\n}\n"},{"path":"components/motion/dropdown-menu/menu-panel.tsx","type":"util","content":"\"use client\";\n\nimport { motion, type Variants } from \"motion/react\";\nimport {\n  type MutableRefObject,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { enabledItems, useMenuNavigation } from \"@/components/motion/menu/use-menu-navigation\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { type FocusTarget, LevelContext, type LevelContextValue, useRoot } from \"./context\";\nimport { type Align, type Placement, type Point, place, type Side } from \"./placement\";\n\nconst EXIT = { duration: 0.12, ease: EASE_OUT };\n// The panel grows out of its trigger from this scale and distance.\nconst OPEN_SCALE = 0.94;\nconst OPEN_TRAVEL = 6;\nconst OPEN = { duration: 0.2, ease: EASE_OUT };\nconst INSTANT = { duration: 0 };\n\ninterface PanelProps {\n  children: ReactNode;\n  className?: string;\n  id: string;\n  anchorRef: MutableRefObject<HTMLElement | null>;\n  side: Side;\n  align: Align;\n  sideOffset: number;\n  focus: FocusTarget;\n  /** Show without animating; the AnimatePresence around it carries the same flag to the exit. */\n  instant: boolean;\n  present: boolean;\n  gate: { inert: boolean; style: { pointerEvents: \"auto\" | \"none\" } };\n  labelledBy: string;\n  onClose: () => void;\n  onKeyDown?: (event: ReactKeyboardEvent<HTMLDivElement>) => boolean;\n  onPointerEnter?: () => void;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n}\n\n/** One panel, shared by the menu and its submenus. */\nexport function MenuPanel({\n  children,\n  className,\n  id,\n  anchorRef,\n  side,\n  align,\n  sideOffset,\n  focus,\n  instant,\n  present,\n  gate,\n  labelledBy,\n  onClose,\n  onKeyDown,\n  onPointerEnter,\n  panelRef,\n}: PanelProps) {\n  const root = useRoot(\"DropdownMenuContent\");\n  const parent = useContext(LevelContext);\n  const levelId = useId();\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [glide, setGlide] = useState(true);\n  const [openSub, setOpenSubState] = useState<string | null>(null);\n  const [subFocus, setSubFocus] = useState<FocusTarget>(\"none\");\n  const [subInstant, setSubInstant] = useState(false);\n  const grace = useRef<{ polygon: Point[]; until: number } | null>(null);\n  const navigate = useMenuNavigation();\n\n  const layout = usePopoverPortalPosition(anchorRef, panelRef, true);\n  // Held once placed: an exiting panel stays where it was, even if the\n  // trigger scrolls away under it.\n  const [placement, setPlacement] = useState<Placement | null>(null);\n  useLayoutEffect(() => {\n    if (!layout || !present) return;\n    // A submenu measures its gap from the parent panel's edge, not from the\n    // row inside it, so the two panels never touch.\n    const edge = parent?.panelRef.current?.getBoundingClientRect();\n    const anchor = edge ? { ...layout.trigger, left: edge.left, width: edge.width } : layout.trigger;\n    setPlacement(place(anchor, layout.content, side, align, sideOffset));\n  }, [layout, present, side, align, sideOffset, parent]);\n\n  const setOpenSub = useCallback(\n    (next: string | null, nextFocus: FocusTarget = \"none\", now = nextFocus !== \"none\") => {\n      setSubFocus(nextFocus);\n      setSubInstant(now);\n      setOpenSubState(next);\n    },\n    [],\n  );\n\n  // Waits for the first placement: the panel is `visibility: hidden` until\n  // then, and the browser will not focus anything inside it.\n  const placed = placement !== null;\n  useEffect(() => {\n    const panel = panelRef.current;\n    // `present` too: reopening during the exit brings this same panel back.\n    if (!placed || !present || !panel || focus === \"none\") return;\n    if (focus === \"panel\") {\n      panel.focus({ preventScroll: true });\n      return;\n    }\n    const items = enabledItems(panel);\n    (focus === \"last\" ? items[items.length - 1] : items[0])?.focus({ preventScroll: true });\n  }, [placed, present, focus, panelRef]);\n\n  const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n    // Submenus render inside this panel's React tree, so their keys bubble\n    // here too. Each panel answers only for its own rows.\n    const panel = panelRef.current;\n    const target = event.target as HTMLElement;\n    if (!panel || target.closest(\"[data-menu-panel]\") !== panel) return;\n    // Set before the key moves focus, so the highlight it lands on jumps.\n    setGlide(false);\n    if (onKeyDown?.(event)) return;\n    if (event.key === \"Tab\") {\n      event.preventDefault();\n      onClose();\n      return;\n    }\n    navigate(event, panel);\n  };\n\n  const level = useMemo<LevelContextValue>(\n    () => ({\n      levelId,\n      present,\n      panelRef,\n      activeId,\n      setActiveId,\n      glide,\n      openSub,\n      setOpenSub,\n      subFocus,\n      subInstant,\n      grace,\n    }),\n    [levelId, present, panelRef, activeId, glide, openSub, setOpenSub, subFocus, subInstant],\n  );\n\n  // The panel starts tucked toward its trigger and springs out of it.\n  const used = placement?.side ?? side;\n  const toward = used === \"top\" || used === \"left\" ? 1 : -1;\n  const vertical = used === \"top\" || used === \"bottom\";\n  const offset = (distance: number) => (vertical ? { y: distance * toward } : { x: distance * toward });\n  // `custom` is the instant flag. An exiting panel reads it from its\n  // AnimatePresence, so Escape removes the menu at once even after it has\n  // already left the React tree.\n  const variants: Variants = root.reduce\n    ? {\n        hidden: { opacity: 0 },\n        shown: (now = false) => ({\n          opacity: 1,\n          transition: now ? INSTANT : { duration: 0.15, ease: EASE_OUT },\n        }),\n        gone: (now = false) => ({ opacity: 0, transition: now ? INSTANT : EXIT }),\n      }\n    : {\n        hidden: { opacity: 0, scale: OPEN_SCALE, ...offset(OPEN_TRAVEL) },\n        shown: (now = false) => ({\n          opacity: 1,\n          scale: 1,\n          x: 0,\n          y: 0,\n          transition: now\n            ? INSTANT\n            : {\n                ...OPEN,\n                opacity: { duration: 0.12, ease: EASE_OUT },\n              },\n        }),\n        gone: (now = false) => ({\n          opacity: 0,\n          scale: 0.97,\n          ...offset(OPEN_TRAVEL / 2),\n          transition: now ? INSTANT : EXIT,\n        }),\n      };\n\n  return createPortal(\n    <motion.div\n      {...gate}\n      ref={panelRef}\n      id={id}\n      role=\"menu\"\n      aria-labelledby={labelledBy}\n      aria-orientation=\"vertical\"\n      tabIndex={-1}\n      data-menu-panel=\"\"\n      data-menu-root={root.menuId}\n      data-level={levelId}\n      data-side={placement?.side ?? side}\n      custom={instant}\n      variants={variants}\n      initial=\"hidden\"\n      animate=\"shown\"\n      exit=\"gone\"\n      onKeyDown={handleKeyDown}\n      onPointerMove={(event) => {\n        if (event.pointerType !== \"touch\") setGlide(true);\n      }}\n      onFocus={(event) => {\n        if (event.target === event.currentTarget) setActiveId(null);\n      }}\n      onPointerEnter={onPointerEnter}\n      onPointerLeave={(event) => {\n        // Leaving the panel drops the highlight, unless the row it sits on\n        // owns the open submenu the pointer is heading into.\n        if (event.pointerType === \"touch\" || openSub) return;\n        const panel = panelRef.current;\n        if (panel?.contains(document.activeElement)) panel.focus({ preventScroll: true });\n      }}\n      style={{\n        ...gate.style,\n        left: placement?.left ?? 0,\n        top: placement?.top ?? 0,\n        transformOrigin: placement?.origin,\n        maxHeight: placement?.maxHeight,\n        visibility: placement ? undefined : \"hidden\",\n      }}\n      className={cn(\n        \"fixed z-[100] min-w-48 overflow-y-auto overscroll-contain rounded-2xl border border-border bg-background p-2 text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)] outline-none\",\n        parent && \"z-[101]\",\n        className,\n      )}\n    >\n      <LevelContext.Provider value={level}>{children}</LevelContext.Provider>\n    </motion.div>,\n    document.body,\n  );\n}\n"},{"path":"components/motion/dropdown-menu/placement.ts","type":"util","content":"export const VIEWPORT_PADDING = 8;\n// The panel's border and padding, so a submenu's first row lines up with the\n// row that opened it.\nexport const SUB_ALIGN_OFFSET = 9;\n// How far a submenu stacked under its row sits in, so it reads as nested.\nexport const SUB_STACK_INDENT = 16;\n\nexport type Side = \"top\" | \"bottom\" | \"left\" | \"right\";\nexport type Align = \"start\" | \"center\" | \"end\";\nexport type Point = { x: number; y: number };\n\nexport type Placement = {\n  left: number;\n  top: number;\n  side: Side;\n  origin: string;\n  /** The room on the chosen side; a taller menu scrolls inside it. */\n  maxHeight: number;\n};\n\nexport type Rect = { left: number; top: number; width: number; height: number };\n\nexport function clamp(value: number, min: number, max: number) {\n  return Math.min(Math.max(value, min), Math.max(min, max));\n}\n\nexport function insidePolygon(point: Point, polygon: Point[]) {\n  let inside = false;\n  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n    const a = polygon[i];\n    const b = polygon[j];\n    if (\n      a.y > point.y !== b.y > point.y &&\n      point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x\n    ) {\n      inside = !inside;\n    }\n  }\n  return inside;\n}\n\nexport function placeVertical(\n  trigger: Rect,\n  size: { width: number; height: number },\n  side: \"top\" | \"bottom\",\n  align: Align,\n  offset: number,\n): Placement {\n  const viewWidth = document.documentElement.clientWidth;\n  const viewHeight = window.innerHeight;\n  const below = trigger.top + trigger.height + offset;\n  const roomBelow = viewHeight - VIEWPORT_PADDING - below;\n  const roomAbove = trigger.top - offset - VIEWPORT_PADDING;\n  // The preferred side when the menu fits there, otherwise the roomier one.\n  const used =\n    side === \"bottom\"\n      ? size.height <= roomBelow || roomBelow >= roomAbove\n        ? \"bottom\"\n        : \"top\"\n      : size.height <= roomAbove || roomAbove >= roomBelow\n        ? \"top\"\n        : \"bottom\";\n  const maxHeight = Math.max(used === \"bottom\" ? roomBelow : roomAbove, 0);\n  const height = Math.min(size.height, maxHeight);\n  const start =\n    align === \"start\"\n      ? trigger.left\n      : align === \"end\"\n        ? trigger.left + trigger.width - size.width\n        : trigger.left + trigger.width / 2 - size.width / 2;\n  const x = clamp(start, VIEWPORT_PADDING, viewWidth - size.width - VIEWPORT_PADDING);\n  const y = used === \"bottom\" ? below : trigger.top - offset - height;\n  // Grow from the aligned edge, so that edge holds still while the panel\n  // scales in instead of sliding sideways into place.\n  const anchorX =\n    align === \"start\"\n      ? trigger.left\n      : align === \"end\"\n        ? trigger.left + trigger.width\n        : trigger.left + trigger.width / 2;\n  const originX = clamp(anchorX - x, 0, size.width);\n  return {\n    left: x,\n    top: y,\n    side: used,\n    origin: `${originX}px ${used === \"bottom\" ? 0 : height}px`,\n    maxHeight,\n  };\n}\n\nexport function place(\n  trigger: Rect,\n  size: { width: number; height: number },\n  side: Side,\n  align: Align,\n  offset: number,\n): Placement {\n  if (side === \"top\" || side === \"bottom\") {\n    return placeVertical(trigger, size, side, align, offset);\n  }\n\n  const viewWidth = document.documentElement.clientWidth;\n  const viewHeight = window.innerHeight;\n  const right = trigger.left + trigger.width + offset;\n  const left = trigger.left - size.width - offset;\n  const fitsRight = right + size.width <= viewWidth - VIEWPORT_PADDING;\n  const fitsLeft = left >= VIEWPORT_PADDING;\n  // A narrow screen has room on neither side: drop below the row instead of\n  // covering it, the way a phone stacks a submenu.\n  if (!fitsRight && !fitsLeft) {\n    return placeVertical(\n      { ...trigger, left: trigger.left + SUB_STACK_INDENT, width: trigger.width - SUB_STACK_INDENT },\n      size,\n      \"bottom\",\n      \"start\",\n      2,\n    );\n  }\n  const used: Side = side === \"right\" ? (fitsRight ? \"right\" : \"left\") : fitsLeft ? \"left\" : \"right\";\n  const maxHeight = viewHeight - VIEWPORT_PADDING * 2;\n  const height = Math.min(size.height, maxHeight);\n  const x = used === \"right\" ? right : left;\n  const y = clamp(trigger.top - SUB_ALIGN_OFFSET, VIEWPORT_PADDING, viewHeight - height - VIEWPORT_PADDING);\n  const originY = clamp(trigger.top + trigger.height / 2 - y, 0, height);\n  return {\n    left: x,\n    top: y,\n    side: used,\n    origin: `${used === \"right\" ? 0 : size.width}px ${originY}px`,\n    maxHeight,\n  };\n}\n"},{"path":"components/motion/menu/use-menu-navigation.ts","type":"util","content":"\"use client\";\n\nimport { type KeyboardEvent, useCallback, useEffect, useRef } from \"react\";\n\nconst TYPEAHEAD_RESET = 500;\n\n/**\n * The enabled rows of one menu panel, in order. Rows carry `data-menu-item`\n * and the panel's `data-level`, so a submenu rendered inside the panel keeps\n * its own rows to itself.\n */\nexport function enabledItems(panel: HTMLElement | null) {\n  if (!panel) return [];\n  return Array.from(\n    panel.querySelectorAll<HTMLElement>(\n      `[data-menu-item][data-level=\"${panel.dataset.level}\"]:not([data-disabled])`,\n    ),\n  );\n}\n\n/**\n * Arrow keys, Home, End and typeahead for a menu panel. The returned handler\n * moves focus between the panel's rows and says whether it used the key.\n * Typeahead matches a row's `data-text-value`, or its text.\n */\nexport function useMenuNavigation() {\n  const query = useRef(\"\");\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  useEffect(\n    () => () => {\n      if (timer.current) clearTimeout(timer.current);\n    },\n    [],\n  );\n\n  return useCallback((event: KeyboardEvent<HTMLElement>, panel: HTMLElement | null) => {\n    const items = enabledItems(panel);\n    const index = items.indexOf(event.target as HTMLElement);\n    if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n      event.preventDefault();\n      if (items.length === 0) return true;\n      const step = event.key === \"ArrowDown\" ? 1 : -1;\n      const next =\n        index < 0\n          ? step === 1\n            ? 0\n            : items.length - 1\n          : (index + step + items.length) % items.length;\n      items[next]?.focus();\n      return true;\n    }\n    if (event.key === \"Home\" || event.key === \"End\") {\n      event.preventDefault();\n      items[event.key === \"Home\" ? 0 : items.length - 1]?.focus();\n      return true;\n    }\n    const typed = event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;\n    // A space with nothing typed yet presses the row instead.\n    if (!typed || (event.key === \" \" && query.current === \"\")) return false;\n    query.current += event.key.toLocaleLowerCase();\n    if (timer.current) clearTimeout(timer.current);\n    timer.current = setTimeout(() => {\n      query.current = \"\";\n    }, TYPEAHEAD_RESET);\n    // Start after the current row, so repeating a letter cycles its matches.\n    const ordered = [...items.slice(index + 1), ...items.slice(0, index + 1)];\n    const typedSoFar = query.current;\n    const repeated = typedSoFar.length > 1 && [...typedSoFar].every((char) => char === typedSoFar[0]);\n    const needle = repeated ? typedSoFar[0] : typedSoFar;\n    const match = ordered.find((item) =>\n      (item.dataset.textValue ?? item.textContent ?? \"\").trim().toLocaleLowerCase().startsWith(needle),\n    );\n    if (!match) return false;\n    event.preventDefault();\n    match.focus();\n    return true;\n  }, []);\n}\n"},{"path":"lib/presence-gate.tsx","type":"util","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport type { ReactNode } from \"react\";\n\nexport interface PresenceGateRenderProps {\n  /**\n   * False from the render that starts the exit animation onward. An overlay\n   * kept in the tree by `AnimatePresence` is still the topmost thing on the\n   * page, so anything it decides from `open` alone stays true for the whole\n   * exit - this is the boolean that already knows the overlay is leaving.\n   */\n  isPresent: boolean;\n  /**\n   * Spread onto every layer that takes pointer events while the overlay is\n   * open. Interaction releases in the same commit that starts the exit while\n   * the visual exit keeps playing: pointer events stop landing, and `inert`\n   * drops the subtree from focus order, from tab order and from the\n   * accessibility tree - an exiting dialog is not a dialog you can still type\n   * into. A layer that never takes pointer events (a wrapper that only centres\n   * the panel) takes `inert={!isPresent}` alone, so its own\n   * `pointer-events-none` is not overwritten.\n   */\n  gate: {\n    inert: boolean;\n    style: { pointerEvents: \"auto\" | \"none\" };\n  };\n}\n\nexport interface PresenceGateProps {\n  children: (props: PresenceGateRenderProps) => ReactNode;\n}\n\n/**\n * Reads the presence of the subtree it renders and hands it down.\n *\n * `useIsPresent` only answers inside the `AnimatePresence` subtree, and the\n * components that own an overlay render the `AnimatePresence` themselves, so\n * the boolean has to be read one component further down: this is that\n * component, and the render prop is how it reaches the layers.\n */\nexport function PresenceGate({ children }: PresenceGateProps) {\n  const isPresent = useIsPresent();\n\n  return children({\n    isPresent,\n    gate: {\n      inert: !isPresent,\n      style: { pointerEvents: isPresent ? \"auto\" : \"none\" },\n    },\n  });\n}\n"},{"path":"lib/sound.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n} from \"react\";\nimport {\n  registerSoundSettings,\n  retainAudioContext,\n  type SoundSettingsEntry,\n} from \"@/lib/audio-context\";\nimport type { PlayOptions, Sound } from \"@/lib/sounds/engine\";\n\nexport interface SoundSettings {\n  /** False mutes every beUI sound under the provider. */\n  enabled: boolean;\n  /** 0 to 1, scales every beUI sound. */\n  volume: number;\n}\n\nconst SoundContext = createContext<SoundSettings & { depth: number }>({\n  enabled: true,\n  volume: 1,\n  depth: 0,\n});\n\n/**\n * App-wide sound settings. `enabled={false}` mutes every beUI sound, from\n * component `sound` props and `useSound` to the games, Wheel Picker and\n * Bookshelf, and `volume` scales them all. Without a provider, sounds play at\n * full volume. A nested provider overrides the one around it.\n */\nexport function SoundProvider({\n  enabled = true,\n  volume = 1,\n  children,\n}: Partial<SoundSettings> & { children: ReactNode }) {\n  const depth = useContext(SoundContext).depth + 1;\n  const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);\n\n  // Module-level as well (lib/audio-context.ts), so players outside React\n  // and `sound.play()` obey it too.\n  const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });\n  const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);\n  useEffect(() => {\n    registration.current = registerSoundSettings(entry.current);\n    return () => {\n      registration.current?.release();\n      registration.current = null;\n    };\n  }, []);\n  useEffect(() => {\n    Object.assign(entry.current, { depth, enabled, volume });\n    registration.current?.update();\n  }, [depth, enabled, volume]);\n\n  return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;\n}\n\nexport function useSoundSettings(): SoundSettings {\n  return useContext(SoundContext);\n}\n\nexport interface UseSoundOptions {\n  /** False makes `play` do nothing, for a component's `sound` prop. */\n  enabled?: boolean;\n  /** 0 to 1 for this sound, on top of the provider volume. */\n  volume?: number;\n}\n\n/**\n * A stable `play()` for one sound. It does nothing while disabled or muted,\n * and keeps the shared audio context warm only while it can play.\n */\nexport function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {\n  const settings = useSoundSettings();\n  const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;\n  // Read by the stable callback, so a caller's effects don't re-run when\n  // the settings change.\n  const latest = useRef({ on, volume, sound });\n  useLayoutEffect(() => {\n    latest.current = { on, volume, sound };\n  });\n\n  useEffect(() => {\n    if (!on) return;\n    return retainAudioContext();\n  }, [on]);\n\n  return useCallback((options?: PlayOptions) => {\n    const current = latest.current;\n    if (!current.on) return;\n    current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });\n  }, []);\n}\n"},{"path":"lib/sounds/close.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** The open whoosh falling and a little quicker, settling with a soft low tap, for things closing. */\nexport const closeSound = defineSound({\n  name: \"Close\",\n  duration: 0.16,\n  room: 0.18,\n  build: (v) => {\n    v.noise({ freq: 2600, to: 700, q: 1.2, attack: 0.012, decay: 0.09, gain: 0.7 });\n    v.click({ freq: 1400, q: 1.2, at: 0.05, decay: 0.006, gain: 0.2 });\n    v.strike({ freq: 260, material: \"wood\", bend: 1.2, at: 0.05, decay: 0.045, gain: 0.3 });\n  },\n});\n"},{"path":"lib/sounds/open.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A soft rising whoosh that lands with a light glass touch, for menus, popovers and dialogs opening. */\nexport const openSound = defineSound({\n  name: \"Open\",\n  duration: 0.2,\n  room: 0.2,\n  build: (v) => {\n    v.noise({ freq: 600, to: 2600, q: 1.2, attack: 0.035, decay: 0.11, gain: 0.75 });\n    v.noise({ freq: 4500, to: 6000, q: 1, attack: 0.03, decay: 0.07, gain: 0.05 });\n    v.strike({ freq: 1320, material: \"glass\", at: 0.05, decay: 0.07, gain: 0.12 });\n  },\n});\n"},{"path":"lib/sounds/select.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */\nexport const selectSound = defineSound({\n  name: \"Select\",\n  duration: 0.05,\n  room: 0.08,\n  build: (v) => {\n    v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });\n    v.strike({ freq: 1700, material: \"metal\", decay: 0.028, gain: 0.3 });\n    v.strike({ freq: 520, material: \"wood\", bend: 1.15, decay: 0.012, gain: 0.25 });\n  },\n});\n"},{"path":"lib/hooks/use-favicon.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useState } from \"react\";\nimport { getFaviconUrl } from \"@/lib/favicon\";\n\n/**\n * Resolves a site favicon and drops it once it is known to be unusable, so\n * callers can draw their own glyph instead of a broken image. Plenty of sites\n * answer `/favicon.ico` with a 403 or 404, and `onError` is not enough to catch\n * it: an image the browser starts loading from server-rendered HTML usually\n * fails before React attaches a handler, and that event is never replayed.\n * `decode()` settles on the image's final state instead of relying on an event\n * firing at the right moment.\n */\nexport function useFavicon(url?: string) {\n  const resolved = url ? getFaviconUrl(url) : null;\n  const [failedSrc, setFailedSrc] = useState<string | null>(null);\n  const src = resolved && resolved !== failedSrc ? resolved : null;\n\n  const ref = useCallback(\n    (img: HTMLImageElement | null) => {\n      if (!img || !src) return;\n\n      let released = false;\n      img.decode().catch(() => {\n        if (!released) setFailedSrc(src);\n      });\n\n      // The node is going away or the source changed; a late rejection then\n      // describes an image we are no longer showing.\n      return () => {\n        released = true;\n      };\n    },\n    [src],\n  );\n\n  return { src, ref };\n}\n"},{"path":"lib/hooks/use-focus-trap.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport { cycleTab, focusFirstIn } from \"@/lib/focusable\";\nimport { inLayerAbove, type Layer, openLayer, ownsEscape, trapAbove } from \"@/lib/layers\";\n\nexport interface FocusTrapOptions {\n  /** Called on Escape while this is the innermost open layer. */\n  onEscape?: () => void;\n}\n\n/**\n * Moves focus into `panel` when `open` turns true, keeps Tab cycling inside it,\n * pulls focus back if it lands outside, and returns focus to whatever held it\n * before opening once `open` turns false.\n *\n * Layers opened on top (a menu portaled out of a drawer, a sheet opened from\n * it) keep focus and Escape until they close: see `lib/layers.ts`.\n *\n * For overlays rendered in place, where `useModalScope` cannot inert the rest\n * of the page. Pass `open` rather than presence: an exiting panel is already\n * inert through `PresenceGate`, so the trap releases with the same commit.\n * Give the panel `tabIndex={-1}` so it can take focus when it holds nothing\n * focusable.\n */\nexport function useFocusTrap(\n  open: boolean,\n  panel: RefObject<HTMLElement | null>,\n  { onEscape }: FocusTrapOptions = {},\n) {\n  const escapeRef = useRef(onEscape);\n  useLayoutEffect(() => {\n    escapeRef.current = onEscape;\n  });\n\n  useEffect(() => {\n    if (!open || !panel.current) return;\n    const layer: Layer = {\n      contains: (target) => Boolean(panel.current?.contains(target)),\n      traps: true,\n      get escape() {\n        return Boolean(escapeRef.current);\n      },\n    };\n    const closeLayer = openLayer(layer);\n    const returnFocus =\n      document.activeElement instanceof HTMLElement\n        ? document.activeElement\n        : null;\n    if (!panel.current.contains(document.activeElement)) focusFirstIn(panel.current);\n\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (!(target instanceof Node) || !panel.current) return;\n      if (panel.current.closest(\"[inert]\") || panel.current.contains(target)) return;\n      if (inLayerAbove(layer, target) || trapAbove(layer)) return;\n      focusFirstIn(panel.current);\n    };\n    const onKey = (event: KeyboardEvent) => {\n      if (event.key === \"Escape\") {\n        if (!escapeRef.current || !ownsEscape(layer, event)) return;\n        event.preventDefault();\n        escapeRef.current();\n        return;\n      }\n      const active = document.activeElement;\n      if (event.defaultPrevented || (active && inLayerAbove(layer, active))) return;\n      cycleTab(event, panel.current);\n    };\n    document.addEventListener(\"focusin\", onFocus);\n    document.addEventListener(\"keydown\", onKey);\n    return () => {\n      document.removeEventListener(\"focusin\", onFocus);\n      document.removeEventListener(\"keydown\", onKey);\n      closeLayer();\n      if (returnFocus?.isConnected && !returnFocus.closest(\"[inert]\"))\n        returnFocus.focus({ preventScroll: true });\n    };\n  }, [open, panel]);\n}\n"},{"path":"lib/scroll-lock.ts","type":"util","content":"\"use client\";\n\nimport { useEffect } from \"react\";\n\nexport interface ScrollLockOptions {\n  /**\n   * Pin the body with `position: fixed` and restore the scroll offset on\n   * release. iOS Safari still scrolls an `overflow: hidden` body under a\n   * touch drag, so full-screen sheets that take touch gestures need this.\n   */\n  fixed?: boolean;\n}\n\n// Reference-counted, so overlays that close out of order never unlock the\n// page under one that is still open. The first lock picks the technique.\nlet owners = 0;\nlet restore: (() => void) | null = null;\n\nfunction apply({ fixed = false }: ScrollLockOptions) {\n  const root = document.documentElement;\n  const body = document.body;\n  const scrollY = window.scrollY;\n  const previous = {\n    rootOverflow: root.style.overflow,\n    overflow: body.style.overflow,\n    position: body.style.position,\n    top: body.style.top,\n    left: body.style.left,\n    right: body.style.right,\n  };\n  root.style.overflow = \"hidden\";\n  body.style.overflow = \"hidden\";\n  if (fixed) {\n    body.style.position = \"fixed\";\n    body.style.top = `-${scrollY}px`;\n    body.style.left = \"0\";\n    body.style.right = \"0\";\n  }\n  return () => {\n    root.style.overflow = previous.rootOverflow;\n    body.style.overflow = previous.overflow;\n    if (!fixed) return;\n    body.style.position = previous.position;\n    body.style.top = previous.top;\n    body.style.left = previous.left;\n    body.style.right = previous.right;\n    window.scrollTo(0, scrollY);\n  };\n}\n\n/** Locks page scroll. Call the returned function to release this lock. */\nexport function lockScroll(options: ScrollLockOptions = {}) {\n  if (owners++ === 0) restore = apply(options);\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    if (--owners === 0) {\n      restore?.();\n      restore = null;\n    }\n  };\n}\n\n/** Locks page scroll while `locked` is true. */\nexport function useScrollLock(locked: boolean, { fixed = false }: ScrollLockOptions = {}) {\n  useEffect(() => {\n    if (!locked) return;\n    return lockScroll({ fixed });\n  }, [locked, fixed]);\n}\n"},{"path":"components/motion/popover-position.ts","type":"util","content":"\"use client\";\n\nimport {\n  type MutableRefObject,\n  useCallback,\n  useLayoutEffect,\n  useState,\n} from \"react\";\n\nexport type PortalLayout = {\n  trigger: {\n    left: number;\n    top: number;\n    width: number;\n    height: number;\n  };\n  content: {\n    width: number;\n    height: number;\n  };\n};\n\nfunction sameLayout(a: PortalLayout | null, b: PortalLayout) {\n  return (\n    a?.trigger.left === b.trigger.left &&\n    a.trigger.top === b.trigger.top &&\n    a.trigger.width === b.trigger.width &&\n    a.trigger.height === b.trigger.height &&\n    a.content.width === b.content.width &&\n    a.content.height === b.content.height\n  );\n}\n\n/** Measures a trigger and portalled panel in viewport coordinates. */\nexport function usePopoverPortalPosition<\n  TriggerElement extends HTMLElement,\n  ContentElement extends HTMLElement,\n>(\n  triggerRef: MutableRefObject<TriggerElement | null>,\n  contentRef: MutableRefObject<ContentElement | null>,\n  active: boolean,\n) {\n  const [layout, setLayout] = useState<PortalLayout | null>(null);\n\n  const update = useCallback(() => {\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    if (!trigger || !content) return;\n\n    const rect = trigger.getBoundingClientRect();\n    const next: PortalLayout = {\n      trigger: {\n        left: rect.left,\n        top: rect.top,\n        width: rect.width,\n        height: rect.height,\n      },\n      content: {\n        width: content.offsetWidth,\n        height: content.offsetHeight,\n      },\n    };\n    setLayout((current) => (sameLayout(current, next) ? current : next));\n  }, [contentRef, triggerRef]);\n\n  useLayoutEffect(() => {\n    update();\n    if (!active) return;\n\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    const observer = new ResizeObserver(update);\n    if (trigger) observer.observe(trigger);\n    if (content) observer.observe(content);\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [active, contentRef, triggerRef, update]);\n\n  return layout;\n}\n"},{"path":"lib/focusable.ts","type":"util","content":"/**\n * Elements that can usually take keyboard focus. The selector cannot see\n * everything focus() checks (an element under `display: none`, say), so a\n * caller that needs certainty tries focus() and checks where it landed.\n */\nexport const FOCUSABLE_SELECTOR = [\n  \"a[href]\",\n  \"button:not(:disabled)\",\n  \"input:not(:disabled):not([type='hidden'])\",\n  \"select:not(:disabled)\",\n  \"textarea:not(:disabled)\",\n  \"[tabindex]:not([tabindex='-1'])\",\n].join(\",\");\n\n/** Elements inside `container` that Tab can reach, in DOM order. */\nexport function focusablesIn(container: Element | null | undefined) {\n  return Array.from(\n    container?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR) ?? [],\n  ).filter((element) => element.tabIndex >= 0 && !element.closest(\"[inert]\"));\n}\n\n/** Focuses the first tabbable element in `panel`, or the panel itself. */\nexport function focusFirstIn(panel: HTMLElement | null | undefined) {\n  (focusablesIn(panel)[0] ?? panel)?.focus({ preventScroll: true });\n}\n\n/**\n * Keeps a Tab keypress inside `panel`, wrapping from the last tabbable element\n * to the first and back. Give the panel `tabIndex={-1}` so it can hold focus\n * when it has nothing tabbable.\n */\nexport function cycleTab(event: KeyboardEvent, panel: HTMLElement | null) {\n  if (event.key !== \"Tab\" || !panel) return;\n  const elements = focusablesIn(panel);\n  const first = elements[0];\n  const last = elements[elements.length - 1];\n  const active = document.activeElement;\n  if (!first || !last) {\n    event.preventDefault();\n    panel.focus({ preventScroll: true });\n  } else if (event.shiftKey && (active === first || active === panel)) {\n    event.preventDefault();\n    last.focus();\n  } else if (!event.shiftKey && active === last) {\n    event.preventDefault();\n    first.focus();\n  }\n}\n"},{"path":"lib/sounds/press.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A physical button: a switch click that settles twice over a soft thump and a little casing ring. */\nexport const pressSound = defineSound({\n  name: \"Press\",\n  duration: 0.1,\n  vary: 0.03,\n  room: 0.1,\n  build: (v) => {\n    v.click({ freq: 2800, q: 1.8, decay: 0.005, gain: 0.5 });\n    v.click({ freq: 4200, q: 2.5, at: 0.011, decay: 0.003, gain: 0.16 });\n    v.strike({ freq: 150, material: \"wood\", bend: 1.5, decay: 0.07, gain: 0.75 });\n    v.strike({ freq: 1250, material: \"plastic\", decay: 0.022, gain: 0.14 });\n  },\n});\n"},{"path":"components/motion/magnetic.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useMotionValue, useReducedMotion, useSpring } from \"motion/react\";\nimport { useRef, type ReactNode } from \"react\";\nimport { SPRING_MOUSE } from \"@/lib/ease\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface MagneticProps {\n  children: ReactNode;\n  strength?: number;\n  className?: string;\n}\n\nexport function Magnetic({ children, strength = 0.35, className }: MagneticProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const reduce = useReducedMotion();\n  const canHover = useHoverCapable();\n  // Decorative cursor-follow: skip on touch (phantom hover) and reduced motion.\n  const enabled = !reduce && canHover;\n  const x = useMotionValue(0);\n  const y = useMotionValue(0);\n  const sx = useSpring(x, SPRING_MOUSE);\n  const sy = useSpring(y, SPRING_MOUSE);\n\n  const onMove = (e: React.MouseEvent<HTMLDivElement>) => {\n    const el = ref.current;\n    if (!el || !enabled) return;\n    const rect = el.getBoundingClientRect();\n    x.set((e.clientX - rect.left - rect.width / 2) * strength);\n    y.set((e.clientY - rect.top - rect.height / 2) * strength);\n  };\n\n  const onLeave = () => {\n    x.set(0);\n    y.set(0);\n  };\n\n  return (\n    <motion.div\n      ref={ref}\n      onMouseMove={onMove}\n      onMouseLeave={onLeave}\n      style={{ x: sx, y: sy }}\n      className={cn(\"inline-block\", className)}\n    >\n      {children}\n    </motion.div>\n  );\n}\n"},{"path":"lib/layers.ts","type":"util","content":"/**\n * Every open overlay on the page, innermost last: focus traps, modal scopes\n * and dismissable menus all register here. Overlays have no shared z-order to\n * consult, and a menu inside a drawer portals out of it, so this stack is how\n * they agree on who answers Escape and where focus may go.\n */\n\nexport interface Layer {\n  /** Whether `target` belongs to this layer (its panel, portals, trigger). */\n  contains: (target: Node) => boolean;\n  /** True for focus traps and modal scopes, which pull stray focus back. */\n  traps?: boolean;\n  /** False for a layer that ignores Escape, so the key reaches the one below. */\n  escape?: boolean;\n}\n\nconst stack: Layer[] = [];\n// The innermost layer when each Escape began, read before any handler runs,\n// so a layer that closes itself mid-event can't hand the key to the one below.\nconst escapeOwners = new WeakMap<Event, Layer | undefined>();\nlet listening = false;\n\nfunction innermostEscapeLayer() {\n  for (let index = stack.length - 1; index >= 0; index--) {\n    if (stack[index].escape !== false) return stack[index];\n  }\n  return undefined;\n}\n\nfunction recordEscapeOwner(event: KeyboardEvent) {\n  if (event.key === \"Escape\") escapeOwners.set(event, innermostEscapeLayer());\n}\n\n/** Registers an open layer. Call the returned function when it closes. */\nexport function openLayer(layer: Layer) {\n  if (!listening) {\n    document.addEventListener(\"keydown\", recordEscapeOwner, true);\n    listening = true;\n  }\n  stack.push(layer);\n  return () => {\n    const index = stack.indexOf(layer);\n    if (index !== -1) stack.splice(index, 1);\n  };\n}\n\n/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */\nexport function ownsEscape(layer: Layer, event: KeyboardEvent) {\n  if (event.defaultPrevented) return false;\n  const owner = escapeOwners.has(event)\n    ? escapeOwners.get(event)\n    : innermostEscapeLayer();\n  return owner === layer;\n}\n\n/** Whether `target` sits in a layer opened on top of `layer`. */\nexport function inLayerAbove(layer: Layer, target: Node) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.contains(target));\n}\n\n/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */\nexport function trapAbove(layer: Layer) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.traps);\n}\n\n/**\n * Whether `target` belongs to any open layer other than `layer`. Pass\n * `traps: false` to count only dismissable overlays, not the traps under them.\n */\nexport function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {\n  return stack.some(\n    (other) => other !== layer && (traps || !other.traps) && other.contains(target),\n  );\n}\n"},{"path":"lib/touch.ts","type":"util","content":"// Shared touch primitives. iOS and iPadOS run their own gestures on top of the\n// page - the long-press selection callout and the selection it drags in with\n// it - and they win: once the platform claims a touch it cancels ours\n// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own\n// their gesture have to opt out.\n//\n// What the two classes below cover, precisely:\n// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:\n//   it is not a property other engines have, so it is inert everywhere else.\n// - `user-select: none` stops the long-press selection on every engine,\n//   Android included, and stops a drag from painting a selection under the\n//   cursor. It is inherited, so it reaches every descendant - which is why the\n//   two classes differ only in whether they apply it unconditionally.\n// What neither covers:\n// - Chrome for Android's long-press menu on a link or an image. No CSS\n//   suppresses it; a gesture surface that wraps one needs its own\n//   `onContextMenu` with `preventDefault()`.\n// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is\n//   not inherited and plain divs and buttons are not drag sources, so setting\n//   it on the surface does nothing - the child itself needs `draggable={false}`.\n\n/**\n * Classes for a surface that *is* the control: a thumb, a drum, a stage, a\n * handle, a hold button. Selection is suppressed on every input, because a\n * drag that highlights the control's own label is wrong on a mouse too.\n * Compose with `touch-none` when the surface also owns the scroll axis - leave\n * it off when the page must still scroll from there.\n */\nexport const TOUCH_GESTURE_CLASS = \"select-none [-webkit-touch-callout:none]\";\n\n/**\n * The same opt-out for a gesture surface that wraps content the consumer owns:\n * a scroller, a context-menu trigger, a sheet header, a list row. Selection is\n * suppressed only where the platform runs its own press gestures - a coarse\n * pointer - so a mouse user can still select and copy that content. If the\n * gesture itself would paint a selection under the cursor, add `select-none`\n * for the duration of the gesture rather than reaching for\n * `TOUCH_GESTURE_CLASS`.\n *\n * `pointer: coarse` describes the *primary* pointer and nothing else, so a\n * hybrid machine reads it wrong in both directions: a tablet with a mouse\n * plugged in keeps touch as primary and loses mouse selection, and a laptop\n * with a touchscreen keeps the mouse as primary and leaves selection live\n * under a finger. No media query can answer per interaction - the query is\n * about the device, and the question is about the gesture in progress. The\n * default stays here because it is right on the machines that are one thing or\n * the other, and losing a selection is a nuisance; where the miss costs a\n * *gesture* instead, the surface pairs it with `holdSelection` on the press.\n */\nexport const TOUCH_GESTURE_CONTENT_CLASS =\n  \"[-webkit-touch-callout:none] pointer-coarse:select-none\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal - a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs - routine on iOS, where the\n * system can claim the touch first - and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active - implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer - a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger - so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it - `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"},{"path":"lib/audio-context.ts","type":"util","content":"// One AudioContext for every synthesized sound on the page: the sounds\n// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino\n// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap\n// concurrent contexts, and a page can show a date made of several WheelPickers\n// next to a game, so they all share this one. It is created on first use and\n// closed once every player is disposed.\n//\n// Every player connects to `audioOutput()` rather than the context's\n// destination, so the page-wide volume and mute from `SoundProvider`\n// (lib/sound.tsx) reach all of them in one place.\n\ntype AudioContextCtor = typeof AudioContext;\n\nlet context: AudioContext | null = null;\nlet master: GainNode | null = null;\nlet users = 0;\n\n/** Settings one mounted `SoundProvider` asks for. */\nexport interface SoundSettingsEntry {\n  /** Nesting depth: the deepest provider decides. */\n  depth: number;\n  enabled: boolean;\n  volume: number;\n}\n\n// Mounted providers in mount order. Module state, so `sound.play()` called\n// outside React obeys them too. The deepest provider wins; among equals, the\n// one mounted last. Effects run child first, so this can't be \"whoever ran\n// last\".\nconst providers = new Set<SoundSettingsEntry>();\nlet allowed = true;\nlet volume = 1;\n\nfunction applySettings() {\n  let chosen: SoundSettingsEntry | undefined;\n  for (const entry of providers) {\n    if (!chosen || entry.depth >= chosen.depth) chosen = entry;\n  }\n  allowed = chosen?.enabled ?? true;\n  volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));\n  if (master) master.gain.value = volume;\n}\n\n/**\n * Registers a provider's settings; call `update` after changing the entry and\n * the returned release function when the provider unmounts.\n */\nexport function registerSoundSettings(entry: SoundSettingsEntry) {\n  providers.add(entry);\n  applySettings();\n  return {\n    update: applySettings,\n    release() {\n      providers.delete(entry);\n      applySettings();\n    },\n  };\n}\n\n/**\n * Registers a sound player. Call the returned function when the player is\n * disposed; the context closes after the last one.\n */\nexport function retainAudioContext() {\n  users++;\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    users--;\n    if (users === 0 && context) {\n      void context.close();\n      context = null;\n      master = null;\n    }\n  };\n}\n\n/**\n * The shared context, created on first call and resumed if suspended. Null\n * during SSR, in browsers without Web Audio, and while sounds are muted or at\n * zero volume.\n */\nexport function getAudioContext(): AudioContext | null {\n  if (!allowed || volume <= 0) return null;\n  if (!context) {\n    if (typeof window === \"undefined\") return null;\n    const Ctor =\n      window.AudioContext ??\n      (window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;\n    if (!Ctor) return null;\n    context = new Ctor();\n  }\n  // Browsers may refuse outside a user gesture. Players call this from\n  // pointer and key handlers first, so a later call finds it running.\n  if (context.state === \"suspended\") void context.resume().catch(() => undefined);\n  return context;\n}\n\n/** The node every player connects to: the page-wide volume, then the speakers. */\nexport function audioOutput(ctx: AudioContext): AudioNode {\n  if (master?.context !== ctx) {\n    master = ctx.createGain();\n    master.gain.value = volume;\n    master.connect(ctx.destination);\n  }\n  return master;\n}\n\nconst gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();\n\n/**\n * A player's own level, made once per context and routed into `audioOutput`.\n * Players keep their mix this way without rebuilding nodes on every play, and\n * a context closed and recreated gets fresh ones.\n */\nexport function playerGain(ctx: AudioContext, key: string, level: number): GainNode {\n  let byKey = gains.get(ctx);\n  if (!byKey) {\n    byKey = new Map();\n    gains.set(ctx, byKey);\n  }\n  let gain = byKey.get(key);\n  if (!gain) {\n    gain = ctx.createGain();\n    gain.gain.value = level;\n    gain.connect(audioOutput(ctx));\n    byKey.set(key, gain);\n  }\n  return gain;\n}\n"},{"path":"lib/sounds/engine.ts","type":"util","content":"import { audioOutput, getAudioContext } from \"@/lib/audio-context\";\n\n// Every beUI sound is a short recipe played with Web Audio the moment it is\n// asked for. Nothing is downloaded. Recipes are built the way a real tap\n// sounds: a contact click (a millisecond of filtered noise), a body that\n// rings at a few inharmonic partials of a material and settles in pitch, and\n// a little of a small room behind it.\n\n/** Options for one play of a sound. */\nexport interface PlayOptions {\n  /** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */\n  volume?: number;\n  /** Pitch multiplier; 1 is the designed pitch. */\n  pitch?: number;\n}\n\n/** Where a sound renders: the live context, or an offline one for drawing. */\nexport interface SoundTarget {\n  context: BaseAudioContext;\n  destination: AudioNode;\n  /** Start time on the context clock, in seconds. */\n  when: number;\n  volume: number;\n  pitch: number;\n}\n\n/** A plain oscillator with an attack, a decay and an optional glide. */\nexport interface ToneSpec {\n  type?: OscillatorType;\n  /** Start frequency in Hz. */\n  freq: number;\n  /** End frequency in Hz; glides from `freq` over `glide`. */\n  to?: number;\n  /** Glide time in seconds; defaults to the attack plus decay. */\n  glide?: number;\n  /** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** A burst of filtered white noise. */\nexport interface NoiseSpec {\n  filter?: BiquadFilterType;\n  /** Filter frequency in Hz. */\n  freq: number;\n  /** End filter frequency in Hz; sweeps from `freq` over the decay. */\n  to?: number;\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */\nexport interface ClickSpec {\n  /** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */\n  freq: number;\n  /** Band width; higher is narrower and more tonal. */\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time to fade to silence, in seconds. */\n  decay?: number;\n  gain: number;\n}\n\n/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */\nexport interface Material {\n  partials: readonly (readonly [ratio: number, level: number])[];\n  /** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */\n  damping: number;\n}\n\n// Partial ratios follow the modes of small struck objects: a free bar for\n// wood and metal, a cup for glass, a tuned bar for the mallet.\nexport const MATERIALS = {\n  wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },\n  plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },\n  glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },\n  metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },\n  mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },\n  bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },\n} satisfies Record<string, Material>;\n\n/** A struck object: one partial per mode of its material, each with its own decay. */\nexport interface StrikeSpec {\n  /** Fundamental in Hz. */\n  freq: number;\n  /** A name from `MATERIALS` or your own partials. Default: \"plastic\". */\n  material?: keyof typeof MATERIALS | Material;\n  /** Starts this many times higher and settles in about 15 ms. Default: 1.01. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time for the fundamental to fade to silence, in seconds. */\n  decay: number;\n  gain: number;\n}\n\nexport interface Voice {\n  tone(spec: ToneSpec): void;\n  noise(spec: NoiseSpec): void;\n  click(spec: ClickSpec): void;\n  strike(spec: StrikeSpec): void;\n}\n\nexport interface Sound {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Plays the sound now. Silent during SSR and while sounds are muted. */\n  play(options?: PlayOptions): void;\n  /** Schedules the sound on any context; `play` uses the live one. */\n  render(target: SoundTarget): void;\n}\n\nexport interface SoundRecipe {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */\n  vary?: number;\n  /** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */\n  room?: number;\n  /** Adds the sound's layers to the voice on each play. */\n  build: (voice: Voice) => void;\n}\n\n// Keeps a sum of voices well under clipping at volume 1.\nconst MASTER_GAIN = 0.16;\nconst SILENT = 0.0001;\n// Time a strike or bend takes to settle onto its pitch.\nconst SETTLE = 0.015;\n\nconst noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\n/** One second of white noise per context, shared by every noise voice. */\nexport function noiseBuffer(context: BaseAudioContext) {\n  let buffer = noiseBuffers.get(context);\n  if (!buffer) {\n    buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);\n    const data = buffer.getChannelData(0);\n    for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n    noiseBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// A small, soft room: 8 early reflections, then a diffuse tail that falls\n// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls\n// absorb highs first. Generated once per context.\nconst ROOM_LENGTH = 0.3;\n// The convolver's equal-power normalization leaves the room about 15 dB\n// under the dry sound; this brings `room: 0.12` to a tail heard only as space.\nconst ROOM_GAIN = 6;\nconst roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\nfunction roomBuffer(context: BaseAudioContext) {\n  let buffer = roomBuffers.get(context);\n  if (!buffer) {\n    const rate = context.sampleRate;\n    const length = Math.ceil(ROOM_LENGTH * rate);\n    buffer = context.createBuffer(2, length, rate);\n    for (let channel = 0; channel < 2; channel++) {\n      const data = buffer.getChannelData(channel);\n      let smooth = 0;\n      for (let i = Math.floor(0.004 * rate); i < length; i++) {\n        const t = i / rate;\n        // One-pole low-pass whose cutoff closes over the tail.\n        const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;\n        smooth += brightness * (Math.random() * 2 - 1 - smooth);\n        data[i] = smooth * Math.exp(-t / 0.043);\n      }\n      for (let r = 0; r < 8; r++) {\n        const at = Math.floor((0.005 + Math.random() * 0.022) * rate);\n        data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);\n      }\n    }\n    roomBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// One convolver per output node, shared by every play: building one is the\n// expensive part, sending to it is cheap.\nconst rooms = new WeakMap<AudioNode, ConvolverNode>();\n\nfunction roomFor(context: BaseAudioContext, destination: AudioNode) {\n  let room = rooms.get(destination);\n  if (!room) {\n    room = context.createConvolver();\n    room.buffer = roomBuffer(context);\n    room.connect(destination);\n    rooms.set(destination, room);\n  }\n  return room;\n}\n\n/** A linear attack to `peak`, then an exponential fall to silence. */\nfunction envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {\n  param.setValueAtTime(0, start);\n  param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);\n  param.exponentialRampToValueAtTime(SILENT, start + attack + decay);\n}\n\nfunction voiceFor(target: SoundTarget, output: AudioNode): Voice {\n  const { context, when, pitch } = target;\n  // Partials above this only add hiss on small speakers, or alias near Nyquist.\n  const ceiling = Math.min(12000, context.sampleRate * 0.45);\n\n  const tone: Voice[\"tone\"] = ({ type = \"sine\", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const osc = context.createOscillator();\n    const amp = context.createGain();\n    osc.type = type;\n    const base = freq * pitch;\n    osc.frequency.setValueAtTime(base * (bend ?? 1), start);\n    if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);\n    if (to !== undefined) {\n      osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    osc.connect(amp).connect(output);\n    osc.start(start);\n    osc.stop(start + attack + decay + 0.02);\n  };\n\n  const noise: Voice[\"noise\"] = ({ filter = \"bandpass\", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const source = context.createBufferSource();\n    const shape = context.createBiquadFilter();\n    const amp = context.createGain();\n    source.buffer = noiseBuffer(context);\n    shape.type = filter;\n    shape.Q.value = q;\n    shape.frequency.setValueAtTime(freq * pitch, start);\n    if (to !== undefined) {\n      shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    source.connect(shape).connect(amp).connect(output);\n    // A random offset into the buffer keeps each burst a little different.\n    source.start(start, Math.random() * 0.5);\n    source.stop(start + attack + decay + 0.02);\n  };\n\n  return {\n    tone,\n    noise,\n    click({ freq, q = 2, at = 0, decay = 0.005, gain }) {\n      // A little spread on the band, so no two contacts are identical.\n      noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });\n    },\n    strike({ freq, material = \"plastic\", bend = 1.01, at = 0, decay, gain }) {\n      const { partials, damping } = typeof material === \"string\" ? MATERIALS[material] : material;\n      for (const [ratio, level] of partials) {\n        if (freq * ratio * pitch * bend > ceiling) continue;\n        tone({\n          // Real objects are never perfectly tuned; a hair of detune per partial.\n          freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),\n          bend,\n          at,\n          attack: 0.001,\n          decay: decay / ratio ** damping,\n          gain: gain * level,\n        });\n      }\n    },\n  };\n}\n\n/** Turns a recipe into a playable sound. */\nexport function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {\n  const render = (target: SoundTarget) => {\n    const { context, destination } = target;\n    const output = context.createGain();\n    output.gain.value = MASTER_GAIN * target.volume;\n    output.connect(destination);\n    if (room > 0) {\n      const send = context.createGain();\n      send.gain.value = room * ROOM_GAIN;\n      output.connect(send).connect(roomFor(context, destination));\n    }\n    build(voiceFor(target, output));\n  };\n\n  return {\n    name,\n    duration,\n    render,\n    play({ volume = 1, pitch = 1 } = {}) {\n      const context = getAudioContext();\n      if (!context || volume <= 0) return;\n      const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;\n      render({\n        context,\n        // The page-wide volume is applied there.\n        destination: audioOutput(context),\n        when: context.currentTime + 0.005,\n        volume,\n        pitch: pitch * spread,\n      });\n    },\n  };\n}\n"},{"path":"lib/favicon.ts","type":"util","content":"/** Resolve a website URL to its conventional root favicon location. */\nexport function getFaviconUrl(value: string) {\n  try {\n    return new URL(\"/favicon.ico\", value).toString();\n  } catch {\n    return null;\n  }\n}\n"},{"path":"components/previews/agents/chat-app.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { Maximize2, Minimize2 } from \"lucide-react\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { ActionSwapIcon } from \"@/components/motion/action-swap\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { ChatAppExample } from \"@/components/previews/agents/chat-app-usage\";\nimport { cn } from \"@/lib/utils\";\n\nexport function ChatAppPreview() {\n  const [expanded, setExpanded] = useState(false);\n  const containerRef = useRef<HTMLDivElement>(null);\n  const toggleRef = useRef<HTMLButtonElement>(null);\n\n  useEffect(() => {\n    if (!expanded) return;\n    const container = containerRef.current;\n    if (!container) return;\n    const previousOverflow = document.body.style.overflow;\n    document.body.style.overflow = \"hidden\";\n    const isolated: Array<{\n      element: HTMLElement;\n      inert: boolean;\n      ariaHidden: string | null;\n    }> = [];\n    let branch: HTMLElement = container;\n    while (branch.parentElement) {\n      const parent = branch.parentElement;\n      for (const sibling of Array.from(parent.children)) {\n        if (sibling === branch || !(sibling instanceof HTMLElement)) continue;\n        isolated.push({\n          element: sibling,\n          inert: sibling.inert,\n          ariaHidden: sibling.getAttribute(\"aria-hidden\"),\n        });\n        sibling.inert = true;\n        sibling.setAttribute(\"aria-hidden\", \"true\");\n      }\n      if (parent === document.body) break;\n      branch = parent;\n    }\n\n    const focusableSelector = [\n      \"a[href]\",\n      \"button:not([disabled])\",\n      \"input:not([disabled])\",\n      \"select:not([disabled])\",\n      \"textarea:not([disabled])\",\n      \"[tabindex]:not([tabindex='-1'])\",\n    ].join(\",\");\n    const handleKeyDown = (event: KeyboardEvent) => {\n      if (event.key === \"Escape\") {\n        event.preventDefault();\n        setExpanded(false);\n        return;\n      }\n      if (event.key !== \"Tab\") return;\n      const focusable = Array.from(\n        container.querySelectorAll<HTMLElement>(focusableSelector),\n      ).filter((element) => !element.inert && element.offsetParent !== null);\n      const first = focusable[0];\n      const last = focusable.at(-1);\n      if (!first || !last) {\n        event.preventDefault();\n        container.focus();\n      } else if (event.shiftKey && document.activeElement === first) {\n        event.preventDefault();\n        last.focus();\n      } else if (!event.shiftKey && document.activeElement === last) {\n        event.preventDefault();\n        first.focus();\n      }\n    };\n    window.addEventListener(\"keydown\", handleKeyDown);\n    requestAnimationFrame(() =>\n      toggleRef.current?.focus({ preventScroll: true }),\n    );\n    return () => {\n      document.body.style.overflow = previousOverflow;\n      window.removeEventListener(\"keydown\", handleKeyDown);\n      for (const { element, inert, ariaHidden } of isolated) {\n        element.inert = inert;\n        if (ariaHidden === null) element.removeAttribute(\"aria-hidden\");\n        else element.setAttribute(\"aria-hidden\", ariaHidden);\n      }\n      requestAnimationFrame(() =>\n        toggleRef.current?.focus({ preventScroll: true }),\n      );\n    };\n  }, [expanded]);\n\n  const toggleExpanded = useCallback(() => {\n    setExpanded((current) => !current);\n  }, []);\n\n  return (\n    <div\n      ref={containerRef}\n      role=\"dialog\"\n      aria-modal={expanded || undefined}\n      aria-label=\"Chat app preview\"\n      tabIndex={expanded ? -1 : undefined}\n      className={cn(\n        \"relative w-full bg-background px-0 py-2 sm:p-3\",\n        expanded &&\n          \"fixed inset-0 z-[100] h-dvh overscroll-contain p-3 sm:p-4\",\n      )}\n    >\n      <Tooltip content={expanded ? \"Exit expanded preview\" : \"Expand preview\"} side=\"bottom\">\n      <button\n        ref={toggleRef}\n        type=\"button\"\n        onClick={toggleExpanded}\n        aria-label={expanded ? \"Exit expanded preview\" : \"Expand preview\"}\n        className=\"absolute top-5 right-24 z-50 grid size-10 place-items-center rounded-full border border-border/80 bg-background/90 text-muted-foreground backdrop-blur-sm transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2\"\n      >\n        <ActionSwapIcon\n          value={expanded ? \"minimize\" : \"maximize\"}\n          animation=\"blur\"\n        >\n          {expanded ? (\n            <Minimize2 className=\"size-4\" />\n          ) : (\n            <Maximize2 className=\"size-4\" />\n          )}\n        </ActionSwapIcon>\n      </button>\n      </Tooltip>\n      <ChatAppExample className={expanded ? \"h-full\" : undefined} />\n    </div>\n  );\n}\n"},{"path":"components/previews/agents/chat-app-usage.tsx","type":"util","content":"\"use client\";\n\nimport {\n  Bot,\n  Clock3,\n  FolderKanban,\n  MessageSquarePlus,\n  PanelLeft,\n  Paperclip,\n  Puzzle,\n  Search,\n  User,\n} from \"lucide-react\";\nimport { useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentProps,\n  useCallback,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { AgentActivity } from \"@/components/agents/agent-activity\";\nimport {\n  AISidebar,\n  type SidebarResource,\n} from \"@/components/agents/ai-sidebar\";\nimport {\n  ApprovalCard,\n  type ApprovalCardQuestion,\n  type ApprovalCardStatus,\n} from \"@/components/agents/approval-card\";\nimport { ChatApp } from \"@/components/agents/chat-app\";\nimport { CodeBlock } from \"@/components/agents/code-block\";\nimport { FileDiff } from \"@/components/agents/file-diff\";\nimport { ImageGeneration } from \"@/components/agents/image-generation\";\nimport { ThinkingShimmer } from \"@/components/agents/loading-states\";\nimport {\n  Message,\n  MessageAvatar,\n  MessageContent,\n  MessageFooter,\n  MessageGroup,\n  MessageHeader,\n} from \"@/components/agents/message\";\nimport {\n  MessageBubble,\n  MessageBubbleContent,\n} from \"@/components/agents/message-bubble\";\nimport { MessageScroller } from \"@/components/agents/message-scroller\";\nimport { PromptInput } from \"@/components/agents/prompt-input\";\nimport { StreamingResponse } from \"@/components/agents/streaming-response\";\nimport { type TodoItem, TodoList } from \"@/components/agents/todo-list\";\nimport {\n  ToolApproval,\n  ToolApprovalCode,\n  type ToolApprovalStatus,\n} from \"@/components/agents/tool-approval\";\nimport {\n  ToolResult,\n  ToolResultOutput,\n} from \"@/components/agents/tool-result\";\nimport {\n  AnimatedSidebar,\n  AnimatedSidebarContent,\n  AnimatedSidebarGroup,\n  AnimatedSidebarGroupContent,\n  AnimatedSidebarGroupLabel,\n  AnimatedSidebarInset,\n  AnimatedSidebarMenu,\n  AnimatedSidebarMenuButton,\n  AnimatedSidebarMenuItem,\n  AnimatedSidebarRail,\n  AnimatedSidebarTrigger,\n} from \"@/components/motion/animated-sidebar\";\nimport { cn } from \"@/lib/utils\";\n\nconst resources: SidebarResource[] = [\n  {\n    id: \"release\",\n    label: \"Release workspace\",\n    kind: \"project\",\n    children: [\n      { id: \"checkout\", label: \"Checkout audit\", kind: \"file\" },\n      { id: \"release-notes\", label: \"Release notes\", kind: \"file\" },\n      { id: \"references\", label: \"Research sources\", kind: \"bookmark\" },\n    ],\n  },\n  {\n    id: \"design\",\n    label: \"Design system\",\n    kind: \"folder\",\n    children: [\n      { id: \"tokens\", label: \"Motion tokens\", kind: \"file\" },\n      { id: \"components\", label: \"Component inventory\", kind: \"file\" },\n    ],\n  },\n  { id: \"archive\", label: \"Archived runs\", kind: \"folder\" },\n];\n\nconst diffLines = [\n  {\n    id: \"context-1\",\n    type: \"context\" as const,\n    oldLine: 41,\n    newLine: 41,\n    content: \"  const total = subtotal + shipping;\",\n  },\n  {\n    id: \"removed-1\",\n    type: \"removed\" as const,\n    oldLine: 42,\n    content: \"  return submitOrder(total);\",\n  },\n  {\n    id: \"added-1\",\n    type: \"added\" as const,\n    newLine: 42,\n    content: \"  const result = validateOrder({ total, items });\",\n  },\n  {\n    id: \"added-2\",\n    type: \"added\" as const,\n    newLine: 43,\n    content: \"  return result.ok ? submitOrder(total) : result;\",\n  },\n];\n\nconst approvalQuestions: ApprovalCardQuestion[] = [\n  {\n    id: \"release\",\n    title: \"How should the patch be released?\",\n    options: [\n      { value: \"focused\", label: \"Ship the focused checkout fix\" },\n      { value: \"bundle\", label: \"Bundle it with the next release\" },\n    ],\n    allowCustom: true,\n    customPlaceholder: \"Add another release instruction…\",\n  },\n];\n\nconst reply =\n  \"I’ll keep the patch focused, preserve the current checkout layout, and run the same validation path before preparing the release.\";\n\ninterface AddedMessage {\n  id: string;\n  from: \"user\" | \"assistant\";\n  content: string;\n  streaming?: boolean;\n}\n\nfunction GeneratedPreview() {\n  return (\n    <svg\n      viewBox=\"0 0 640 420\"\n      aria-hidden=\"true\"\n      className=\"size-full\"\n    >\n      <rect width=\"640\" height=\"420\" fill=\"currentColor\" className=\"text-muted\" />\n      <rect x=\"64\" y=\"52\" width=\"512\" height=\"316\" rx=\"28\" fill=\"currentColor\" className=\"text-background\" />\n      <circle cx=\"320\" cy=\"144\" r=\"38\" fill=\"currentColor\" className=\"text-emerald-500\" />\n      <path d=\"m301 144 13 13 26-29\" fill=\"none\" stroke=\"white\" strokeWidth=\"9\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n      <rect x=\"204\" y=\"210\" width=\"232\" height=\"18\" rx=\"9\" fill=\"currentColor\" className=\"text-foreground/85\" />\n      <rect x=\"238\" y=\"246\" width=\"164\" height=\"12\" rx=\"6\" fill=\"currentColor\" className=\"text-muted-foreground/35\" />\n      <rect x=\"248\" y=\"298\" width=\"144\" height=\"34\" rx=\"17\" fill=\"currentColor\" className=\"text-foreground\" />\n    </svg>\n  );\n}\n\nfunction AssistantIdentity({ label = \"beUI Agent\" }: { label?: string }) {\n  return (\n    <MessageHeader>\n      <span>{label}</span>\n      <span>Now</span>\n    </MessageHeader>\n  );\n}\n\nexport function ChatAppExample({\n  className,\n}: Pick<ComponentProps<typeof ChatApp>, \"className\">) {\n  const reduce = useReducedMotion() ?? false;\n  const toolTimers = useRef<number[]>([]);\n  const chatTimers = useRef<number[]>([]);\n  const approvalTimers = useRef<number[]>([]);\n  const runId = useRef(0);\n  const [items, setItems] = useState(resources);\n  const [activeResource, setActiveResource] = useState(\"checkout\");\n  const [input, setInput] = useState(\"\");\n  const [pending, setPending] = useState(false);\n  const [activeReply, setActiveReply] = useState<string | null>(null);\n  const [messages, setMessages] = useState<AddedMessage[]>([]);\n  const [toolStatus, setToolStatus] = useState<ToolApprovalStatus>(\"pending\");\n  const [approvalStatus, setApprovalStatus] =\n    useState<ApprovalCardStatus>(\"pending\");\n\n  const clearToolTimers = useCallback(() => {\n    toolTimers.current.forEach(window.clearTimeout);\n    toolTimers.current = [];\n  }, []);\n\n  const clearChatTimers = useCallback(() => {\n    chatTimers.current.forEach(window.clearTimeout);\n    chatTimers.current = [];\n  }, []);\n\n  const clearApprovalTimers = useCallback(() => {\n    approvalTimers.current.forEach(window.clearTimeout);\n    approvalTimers.current = [];\n  }, []);\n\n  useEffect(\n    () => () => {\n      clearToolTimers();\n      clearChatTimers();\n      clearApprovalTimers();\n    },\n    [clearApprovalTimers, clearChatTimers, clearToolTimers],\n  );\n\n  const plan = useMemo<TodoItem[]>(() => {\n    const checksStatus =\n      toolStatus === \"complete\"\n        ? \"completed\"\n        : toolStatus === \"running\"\n          ? \"in-progress\"\n          : toolStatus === \"denied\" || toolStatus === \"error\"\n            ? \"cancelled\"\n            : \"pending\";\n    return [\n      { id: \"inspect\", title: \"Inspect the checkout flow\", status: \"completed\" },\n      { id: \"patch\", title: \"Prepare the validation patch\", status: \"completed\" },\n      { id: \"checks\", title: \"Run focused checks\", status: checksStatus },\n      {\n        id: \"review\",\n        title: \"Collect release approval\",\n        status: toolStatus === \"complete\" ? \"in-progress\" : \"pending\",\n      },\n    ];\n  }, [toolStatus]);\n\n  useEffect(() => {\n    if (!activeReply) return;\n\n    if (reduce) {\n      setMessages((current) =>\n        current.map((message) =>\n          message.id === activeReply\n            ? { ...message, content: reply, streaming: false }\n            : message,\n        ),\n      );\n      setActiveReply(null);\n      return;\n    }\n\n    const startedAt = performance.now();\n    let frame = 0;\n    const stream = (now: number) => {\n      const cursor = Math.min(\n        reply.length,\n        Math.floor(((now - startedAt) / 1000) * 92),\n      );\n      const content = reply.slice(0, cursor);\n      setMessages((current) =>\n        current.map((message) =>\n          message.id === activeReply && message.content !== content\n            ? { ...message, content }\n            : message,\n        ),\n      );\n\n      if (cursor < reply.length) {\n        frame = requestAnimationFrame(stream);\n      } else {\n        setMessages((current) =>\n          current.map((message) =>\n            message.id === activeReply\n              ? { ...message, streaming: false }\n              : message,\n          ),\n        );\n        setActiveReply(null);\n      }\n    };\n\n    frame = requestAnimationFrame(stream);\n    return () => cancelAnimationFrame(frame);\n  }, [activeReply, reduce]);\n\n  const approveTool = () => {\n    clearToolTimers();\n    setToolStatus(\"approving\");\n    toolTimers.current = [\n      window.setTimeout(() => setToolStatus(\"approved\"), 450),\n      window.setTimeout(() => setToolStatus(\"running\"), 850),\n      window.setTimeout(() => setToolStatus(\"complete\"), 1650),\n    ];\n  };\n\n  const submit = (value: string) => {\n    if (!value.trim() || pending || activeReply) return;\n    const id = runId.current++;\n    const assistantId = `assistant-${id}`;\n    setMessages((current) => [\n      ...current,\n      { id: `user-${id}`, from: \"user\", content: value },\n    ]);\n    setInput(\"\");\n    setPending(true);\n    chatTimers.current.push(\n      window.setTimeout(() => {\n        setMessages((current) => [\n          ...current,\n          {\n            id: assistantId,\n            from: \"assistant\",\n            content: \"\",\n            streaming: true,\n          },\n        ]);\n        setPending(false);\n        setActiveReply(assistantId);\n      }, reduce ? 0 : 420),\n    );\n  };\n\n  const stop = () => {\n    clearChatTimers();\n    setPending(false);\n    setMessages((current) =>\n      current.map((message) =>\n        message.streaming ? { ...message, streaming: false } : message,\n      ),\n    );\n    setActiveReply(null);\n  };\n\n  const busy = pending || activeReply !== null;\n\n  return (\n    <ChatApp sidebarWidth=\"17rem\" className={cn(\"h-[760px]\", className)}>\n      <AnimatedSidebar\n        ariaLabel=\"Agent workspace\"\n        collapsible=\"offcanvas\"\n        className=\"min-h-0\"\n        panelClassName=\"h-full bg-background\"\n      >\n        <AnimatedSidebarContent className=\"gap-4 overflow-hidden px-2 py-4\">\n          <AnimatedSidebarGroup className=\"shrink-0 px-1 py-0\">\n            <AnimatedSidebarGroupContent>\n              <AnimatedSidebarMenu className=\"gap-1\">\n                {[\n                  { label: \"New task\", icon: MessageSquarePlus },\n                  { label: \"Search\", icon: Search },\n                  { label: \"Runs\", icon: Clock3 },\n                ].map(({ label, icon: Icon }) => (\n                  <AnimatedSidebarMenuItem key={label}>\n                    <AnimatedSidebarMenuButton\n                      icon={<Icon className=\"size-4\" />}\n                      onSelect={() => {}}\n                      className=\"font-normal\"\n                    >\n                      {label}\n                    </AnimatedSidebarMenuButton>\n                  </AnimatedSidebarMenuItem>\n                ))}\n              </AnimatedSidebarMenu>\n            </AnimatedSidebarGroupContent>\n          </AnimatedSidebarGroup>\n\n          <AnimatedSidebarGroup className=\"min-h-0 flex-1 px-1 py-0\">\n            <AnimatedSidebarGroupLabel className=\"mb-1 h-8 px-2 text-xs font-medium normal-case tracking-normal\">\n              Projects\n            </AnimatedSidebarGroupLabel>\n            <AnimatedSidebarGroupContent className=\"relative min-h-0 flex-1 overflow-hidden\">\n              <div className=\"h-full overflow-y-auto overscroll-contain pb-8 [overflow-anchor:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\">\n                <AISidebar\n                  items={items}\n                  activeId={activeResource}\n                  defaultExpandedIds={[\"release\", \"design\"]}\n                  onActiveChange={setActiveResource}\n                  onItemsChange={setItems}\n                />\n              </div>\n              <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-background to-transparent\" />\n            </AnimatedSidebarGroupContent>\n          </AnimatedSidebarGroup>\n        </AnimatedSidebarContent>\n        <AnimatedSidebarRail />\n      </AnimatedSidebar>\n\n      <AnimatedSidebarInset className=\"min-h-0 bg-background\">\n        <header className=\"flex h-14 shrink-0 items-center justify-between border-border border-b px-4\">\n          <div className=\"flex min-w-0 items-center gap-2.5\">\n            <AnimatedSidebarTrigger className=\"text-muted-foreground hover:bg-muted hover:text-foreground\">\n              <PanelLeft className=\"size-4\" />\n            </AnimatedSidebarTrigger>\n            <div className=\"min-w-0\">\n              <p className=\"truncate text-sm font-medium text-foreground\">\n                Checkout release\n              </p>\n              <p className=\"truncate text-[11px] text-muted-foreground\">\n                Agent workspace · focused patch\n              </p>\n            </div>\n          </div>\n          <span className=\"rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11px] font-medium text-emerald-600 dark:text-emerald-400\">\n            Connected\n          </span>\n        </header>\n\n        <MessageScroller\n          busy={busy}\n          navigation=\"rail\"\n          className=\"min-h-0 flex-1\"\n          viewportClassName=\"px-3 py-5 sm:px-5\"\n          contentClassName=\"mx-auto min-h-full w-full max-w-3xl\"\n        >\n          <MessageGroup spacing=\"default\">\n            <Message from=\"user\">\n              <MessageAvatar><User /></MessageAvatar>\n              <MessageContent>\n                <MessageHeader><span>You</span><span>10:24</span></MessageHeader>\n                <MessageBubble variant=\"solid\">\n                  <MessageBubbleContent>\n                    Audit the checkout flow, fix the validation gap, and prepare a release-ready patch.\n                  </MessageBubbleContent>\n                </MessageBubble>\n              </MessageContent>\n            </Message>\n\n            <Message from=\"assistant\">\n              <MessageAvatar><Bot /></MessageAvatar>\n              <MessageContent className=\"gap-3\">\n                <MessageHeader><span>beUI Agent</span><span>10:24</span></MessageHeader>\n                <AgentActivity\n                  status=\"complete\"\n                  duration={6}\n                  defaultOpen\n                  collapseOnComplete={false}\n                  items={[\n                    { id: \"reason\", type: \"text\", content: \"Tracing the checkout submission path and validation boundary.\" },\n                    { id: \"read\", type: \"tool\", action: \"read\", target: \"checkout/submit.ts\" },\n                    { id: \"search\", type: \"search\", query: \"order validation failures\", results: [\n                      { id: \"result-1\", title: \"Agent interface guide\", domain: \"beui.dev\", url: \"/docs/ai-agents\" },\n                    ] },\n                  ]}\n                />\n                <TodoList items={plan} title=\"Release plan\" collapseOnComplete={false} />\n              </MessageContent>\n            </Message>\n\n            <Message from=\"assistant\">\n              <MessageAvatar placeholder />\n              <MessageContent>\n                <ToolApproval\n                  tool=\"terminal.run\"\n                  title=\"Run focused checkout checks?\"\n                  description=\"The agent needs permission to run the validation and accessibility suites.\"\n                  status={toolStatus}\n                  defaultOpen\n                  parameters={[\n                    {\n                      id: \"command\",\n                      label: \"Command\",\n                      value: (\n                        <ToolApprovalCode\n                          code=\"bun test checkout --coverage\"\n                          language=\"bash\"\n                        />\n                      ),\n                    },\n                    { id: \"scope\", label: \"Scope\", value: \"Current workspace\" },\n                  ]}\n                  onApprove={approveTool}\n                  onAlwaysAllow={approveTool}\n                  onDeny={() => {\n                    clearToolTimers();\n                    setToolStatus(\"denied\");\n                  }}\n                />\n              </MessageContent>\n            </Message>\n\n            {toolStatus === \"running\" || toolStatus === \"complete\" ? (\n              <Message from=\"assistant\" animateIn>\n                <MessageAvatar placeholder />\n                <MessageContent className=\"gap-3\">\n                  <ToolResult\n                    tool=\"terminal.run\"\n                    title={\n                      toolStatus === \"running\"\n                        ? \"Running checkout checks\"\n                        : \"Checkout checks passed\"\n                    }\n                    status={toolStatus === \"running\" ? \"running\" : \"success\"}\n                    kind=\"terminal\"\n                    meta={toolStatus === \"running\" ? \"Live\" : \"2.8s\"}\n                    defaultOpen\n                    collapseOnComplete={false}\n                  >\n                    <ToolResultOutput>\n                      {toolStatus === \"running\"\n                        ? \"✓ validation contract\\n… checkout keyboard flow\"\n                        : \"✓ validation contract\\n✓ checkout keyboard flow\\n✓ order submission recovery\"}\n                    </ToolResultOutput>\n                  </ToolResult>\n                  {toolStatus === \"complete\" ? (\n                    <>\n                      <FileDiff\n                        file=\"checkout/submit.ts\"\n                        lines={diffLines}\n                        status=\"complete\"\n                        defaultOpen\n                        collapseOnComplete={false}\n                      />\n                      <CodeBlock\n                        filename=\"validation.ts\"\n                        language=\"typescript\"\n                        status=\"complete\"\n                        code={\"export function validateOrder(order: Order) {\\n  return schema.safeParse(order);\\n}\"}\n                        showLineNumbers\n                      />\n                    </>\n                  ) : null}\n                </MessageContent>\n              </Message>\n            ) : toolStatus === \"denied\" || toolStatus === \"error\" ? (\n              <Message from=\"assistant\" animateIn>\n                <MessageAvatar placeholder />\n                <MessageContent>\n                  <ToolResult\n                    tool=\"terminal.run\"\n                    title=\"Checkout checks were not run\"\n                    status={toolStatus === \"denied\" ? \"cancelled\" : \"error\"}\n                    kind=\"terminal\"\n                    defaultOpen\n                    collapseOnComplete={false}\n                  >\n                    <ToolResultOutput>\n                      {toolStatus === \"denied\"\n                        ? \"Permission was not granted. No command was run.\"\n                        : \"The command could not be completed.\"}\n                    </ToolResultOutput>\n                  </ToolResult>\n                </MessageContent>\n              </Message>\n            ) : null}\n\n            {toolStatus === \"complete\" ? (\n              <Message from=\"assistant\" animateIn>\n                <MessageAvatar placeholder />\n                <MessageContent className=\"gap-3\">\n                  <ImageGeneration\n                    status=\"complete\"\n                    prompt=\"a clear checkout confirmation screen\"\n                    resolution=\"1280 × 840\"\n                    size=\"compact\"\n                  >\n                    <GeneratedPreview />\n                  </ImageGeneration>\n                  <MessageBubble variant=\"ghost\" className=\"w-full\">\n                    <MessageBubbleContent>\n                      <StreamingResponse\n                        status=\"complete\"\n                        copyText=\"The checkout patch is ready for review.\"\n                        sources={[\n                          {\n                            id: \"message\",\n                            title: \"Message composition\",\n                            domain: \"beui.dev\",\n                            url: \"/components/agents/message\",\n                          },\n                          {\n                            id: \"diff\",\n                            title: \"File Diff\",\n                            domain: \"beui.dev\",\n                            url: \"/components/agents/file-diff\",\n                          },\n                          {\n                            id: \"approval\",\n                            title: \"Tool Approval\",\n                            domain: \"beui.dev\",\n                            url: \"/components/agents/tool-approval\",\n                          },\n                        ]}\n                      >\n                        <p>The checkout patch is ready for review.</p>\n                        <ul>\n                          <li>Validation now runs before submission.</li>\n                          <li>Failure output stays inside the current flow.</li>\n                          <li>\n                            Focused checks pass without changing the layout.\n                          </li>\n                        </ul>\n                      </StreamingResponse>\n                    </MessageBubbleContent>\n                  </MessageBubble>\n                </MessageContent>\n              </Message>\n            ) : null}\n\n            {toolStatus === \"complete\" ? (\n              <Message from=\"assistant\" animateIn>\n                <MessageAvatar placeholder />\n                <MessageContent>\n                  <ApprovalCard\n                    questions={approvalQuestions}\n                    status={approvalStatus}\n                    onSubmit={() => {\n                      setApprovalStatus(\"submitting\");\n                      clearApprovalTimers();\n                      approvalTimers.current.push(\n                        window.setTimeout(\n                          () => setApprovalStatus(\"answered\"),\n                          650,\n                        ),\n                      );\n                    }}\n                    result=\"Release direction sent to the agent.\"\n                  />\n                </MessageContent>\n              </Message>\n            ) : null}\n\n            {messages.map((message) => (\n              <Message key={message.id} from={message.from} animateIn>\n                {message.from === \"assistant\" ? (\n                  <MessageAvatar><Bot /></MessageAvatar>\n                ) : (\n                  <MessageAvatar><User /></MessageAvatar>\n                )}\n                <MessageContent>\n                  {message.from === \"assistant\" ? <AssistantIdentity label=\"beUI Agent\" /> : null}\n                  <MessageBubble variant={message.from === \"user\" ? \"solid\" : \"soft\"}>\n                    <MessageBubbleContent>\n                      {message.from === \"assistant\" ? (\n                        <StreamingResponse status={message.streaming ? \"streaming\" : \"complete\"} showActions={!message.streaming} copyText={message.content}>\n                          {message.content}\n                        </StreamingResponse>\n                      ) : message.content}\n                    </MessageBubbleContent>\n                  </MessageBubble>\n                  {message.from === \"user\" ? <MessageFooter>Sent</MessageFooter> : null}\n                </MessageContent>\n              </Message>\n            ))}\n\n            {pending ? (\n              <Message from=\"assistant\" animateIn>\n                <MessageAvatar><Bot /></MessageAvatar>\n                <MessageContent>\n                  <ThinkingShimmer>Reviewing your direction</ThinkingShimmer>\n                </MessageContent>\n              </Message>\n            ) : null}\n          </MessageGroup>\n        </MessageScroller>\n\n        <div className=\"shrink-0 border-border border-t bg-background p-3\">\n          <div className=\"mx-auto max-w-3xl\">\n            <PromptInput\n              value={input}\n              onValueChange={setInput}\n              loading={busy}\n              onStop={stop}\n              onSubmit={submit}\n              minRows={1}\n              maxRows={4}\n              placeholder=\"Ask the agent to continue…\"\n              models={[\n                { value: \"balanced\", label: \"Balanced\" },\n                { value: \"fast\", label: \"Fast\" },\n                { value: \"deep\", label: \"Deep reasoning\" },\n              ]}\n              defaultModel=\"balanced\"\n              actions={[\n                { value: \"attach\", label: \"Attach file\", icon: <Paperclip /> },\n                { value: \"project\", label: \"Add project context\", icon: <FolderKanban /> },\n                { value: \"skill\", label: \"Use a skill\", icon: <Puzzle /> },\n              ]}\n            />\n          </div>\n        </div>\n      </AnimatedSidebarInset>\n    </ChatApp>\n  );\n}\n"},{"path":"components/agents/loading-states/index.ts","type":"util","content":"export {\n  AgentProgress,\n  type AgentProgressProps,\n} from \"./agent-progress\";\nexport {\n  type LoadingStatesMessages,\n  loadingStatesMessages,\n} from \"./messages\";\nexport {\n  ReasoningText,\n  type ReasoningTextProps,\n  type ReasoningTextVariant,\n} from \"./reasoning-text\";\nexport {\n  ThinkingShimmer,\n  type ThinkingShimmerProps,\n} from \"./thinking-shimmer\";\n"},{"path":"components/agents/loading-states/agent-progress.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { useEffect, useState } from \"react\";\nimport { EASE_IN_OUT } from \"@/lib/ease\";\nimport { useLocale, useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\nimport { type LoadingStatesMessages, loadingStatesMessages } from \"./messages\";\n\nconst GRID_CELLS = [\n  { id: \"top-left\", delay: 0 },\n  { id: \"top-center\", delay: 0.14 },\n  { id: \"top-right\", delay: 0.28 },\n  { id: \"middle-left\", delay: 0.42 },\n  { id: \"middle-center\", delay: 0.56 },\n  { id: \"middle-right\", delay: 0.7 },\n  { id: \"bottom-left\", delay: 0.84 },\n  { id: \"bottom-center\", delay: 0.98 },\n  { id: \"bottom-right\", delay: 1.12 },\n];\n\nexport interface AgentProgressProps {\n  /** Verb describing the agent's current activity. */\n  label?: string;\n  /** Controlled elapsed time in seconds. */\n  elapsedSeconds?: number;\n  /** Starting time for the internal timer, in seconds. */\n  initialSeconds?: number;\n  /** Whether the internal timer should advance. Ignored when elapsedSeconds is provided. */\n  running?: boolean;\n  /** Override any built-in string. `{label}` fills `inProgress`. */\n  labels?: Partial<LoadingStatesMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nfunction formatElapsed(totalSeconds: number, locale?: string) {\n  const safeSeconds = Math.max(0, totalSeconds);\n  const minutes = Math.floor(safeSeconds / 60);\n  const remainder = safeSeconds % 60;\n\n  // Without a locale keep the exact English text so server and client match.\n  if (!locale) {\n    const seconds = remainder.toFixed(1);\n    return minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;\n  }\n\n  const seconds = new Intl.NumberFormat(locale, {\n    style: \"unit\",\n    unit: \"second\",\n    unitDisplay: \"narrow\",\n    minimumFractionDigits: 1,\n    maximumFractionDigits: 1,\n  }).format(remainder);\n  if (minutes === 0) return seconds;\n  const minuteText = new Intl.NumberFormat(locale, {\n    style: \"unit\",\n    unit: \"minute\",\n    unitDisplay: \"narrow\",\n  }).format(minutes);\n  return `${minuteText} ${seconds}`;\n}\n\nexport function AgentProgress({\n  label: labelProp,\n  elapsedSeconds,\n  initialSeconds = 0,\n  running = true,\n  labels,\n  className,\n}: AgentProgressProps) {\n  const t = useMessages(\"loadingStates\", loadingStatesMessages, labels);\n  const { locale } = useLocale();\n  const label = labelProp ?? t(\"churning\");\n  const reduce = useReducedMotion() ?? false;\n  const [internalSeconds, setInternalSeconds] = useState(initialSeconds);\n\n  useEffect(() => {\n    if (elapsedSeconds !== undefined || !running) return;\n\n    const startedAt = performance.now() - initialSeconds * 1000;\n    const timer = window.setInterval(() => {\n      setInternalSeconds((performance.now() - startedAt) / 1000);\n    }, 100);\n\n    return () => window.clearInterval(timer);\n  }, [elapsedSeconds, initialSeconds, running]);\n\n  const elapsed = elapsedSeconds ?? internalSeconds;\n\n  return (\n    <span\n      role=\"status\"\n      aria-label={t(\"inProgress\", { label })}\n      className={cn(\n        \"inline-flex items-center gap-3 font-mono text-sm text-muted-foreground\",\n        className,\n      )}\n    >\n      <span\n        aria-hidden=\"true\"\n        className=\"grid size-5 shrink-0 grid-cols-3 gap-[2px]\"\n      >\n        {GRID_CELLS.map(({ id, delay }) => (\n          <motion.span\n            key={id}\n            className=\"rounded-[1px] bg-current\"\n            animate={\n              reduce\n                ? { opacity: [0.35, 0.8, 0.35] }\n                : {\n                    opacity: [0.28, 1, 0.28],\n                    scale: [0.72, 1, 0.72],\n                  }\n            }\n            transition={{\n              duration: 1.55,\n              ease: EASE_IN_OUT,\n              repeat: Infinity,\n              delay,\n            }}\n          />\n        ))}\n      </span>\n      <span className=\"font-sans font-medium\">{label}</span>\n      <span\n        aria-hidden=\"true\"\n        className=\"tabular-nums text-muted-foreground/70\"\n      >\n        {formatElapsed(elapsed, locale)}\n      </span>\n    </span>\n  );\n}\n"},{"path":"components/agents/loading-states/reasoning-text.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { type ReactNode, useEffect, useId, useState } from \"react\";\nimport { Loader } from \"@/components/motion/loader\";\nimport { TextScramble } from \"@/components/motion/text-scramble\";\nimport { EASE_OUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport {\n  TEXT_SHIMMER_CLASS_NAME,\n  TEXT_SHIMMER_HIGHLIGHT_CLASS_NAME,\n  TEXT_SHIMMER_KEYFRAMES,\n  textShimmerStyle,\n} from \"@/lib/text-shimmer\";\nimport { cn } from \"@/lib/utils\";\nimport { type LoadingStatesMessages, loadingStatesMessages } from \"./messages\";\n\nconst CASCADE_STAGGER = 0.025;\n\nexport type ReasoningTextVariant = \"cascade\" | \"swap\" | \"scramble\";\n\nexport interface ReasoningTextProps {\n  /** Phrases cycled through while the agent works. */\n  phrases?: string[];\n  /** Animation used when the active phrase changes. */\n  variant?: ReasoningTextVariant;\n  /** Milliseconds each phrase remains visible. */\n  interval?: number;\n  /** Seconds taken for one shimmer pass. */\n  shimmerDuration?: number;\n  /** Optional leading visual. Defaults to a terminal-style ASCII loader. */\n  indicator?: ReactNode;\n  /** Override any built-in string, including the default phrases. */\n  labels?: Partial<LoadingStatesMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\ntype PhraseProps = {\n  phrase: string;\n  reduce: boolean;\n  shimmerDuration: number;\n};\n\nfunction CascadePhrase({\n  phrase,\n  reduce,\n  shimmerDuration,\n}: PhraseProps) {\n  const text = `${phrase}…`;\n\n  if (reduce) {\n    return (\n      <span\n        className={cn(\n          \"col-start-1 row-start-1 inline-block justify-self-start whitespace-pre\",\n          TEXT_SHIMMER_CLASS_NAME,\n        )}\n        style={textShimmerStyle(shimmerDuration)}\n      >\n        {text}\n      </span>\n    );\n  }\n\n  // The letters land plain; one highlight layer over the whole phrase carries\n  // the shimmer, so it sweeps across instead of every letter pulsing at once.\n  // It fades in as the last letter settles.\n  const settle = text.length * CASCADE_STAGGER + 0.2;\n\n  return (\n    <AnimatePresence initial={false}>\n      <motion.span\n        key={phrase}\n        className=\"relative col-start-1 row-start-1 inline-block justify-self-start whitespace-pre [font-kerning:none] [font-variant-ligatures:none]\"\n        initial=\"initial\"\n        animate=\"animate\"\n        exit=\"exit\"\n      >\n        {text.split(\"\").map((character, characterIndex) => (\n          <motion.span\n            // biome-ignore lint/suspicious/noArrayIndexKey: position is the stable cascade slot identity.\n            key={characterIndex}\n            custom={characterIndex * CASCADE_STAGGER}\n            // Own states: a phrase that cycles back re-enters mid-exit, and\n            // only owned targets are restored.\n            initial=\"initial\"\n            animate=\"animate\"\n            exit=\"exit\"\n            variants={{\n              initial: { opacity: 0, y: \"100%\" },\n              animate: (delay: number) => ({\n                opacity: 1,\n                y: \"0%\",\n                transition: { ...SPRING_SWAP, delay },\n              }),\n              exit: (delay: number) => ({\n                opacity: 0,\n                y: \"-100%\",\n                transition: {\n                  duration: 0.14,\n                  ease: EASE_OUT,\n                  delay: delay * 0.45,\n                },\n              }),\n            }}\n            className=\"inline-block whitespace-pre text-muted-foreground will-change-[opacity,transform]\"\n          >\n            {character}\n          </motion.span>\n        ))}\n        <motion.span\n          aria-hidden=\"true\"\n          variants={{\n            initial: { opacity: 0 },\n            animate: { opacity: 1, transition: { duration: 0.3, ease: EASE_OUT, delay: settle } },\n            exit: { opacity: 0, transition: { duration: 0.1, ease: EASE_OUT } },\n          }}\n          className={cn(\n            \"pointer-events-none absolute inset-0 whitespace-pre\",\n            TEXT_SHIMMER_HIGHLIGHT_CLASS_NAME,\n          )}\n          style={textShimmerStyle(shimmerDuration)}\n        >\n          {text}\n        </motion.span>\n      </motion.span>\n    </AnimatePresence>\n  );\n}\n\nfunction SwapPhrase({ phrase, reduce, shimmerDuration }: PhraseProps) {\n  return (\n    <AnimatePresence initial={false}>\n      <motion.span\n        key={phrase}\n        className={cn(\n          \"col-start-1 row-start-1 inline-block justify-self-start whitespace-nowrap will-change-[opacity,transform]\",\n          TEXT_SHIMMER_CLASS_NAME,\n        )}\n        style={textShimmerStyle(shimmerDuration)}\n        initial={reduce ? { opacity: 0 } : { opacity: 0, y: 3 }}\n        animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0 }}\n        exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3 }}\n        transition={{\n          duration: reduce ? 0.12 : 0.2,\n          ease: EASE_OUT,\n        }}\n      >\n        {phrase}…\n      </motion.span>\n    </AnimatePresence>\n  );\n}\n\nfunction ScramblePhrase({\n  phrase,\n  shimmerDuration,\n}: PhraseProps) {\n  const target = `${phrase}…`;\n\n  return (\n    <TextScramble\n      text={target}\n      className={cn(\n        \"col-start-1 row-start-1 justify-self-start tabular-nums\",\n        TEXT_SHIMMER_CLASS_NAME,\n      )}\n      style={textShimmerStyle(shimmerDuration)}\n    />\n  );\n}\n\nexport function ReasoningText({\n  phrases,\n  variant = \"cascade\",\n  interval = 1800,\n  shimmerDuration = 2.2,\n  indicator,\n  labels,\n  className,\n}: ReasoningTextProps) {\n  const t = useMessages(\"loadingStates\", loadingStatesMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const [index, setIndex] = useState(0);\n  const statusId = useId();\n  const safePhrases =\n    phrases && phrases.length > 0\n      ? phrases\n      : [\n          t(\"phraseThinking\"),\n          t(\"phraseReading\"),\n          t(\"phraseConnecting\"),\n          t(\"phraseForming\"),\n        ];\n  const phrase = safePhrases[index % safePhrases.length];\n  const longestPhrase = safePhrases.reduce((longest, current) =>\n    current.length > longest.length ? current : longest,\n  );\n  const phraseProps = { phrase, reduce, shimmerDuration };\n\n  useEffect(() => {\n    if (safePhrases.length < 2) return;\n\n    const timer = window.setInterval(() => {\n      setIndex((current) => (current + 1) % safePhrases.length);\n    }, Math.max(600, interval));\n\n    return () => window.clearInterval(timer);\n  }, [interval, safePhrases.length]);\n\n  return (\n    <>\n      <style>{TEXT_SHIMMER_KEYFRAMES}</style>\n      <span\n        role=\"status\"\n        aria-live=\"polite\"\n        aria-labelledby={statusId}\n        className={cn(\n          \"inline-flex items-center gap-2 text-sm font-medium text-muted-foreground\",\n          className,\n        )}\n      >\n        <span aria-hidden=\"true\" className=\"inline-flex size-3 shrink-0 items-center justify-center\">\n          {indicator ?? (\n            <Loader\n              variant=\"ascii-line\"\n              size={14}\n              speed={0.8}\n              label={t(\"reasoning\")}\n            />\n          )}\n        </span>\n\n        <span aria-hidden=\"true\" className=\"grid overflow-hidden text-left\">\n          <span className=\"invisible col-start-1 row-start-1 whitespace-nowrap\">\n            {longestPhrase}…\n          </span>\n          {variant === \"cascade\" ? (\n            <CascadePhrase {...phraseProps} />\n          ) : variant === \"scramble\" ? (\n            <ScramblePhrase {...phraseProps} />\n          ) : (\n            <SwapPhrase {...phraseProps} />\n          )}\n        </span>\n\n        <span id={statusId} className=\"sr-only\">\n          {phrase}\n        </span>\n      </span>\n    </>\n  );\n}\n"},{"path":"components/motion/loader.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { useEffect, useId, useState } from \"react\";\nimport { EASE_IN_OUT } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport type LoaderVariant =\n  | \"spinner\"\n  | \"dots\"\n  | \"bars\"\n  | \"dot-matrix\"\n  | \"dither\"\n  | \"ascii\"\n  | \"ascii-line\"\n  | \"ascii-braille\"\n  | \"ascii-blocks\"\n  | \"ascii-bounce\"\n  | \"morph\"\n  | \"comet\"\n  | \"scramble\"\n  | \"metaballs\"\n  | \"newton\"\n  | \"helix\"\n  | \"percent\";\n\n// Terminal-style frame sets - the loaders CLI AI agents cycle through.\nconst ASCII_SETS: Record<string, string[]> = {\n  ascii: [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"],\n  \"ascii-line\": [\"|\", \"/\", \"-\", \"\\\\\"],\n  \"ascii-braille\": [\"⣾\", \"⣽\", \"⣻\", \"⢿\", \"⡿\", \"⣟\", \"⣯\", \"⣷\"],\n  \"ascii-blocks\": [\"▁\", \"▂\", \"▃\", \"▄\", \"▅\", \"▆\", \"▇\", \"█\", \"▇\", \"▆\", \"▅\", \"▄\", \"▃\", \"▂\"],\n  \"ascii-bounce\": [\"⠁\", \"⠂\", \"⠄\", \"⡀\", \"⢀\", \"⠠\", \"⠐\", \"⠈\"],\n};\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const loaderMessages = {\n  label: \"Loading\",\n  /** The word the `scramble` variant resolves to. */\n  scramble: \"LOADING\",\n};\n\nexport type LoaderMessages = typeof loaderMessages;\n\nexport interface LoaderProps {\n  /** Which animation to render. */\n  variant?: LoaderVariant;\n  /** Base square size in px. Everything scales from this. */\n  size?: number;\n  /** Seconds per animation cycle. */\n  speed?: number;\n  /** Accessible label announced to screen readers. */\n  label?: string;\n  /** Override any built-in string. */\n  labels?: Partial<LoaderMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\n// Reduced motion keeps a calm opacity pulse and drops every transform.\nconst REDUCED = {\n  animate: { opacity: [1, 0.4, 1] },\n  transition: { duration: 1.4, ease: EASE_IN_OUT, repeat: Infinity },\n};\n\nexport function Loader({\n  variant = \"spinner\",\n  size = 32,\n  speed = 1,\n  label: labelProp,\n  labels,\n  className,\n}: LoaderProps) {\n  const t = useMessages(\"loader\", loaderMessages, labels);\n  const label = labelProp ?? t(\"label\");\n  const reduce = useReducedMotion() ?? false;\n\n  return (\n    <span\n      role=\"status\"\n      aria-label={label}\n      className={cn(\n        \"inline-flex items-center justify-center text-foreground\",\n        className,\n      )}\n    >\n      {variant === \"spinner\" && <Spinner size={size} speed={speed} reduce={reduce} />}\n      {variant === \"dots\" && <Dots size={size} speed={speed} reduce={reduce} />}\n      {variant === \"bars\" && <Bars size={size} speed={speed} reduce={reduce} />}\n      {variant === \"dot-matrix\" && (\n        <DotMatrix size={size} speed={speed} reduce={reduce} />\n      )}\n      {variant === \"dither\" && <Dither size={size} speed={speed} reduce={reduce} />}\n      {ASCII_SETS[variant] && (\n        <Ascii frames={ASCII_SETS[variant]} size={size} speed={speed} reduce={reduce} />\n      )}\n      {variant === \"morph\" && (\n        <Morph size={size} speed={speed} reduce={reduce} label={label} />\n      )}\n      {variant === \"comet\" && <Comet size={size} speed={speed} reduce={reduce} />}\n      {variant === \"scramble\" && (\n        <Scramble\n          size={size}\n          speed={speed}\n          reduce={reduce}\n          target={t(\"scramble\")}\n        />\n      )}\n      {variant === \"metaballs\" && (\n        <Metaballs size={size} speed={speed} reduce={reduce} label={label} />\n      )}\n      {variant === \"newton\" && <Newton size={size} speed={speed} reduce={reduce} />}\n      {variant === \"helix\" && <Helix size={size} speed={speed} reduce={reduce} />}\n      {variant === \"percent\" && (\n        <Percent size={size} speed={speed} reduce={reduce} />\n      )}\n      <span className=\"sr-only\">{label}</span>\n    </span>\n  );\n}\n\ninterface PartProps {\n  size: number;\n  speed: number;\n  reduce: boolean;\n}\n\nfunction Spinner({ size, speed, reduce }: PartProps) {\n  const stroke = Math.max(2, size * 0.09);\n  const r = (size - stroke) / 2;\n  return (\n    <motion.svg\n      width={size}\n      height={size}\n      viewBox={`0 0 ${size} ${size}`}\n      animate={reduce ? REDUCED.animate : { rotate: 360 }}\n      transition={\n        reduce\n          ? REDUCED.transition\n          : { duration: speed, ease: \"linear\", repeat: Infinity }\n      }\n    >\n      <circle\n        cx={size / 2}\n        cy={size / 2}\n        r={r}\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeOpacity={0.2}\n        strokeWidth={stroke}\n      />\n      <path\n        d={`M ${size / 2} ${size / 2 - r} A ${r} ${r} 0 0 1 ${size / 2 + r} ${size / 2}`}\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth={stroke}\n        strokeLinecap=\"round\"\n      />\n    </motion.svg>\n  );\n}\n\nfunction Dots({ size, speed, reduce }: PartProps) {\n  const dot = size * 0.24;\n  return (\n    <span className=\"flex items-center\" style={{ gap: size * 0.14 }}>\n      {[0, 1, 2].map((i) => (\n        <motion.span\n          key={i}\n          className=\"rounded-full bg-current\"\n          style={{ width: dot, height: dot }}\n          animate={\n            reduce\n              ? { opacity: [0.4, 1, 0.4] }\n              : { y: [0, -size * 0.3, 0], opacity: [0.5, 1, 0.5] }\n          }\n          transition={{\n            duration: speed,\n            ease: EASE_IN_OUT,\n            repeat: Infinity,\n            delay: i * speed * 0.16,\n          }}\n        />\n      ))}\n    </span>\n  );\n}\n\nfunction Ascii({\n  frames,\n  size,\n  speed,\n  reduce,\n}: PartProps & { frames: string[] }) {\n  const [frame, setFrame] = useState(0);\n  useEffect(() => {\n    // Reduced motion slows the cycle rather than stopping it - it's a glyph\n    // swap, not on-screen movement.\n    const step = ((reduce ? speed * 2.5 : speed) / frames.length) * 1000;\n    const id = setInterval(\n      () => setFrame((f) => (f + 1) % frames.length),\n      step,\n    );\n    return () => clearInterval(id);\n  }, [frames.length, speed, reduce]);\n\n  return (\n    <span\n      className=\"font-mono leading-none tabular-nums\"\n      style={{ fontSize: size, lineHeight: 1 }}\n    >\n      {frames[frame % frames.length]}\n    </span>\n  );\n}\n\n// Each shape is sampled at the same number of points and emitted as an SVG\n// path with identical command structure, so framer tweens the `d` attribute\n// point-to-point - a real morph, not a snap. (clip-path polygon strings don't\n// interpolate reliably in framer, which left the shapes broken.)\nconst MORPH_POINTS = 24;\n\nfunction ngonRadius(ang: number, n: number, phase = 0) {\n  const seg = (2 * Math.PI) / n;\n  const a = ang - phase;\n  const local = (((a % seg) + seg) % seg) - seg / 2;\n  return Math.cos(Math.PI / n) / Math.cos(local);\n}\n\nfunction morphPath(radiusAt: (ang: number) => number) {\n  const parts: string[] = [];\n  for (let i = 0; i < MORPH_POINTS; i++) {\n    const ang = (i / MORPH_POINTS) * 2 * Math.PI - Math.PI / 2;\n    const r = Math.min(1.05, radiusAt(ang));\n    const x = (50 + Math.cos(ang) * 46 * r).toFixed(2);\n    const y = (50 + Math.sin(ang) * 46 * r).toFixed(2);\n    parts.push(`${i === 0 ? \"M\" : \"L\"}${x} ${y}`);\n  }\n  return `${parts.join(\" \")} Z`;\n}\n\nconst MORPH_PATHS = [\n  morphPath(() => 1), // circle\n  morphPath((a) => ngonRadius(a, 4, Math.PI / 4)), // square\n  morphPath((a) => ngonRadius(a, 3)), // triangle\n  morphPath((a) => ngonRadius(a, 6)), // hexagon\n  morphPath((a) => ngonRadius(a, 4)), // diamond\n];\n\n// Each shape appears twice in a row so it fully forms and HOLDS before the\n// next morph. Even keyframe spacing then alternates hold / morph segments.\nconst MORPH_SEQ = [...MORPH_PATHS.flatMap((p) => [p, p]), MORPH_PATHS[0]];\n// Rotation and scale only change across the morph segments, staying put on the\n// holds, so a settled shape sits still.\nconst MORPH_ROT = [0, 0, 72, 72, 144, 144, 216, 216, 288, 288, 360];\nconst MORPH_SCALE = [1, 1, 0.88, 0.88, 1, 1, 0.88, 0.88, 1, 1, 1];\n\nfunction Morph({ size, speed, reduce, label }: PartProps & { label: string }) {\n  return (\n    <motion.svg\n      width={size}\n      height={size}\n      viewBox=\"0 0 100 100\"\n      role=\"img\"\n      animate={\n        reduce\n          ? { opacity: [1, 0.4, 1] }\n          : { rotate: MORPH_ROT, scale: MORPH_SCALE }\n      }\n      transition={\n        reduce\n          ? { duration: 1.4, ease: EASE_IN_OUT, repeat: Infinity }\n          : { duration: speed * 5, ease: EASE_IN_OUT, repeat: Infinity }\n      }\n    >\n      <title>{label}</title>\n      <motion.path\n        fill=\"currentColor\"\n        d={MORPH_PATHS[0]}\n        // Seeds the motion value; without it motion writes d=\"undefined\"\n        // before the keyframes start.\n        initial={{ d: MORPH_PATHS[0] }}\n        animate={reduce ? undefined : { d: MORPH_SEQ }}\n        transition={\n          reduce\n            ? undefined\n            : { duration: speed * 5, ease: EASE_IN_OUT, repeat: Infinity }\n        }\n      />\n    </motion.svg>\n  );\n}\n\nconst COMET_TRAIL = [0, 1, 2, 3, 4, 5];\n\nfunction Comet({ size, speed, reduce }: PartProps) {\n  const head = size * 0.2;\n  const r = size / 2 - head / 2;\n  return (\n    <span className=\"relative\" style={{ width: size, height: size }}>\n      <motion.span\n        className=\"absolute inset-0\"\n        animate={reduce ? REDUCED.animate : { rotate: 360 }}\n        transition={\n          reduce\n            ? REDUCED.transition\n            : { duration: speed, ease: \"linear\", repeat: Infinity }\n        }\n      >\n        {COMET_TRAIL.map((i) => {\n          const scale = 1 - i * 0.13;\n          const sz = head * scale;\n          return (\n            <span\n              key={i}\n              className=\"absolute top-1/2 left-1/2 rounded-full bg-current\"\n              style={{\n                width: sz,\n                height: sz,\n                marginLeft: -sz / 2,\n                marginTop: -sz / 2,\n                opacity: 1 - i * 0.16,\n                transform: `rotate(${-i * 15}deg) translateY(${-r}px)`,\n              }}\n            />\n          );\n        })}\n      </motion.span>\n    </span>\n  );\n}\n\nconst SCRAMBLE_GLYPHS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>/*#@\";\n\nfunction Scramble({ size, speed, reduce, target }: PartProps & { target: string }) {\n  const [text, setText] = useState(target);\n  useEffect(() => {\n    if (reduce) {\n      setText(target);\n      return;\n    }\n    let tick = 0;\n    const total = target.length + 4;\n    const id = setInterval(\n      () => {\n        const reveal = tick % total;\n        let s = \"\";\n        for (let i = 0; i < target.length; i++) {\n          s +=\n            i < reveal\n              ? target[i]\n              : SCRAMBLE_GLYPHS[\n                  Math.floor(Math.random() * SCRAMBLE_GLYPHS.length)\n                ];\n        }\n        setText(s);\n        tick++;\n      },\n      (speed / target.length) * 1000 * 0.55,\n    );\n    return () => clearInterval(id);\n  }, [speed, reduce, target]);\n\n  return (\n    <span\n      className=\"font-mono font-medium tracking-[0.2em] tabular-nums\"\n      style={{ fontSize: size * 0.42 }}\n    >\n      {text}\n    </span>\n  );\n}\n\nfunction Metaballs({ size, speed, reduce, label }: PartProps & { label: string }) {\n  const id = useId().replace(/:/g, \"\");\n  return (\n    <svg width={size} height={size} viewBox=\"0 0 100 100\" role=\"img\">\n      <title>{label}</title>\n      <defs>\n        <filter id={id}>\n          <feGaussianBlur in=\"SourceGraphic\" stdDeviation=\"5\" result=\"b\" />\n          <feColorMatrix\n            in=\"b\"\n            values=\"1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 20 -8\"\n          />\n        </filter>\n      </defs>\n      <g filter={`url(#${id})`} fill=\"currentColor\">\n        <motion.circle\n          cy=\"50\"\n          r=\"15\"\n          // Seeds the motion value; without it motion writes cx=\"undefined\"\n          // before the keyframes start.\n          initial={{ cx: reduce ? 40 : 30 }}\n          animate={reduce ? { opacity: [0.4, 1, 0.4] } : { cx: [30, 70, 30] }}\n          transition={{ duration: speed * 1.6, ease: EASE_IN_OUT, repeat: Infinity }}\n        />\n        <motion.circle\n          cy=\"50\"\n          r=\"15\"\n          initial={{ cx: reduce ? 60 : 70 }}\n          animate={reduce ? { opacity: [0.4, 1, 0.4] } : { cx: [70, 30, 70] }}\n          transition={{ duration: speed * 1.6, ease: EASE_IN_OUT, repeat: Infinity }}\n        />\n      </g>\n    </svg>\n  );\n}\n\nconst NEWTON_BALLS = [0, 1, 2, 3, 4];\n\nfunction Newton({ size, speed, reduce }: PartProps) {\n  const d = size * 0.2;\n  const out = d * 1.1;\n  // Only the end balls move: the left slides out and back on the first half,\n  // then the right on the second half - the impact appears to jump the three\n  // still middle balls. Pure horizontal slide, no swing, no strings.\n  const moves: Record<number, { x: number[]; times: number[] }> = {\n    0: { x: [0, -out, 0, 0], times: [0, 0.28, 0.5, 1] },\n    4: { x: [0, 0, out, 0], times: [0, 0.5, 0.78, 1] },\n  };\n\n  return (\n    <span className=\"flex items-center justify-center\" style={{ height: d }}>\n      {NEWTON_BALLS.map((i) => {\n        const move = moves[i];\n        return (\n          <motion.span\n            key={i}\n            className=\"rounded-full bg-current\"\n            style={{ width: d, height: d }}\n            animate={reduce || !move ? undefined : { x: move.x }}\n            transition={\n              reduce || !move\n                ? undefined\n                : {\n                    duration: speed * 1.5,\n                    ease: EASE_IN_OUT,\n                    repeat: Infinity,\n                    times: move.times,\n                  }\n            }\n          />\n        );\n      })}\n    </span>\n  );\n}\n\nfunction Helix({ size, speed, reduce }: PartProps) {\n  const rows = 7;\n  const dot = size * 0.14;\n  const amp = size * 0.32;\n  return (\n    <span className=\"relative\" style={{ width: size, height: size }}>\n      {Array.from({ length: rows }, (_, r) => {\n        const top = (r / (rows - 1)) * (size - dot);\n        const delay = (r / rows) * speed;\n        return (\n          <span key={`row-${top}`}>\n            <motion.span\n              className=\"absolute rounded-full bg-current\"\n              style={{ width: dot, height: dot, left: size / 2 - dot / 2, top }}\n              animate={\n                reduce\n                  ? { opacity: [0.4, 1, 0.4] }\n                  : {\n                      x: [amp, -amp, amp],\n                      scale: [1, 0.5, 1],\n                      opacity: [1, 0.45, 1],\n                    }\n              }\n              transition={{\n                duration: speed,\n                ease: EASE_IN_OUT,\n                repeat: Infinity,\n                delay,\n              }}\n            />\n            <motion.span\n              className=\"absolute rounded-full bg-current\"\n              style={{ width: dot, height: dot, left: size / 2 - dot / 2, top }}\n              animate={\n                reduce\n                  ? { opacity: [0.4, 1, 0.4] }\n                  : {\n                      x: [-amp, amp, -amp],\n                      scale: [0.5, 1, 0.5],\n                      opacity: [0.45, 1, 0.45],\n                    }\n              }\n              transition={{\n                duration: speed,\n                ease: EASE_IN_OUT,\n                repeat: Infinity,\n                delay,\n              }}\n            />\n          </span>\n        );\n      })}\n    </span>\n  );\n}\n\nfunction Percent({ size, speed, reduce }: PartProps) {\n  const [p, setP] = useState(0);\n  useEffect(() => {\n    const dur = (reduce ? speed * 2 : speed) * 1000;\n    const start = { t: 0 };\n    const tickMs = 40;\n    const id = setInterval(() => {\n      start.t += tickMs;\n      const next = Math.min(100, Math.round((start.t / dur) * 100));\n      setP(next);\n      if (next >= 100) start.t = 0;\n    }, tickMs);\n    return () => clearInterval(id);\n  }, [speed, reduce]);\n\n  return (\n    <span\n      className=\"flex flex-col items-center\"\n      style={{ gap: size * 0.14, width: size * 1.4 }}\n    >\n      <span\n        className=\"font-mono font-medium tabular-nums\"\n        style={{ fontSize: size * 0.42, lineHeight: 1 }}\n      >\n        {p}%\n      </span>\n      <span\n        className=\"w-full overflow-hidden rounded-full bg-current/15\"\n        style={{ height: Math.max(3, size * 0.1) }}\n      >\n        <span\n          className=\"block h-full rounded-full bg-current\"\n          style={{ width: `${p}%` }}\n        />\n      </span>\n    </span>\n  );\n}\n\nfunction Bars({ size, speed, reduce }: PartProps) {\n  const bar = size * 0.16;\n  return (\n    <span className=\"flex items-center\" style={{ gap: size * 0.1, height: size }}>\n      {[0, 1, 2, 3].map((i) => (\n        <motion.span\n          key={i}\n          className=\"rounded-full bg-current\"\n          style={{ width: bar, height: size, originY: 1 }}\n          animate={\n            reduce ? { opacity: [0.4, 1, 0.4] } : { scaleY: [0.3, 1, 0.3] }\n          }\n          transition={{\n            duration: speed,\n            ease: EASE_IN_OUT,\n            repeat: Infinity,\n            delay: i * speed * 0.12,\n          }}\n        />\n      ))}\n    </span>\n  );\n}\n\nfunction DotMatrix({ size, speed, reduce }: PartProps) {\n  const n = 3;\n  const gap = size * 0.14;\n  const dot = (size - gap * (n - 1)) / n;\n  const cells = Array.from({ length: n * n }, (_, idx) => idx);\n  return (\n    <span\n      className=\"grid\"\n      style={{\n        gap,\n        gridTemplateColumns: `repeat(${n}, ${dot}px)`,\n      }}\n    >\n      {cells.map((idx) => {\n        const x = idx % n;\n        const y = Math.floor(idx / n);\n        // Diagonal wave: cells light in order of their distance from the corner.\n        const delay = ((x + y) / (2 * (n - 1))) * speed;\n        return (\n          <motion.span\n            key={idx}\n            className=\"rounded-full bg-current\"\n            style={{ width: dot, height: dot }}\n            animate={\n              reduce\n                ? { opacity: [0.3, 1, 0.3] }\n                : { opacity: [0.2, 1, 0.2], scale: [0.7, 1, 0.7] }\n            }\n            transition={{\n              duration: speed,\n              ease: EASE_IN_OUT,\n              repeat: Infinity,\n              delay,\n            }}\n          />\n        );\n      })}\n    </span>\n  );\n}\n\n// Ordered Bayer 4x4 matrix - the classic dithering threshold pattern. Cells\n// light in this order, so the fill shimmers like a dissolving halftone.\nconst BAYER_4 = [\n  0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5,\n];\n\nfunction Dither({ size, speed, reduce }: PartProps) {\n  const n = 4;\n  const gap = Math.max(1, size * 0.05);\n  const cell = (size - gap * (n - 1)) / n;\n  return (\n    <span\n      className=\"grid\"\n      style={{ gap, gridTemplateColumns: `repeat(${n}, ${cell}px)` }}\n    >\n      {BAYER_4.map((order, idx) => (\n        <motion.span\n          // biome-ignore lint/suspicious/noArrayIndexKey: fixed matrix cells, order never changes\n          key={idx}\n          className=\"bg-current\"\n          style={{ width: cell, height: cell }}\n          animate={reduce ? { opacity: [0.3, 1, 0.3] } : { opacity: [0.1, 1, 0.1] }}\n          transition={{\n            duration: speed,\n            ease: EASE_IN_OUT,\n            repeat: Infinity,\n            delay: (order / BAYER_4.length) * speed,\n          }}\n        />\n      ))}\n    </span>\n  );\n}\n"},{"path":"components/motion/text-scramble.tsx","type":"util","content":"\"use client\";\n\nimport { useReducedMotion } from \"motion/react\";\nimport {\n  useEffect,\n  useRef,\n  useState,\n  type CSSProperties,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nconst DEFAULT_GLYPHS = \"ABCDEFGHJKLMNPQRSTUVWXYZ0123456789#%&@$?/\";\n\nexport interface TextScrambleProps {\n  /** Final text revealed by the scramble animation. */\n  text: string;\n  /** Maximum animation duration in milliseconds. */\n  duration?: number;\n  /** Characters sampled while unresolved positions are scrambling. */\n  glyphs?: string;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Inline styles for the root element. */\n  style?: CSSProperties;\n}\n\n/** Character scramble that resolves to `text` and respects reduced motion. */\nexport function TextScramble({\n  text,\n  duration,\n  glyphs = DEFAULT_GLYPHS,\n  className,\n  style,\n}: TextScrambleProps) {\n  const reduce = useReducedMotion() ?? false;\n  const [display, setDisplay] = useState(text);\n  const mounted = useRef(false);\n\n  useEffect(() => {\n    if (!mounted.current) {\n      mounted.current = true;\n      setDisplay(text);\n      return;\n    }\n\n    if (reduce || !glyphs) {\n      setDisplay(text);\n      return;\n    }\n\n    const characters = text.split(\"\");\n    const startedAt = performance.now();\n    const animationDuration = duration\n      ?? Math.min(760, Math.max(420, characters.length * 32));\n    let frame = 0;\n    let lastUpdate = 0;\n\n    const animate = (now: number) => {\n      if (now - lastUpdate >= 40) {\n        lastUpdate = now;\n        const progress = Math.min((now - startedAt) / animationDuration, 1);\n        const settled = Math.floor(progress * characters.length);\n        setDisplay(characters.map((character, index) => {\n          if (index < settled || character === \" \") return character;\n          return glyphs[Math.floor(Math.random() * glyphs.length)];\n        }).join(\"\"));\n      }\n\n      if (now - startedAt < animationDuration) {\n        frame = requestAnimationFrame(animate);\n      } else {\n        setDisplay(text);\n      }\n    };\n\n    frame = requestAnimationFrame(animate);\n    return () => cancelAnimationFrame(frame);\n  }, [duration, glyphs, reduce, text]);\n\n  return (\n    <span className={cn(\"inline-block whitespace-pre\", className)} style={style}>\n      <span className=\"sr-only\">{text}</span>\n      <span aria-hidden=\"true\">{reduce ? text : display}</span>\n    </span>\n  );\n}\n"}]}